adam-agent-server 1.3.0 → 1.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/README.md +22 -9
- package/dist/App-JGH6G5US.js +13 -0
- package/dist/adam-tools-W5AOIGEQ.js +1 -0
- package/dist/{approval-handler-RIJO3OBO.js → approval-handler-ORD4MUVM.js} +1 -1
- package/dist/audit-manager-YCJT2WP5.js +1 -0
- package/dist/bree-engine-R5YLSDCL.js +1 -0
- package/dist/{channels-LUJ7GTSP.js → channels-HYSB2EEK.js} +1 -1
- package/dist/channels-JCMPPQED.js +1 -0
- package/dist/{chunk-CLHSPXZ6.js → chunk-23VZKIB6.js} +1 -1
- package/dist/{chunk-AZBNUSM2.js → chunk-2DLVAKH7.js} +1 -1
- package/dist/chunk-2YAP4YJV.js +57 -0
- package/dist/{chunk-YPOTHL7X.js → chunk-5S6BMWD2.js} +1 -1
- package/dist/chunk-5XUR3M23.js +12 -0
- package/dist/chunk-6775OYXA.js +47 -0
- package/dist/chunk-6FXNB7NE.js +1 -0
- package/dist/{chunk-WKS7QVIX.js → chunk-7L2WQM7N.js} +1 -1
- package/dist/{chunk-NDP6LWXX.js → chunk-BR2JY5X2.js} +1 -1
- package/dist/{chunk-IZGTTLTG.js → chunk-C6BOQJJF.js} +1 -1
- package/dist/{chunk-4NW2DNDZ.js → chunk-DZEVMYPB.js} +1 -1
- package/dist/chunk-GBTG5B5R.js +8 -0
- package/dist/chunk-GY52JA5I.js +10 -0
- package/dist/{chunk-HFN7Y3IM.js → chunk-H54ZXA26.js} +1 -1
- package/dist/{chunk-DBUEHITK.js → chunk-H7VDC6FY.js} +2 -2
- package/dist/{chunk-ZQYKT5UY.js → chunk-HDP7A4XY.js} +1 -1
- package/dist/{chunk-4LSIHSCO.js → chunk-HTPUEIFT.js} +1 -1
- package/dist/{chunk-JZNBFZ7W.js → chunk-ISZJV72D.js} +1 -1
- package/dist/{chunk-4MJF77RD.js → chunk-JAS3TUZX.js} +4 -3
- package/dist/chunk-MTWLLE26.js +49 -0
- package/dist/{chunk-NUTUI5KM.js → chunk-QVKI7H7W.js} +1 -1
- package/dist/{chunk-7IXLL673.js → chunk-QWCRZDZS.js} +1 -1
- package/dist/{chunk-P6KWAGAY.js → chunk-R4GIIQ7G.js} +1 -1
- package/dist/chunk-RAW263MQ.js +99 -0
- package/dist/{chunk-IKUBP3SY.js → chunk-S3BAIZ4Q.js} +2 -2
- package/dist/chunk-VRJ7R766.js +1 -0
- package/dist/{chunk-WTRM5VO7.js → chunk-XL46AGRZ.js} +2 -2
- package/dist/{chunk-AKPLOO2V.js → chunk-Y3AMO6WC.js} +1 -1
- package/dist/{chunk-TCHBOWQ5.js → chunk-YVS565QY.js} +1 -1
- package/dist/{chunk-TKDT7EQO.js → chunk-Z4D3L2HR.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{config-HR4MBTIS.js → config-EMNKHR3W.js} +1 -1
- package/dist/{db-6KUGCGVR.js → db-YUYXVV3A.js} +1 -1
- package/dist/{delivery-log-7DJJTPXL.js → delivery-log-VKONLSVD.js} +1 -1
- package/dist/engine-BM5BMPIC.js +1 -0
- package/dist/{evolution-audit-I2ITWAEC.js → evolution-audit-LZSQPDHH.js} +1 -1
- package/dist/index.js +18 -12
- package/dist/{learner-CBPQZ3HL.js → learner-IJN6B7KV.js} +1 -1
- package/dist/{memories-HBBW44MG.js → memories-ZII5QSTJ.js} +1 -1
- package/dist/{memory-extractor-XO2HJ22Y.js → memory-extractor-DIYJFBCI.js} +2 -2
- package/dist/memory-service-QMYJPBAE.js +1 -0
- package/dist/outbound-gateway-6K6P2BEH.js +1 -0
- package/dist/role-presets-K2BDRZBS.js +1 -0
- package/dist/roles-L34L5MK3.js +1 -0
- package/dist/{session-manager-JICVE4CO.js → session-manager-GRJ3FV3L.js} +1 -1
- package/dist/{task-templates-NC7XIZIC.js → task-templates-23YOAF3E.js} +1 -1
- package/dist/workflow-executor-JTUWX5DC.js +1 -0
- package/package.json +2 -2
- package/web/dist/assets/AlertDialog-r3y6IhpW.js +51 -0
- package/web/dist/assets/Button-BjXgrQ95.js +1 -0
- package/web/dist/assets/Card-C153tGfJ.js +1 -0
- package/web/dist/assets/ChannelDetail-C2uAZv1u.js +1 -0
- package/web/dist/assets/Channels-C62Qrg-n.js +12 -0
- package/web/dist/assets/Chat-kH2owmB_.js +1 -0
- package/web/dist/assets/Dashboard-BhD8SpFb.js +1 -0
- package/web/dist/assets/EmptyState-CXwJFCDQ.js +1 -0
- package/web/dist/assets/EnvVarEditor-GSapLD96.js +1 -0
- package/web/dist/assets/Evolution-BO5hysLD.js +6 -0
- package/web/dist/assets/GoalDetail-cxa8OvEi.js +1 -0
- package/web/dist/assets/Goals-Dz3qqp_l.js +1 -0
- package/web/dist/assets/Logs-Ckp3-hYV.js +1 -0
- package/web/dist/assets/Memories-DEuSRoP3.js +1 -0
- package/web/dist/assets/NotFound-Bvn39vSk.js +1 -0
- package/web/dist/assets/PageHeader-BMvN0xiB.js +1 -0
- package/web/dist/assets/Plugins-CRym22JF.js +1 -0
- package/web/dist/assets/RoleDetail-BWMjP9aZ.js +33 -0
- package/web/dist/assets/Roles-DD7NBDku.js +1 -0
- package/web/dist/assets/SectionHeader-CiCj3Is0.js +1 -0
- package/web/dist/assets/Settings-BlU19KuR.js +1 -0
- package/web/dist/assets/Strategies-CJ_q94-v.js +1 -0
- package/web/dist/assets/Switch-CoUUy5jr.js +1 -0
- package/web/dist/assets/Table-CaFJieh_.js +1 -0
- package/web/dist/assets/TaskDetail-DVrjU-E6.js +2 -0
- package/web/dist/assets/Work-BMl61RRi.js +1 -0
- package/web/dist/assets/dist-Bdqp1ixJ.js +1 -0
- package/web/dist/assets/index-DcXMQByM.css +2 -0
- package/web/dist/assets/index-pF--tN9F.js +2 -0
- package/web/dist/assets/ui-B_uMx2Fy.js +1 -0
- package/web/dist/assets/useIsMobileLayout-Bwrm84kJ.js +1 -0
- package/web/dist/assets/vendor-icons-BlMaTTx3.js +1 -0
- package/web/dist/assets/{vendor-react-DLRtONKt.js → vendor-react-7e01TWy7.js} +2 -2
- package/web/dist/assets/vendor-state-Bj70wnRm.js +1 -0
- package/web/dist/index.html +8 -6
- package/dist/App-3OBJDI2C.js +0 -9
- package/dist/adam-tools-4LZYFB6J.js +0 -1
- package/dist/audit-manager-6FFPXID3.js +0 -1
- package/dist/bree-engine-2NOTIBAZ.js +0 -1
- package/dist/channels-TSZLEU3L.js +0 -1
- package/dist/chunk-6NUHSHS5.js +0 -4
- package/dist/chunk-72VLUJ2S.js +0 -1
- package/dist/chunk-7CJGPCSJ.js +0 -49
- package/dist/chunk-NLD7WK3R.js +0 -6
- package/dist/chunk-OTH4M5L3.js +0 -8
- package/dist/chunk-PVYEGQEG.js +0 -83
- package/dist/chunk-XTHP5JMO.js +0 -10
- package/dist/chunk-ZKMDHQJY.js +0 -104
- package/dist/engine-HJUE6I4I.js +0 -1
- package/dist/memory-service-HIFTKEW2.js +0 -1
- package/dist/outbound-gateway-GGFMU5JW.js +0 -1
- package/dist/role-presets-W452Y3RV.js +0 -1
- package/dist/roles-NYGWZMQI.js +0 -1
- package/dist/workflow-executor-QN4KP7B4.js +0 -1
- package/web/dist/assets/Card-4mOZntHG.js +0 -1
- package/web/dist/assets/ChannelDetail-DX4QnE8j.js +0 -1
- package/web/dist/assets/Channels-EXkNOQpB.js +0 -12
- package/web/dist/assets/Chat-Da-mCR0c.js +0 -1
- package/web/dist/assets/Dashboard-Bq6sEDdP.js +0 -1
- package/web/dist/assets/EmptyState-BlgMMAr-.js +0 -1
- package/web/dist/assets/EnvVarEditor-CNxXpVbD.js +0 -1
- package/web/dist/assets/Evolution-DPdmbooj.js +0 -6
- package/web/dist/assets/GoalDetail-BamCfVzS.js +0 -1
- package/web/dist/assets/Goals-CHPEg0RK.js +0 -1
- package/web/dist/assets/Logs-BHkBvH0T.js +0 -1
- package/web/dist/assets/Memories-BY2pJhVd.js +0 -1
- package/web/dist/assets/NotFound-CSjhzSGa.js +0 -1
- package/web/dist/assets/Plugins-C5xLM0BU.js +0 -1
- package/web/dist/assets/RoleDetail-Dnp-W14x.js +0 -33
- package/web/dist/assets/Roles-BVOVoHvc.js +0 -1
- package/web/dist/assets/Settings-eBHvn6s_.js +0 -1
- package/web/dist/assets/Strategies-BbFbLKBJ.js +0 -1
- package/web/dist/assets/Switch-Q-inggPs.js +0 -1
- package/web/dist/assets/Table-BxbnOSbq.js +0 -1
- package/web/dist/assets/TaskDetail-BEjZ1gco.js +0 -2
- package/web/dist/assets/Work-CF2iLs8i.js +0 -1
- package/web/dist/assets/dist-HyCSN_hp.js +0 -1
- package/web/dist/assets/index-CaHdOfAc.js +0 -52
- package/web/dist/assets/index-D0SvKqKc.css +0 -2
- package/web/dist/assets/vendor-icons-CkI4-NxL.js +0 -1
- package/web/dist/assets/vendor-state-B_-GdGNJ.js +0 -1
- /package/web/dist/assets/{format-DvtQjPZn.js → format-CHfBBLog.js} +0 -0
package/dist/App-3OBJDI2C.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{b as T,d as jt,e as Ro}from"./chunk-VRP4LTHY.js";import{a as Ht,f as Ao,h as Do}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as Ft,Text as Pt,useInput as ls}from"ink";import{useState as cs,useEffect as so,useRef as wo}from"react";import{createContext as Dr,useContext as Rr,useReducer as Mr}from"react";import{jsx as _r}from"react/jsx-runtime";var Nr={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null,version:null};function Lr(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};case"SET_VERSION":return{...e,version:t.version};default:return e}}var Mo=Dr(null);function No({children:e}){let[t,o]=Mr(Lr,Nr);return _r(Mo.Provider,{value:{state:t,dispatch:o},children:e})}function st(){let e=Rr(Mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Lo,useRef as _o}from"react";var Vr=15e3;function Vo(){let{state:e,dispatch:t}=st(),o=_o(null),c=_o(null);Lo(()=>{c.current=e.session?.id??null},[e.session?.id]),Lo(()=>{let u=!0,m=null,l=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{l(),o.current=setTimeout(()=>{u&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Vr)};return(()=>{try{m=new jt("/events"),m.on("task_status_change",()=>{}),m.on("approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:a.taskId,approvalId:a.approvalId,toolName:a.toolName,toolInput:a.toolInput,matchedPattern:a.matchedPattern}})}),m.on("plan_approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:a.taskId,planId:a.planId,roleId:a.roleId,plan:a.plan}})}),m.on("plan_approval_decision",()=>{u&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),m.on("config_changed",()=>{u&&t({type:"CONFIG_CHANGED"})}),m.on("execution_task_start",r=>{if(!u)return;let a=r,d=c.current;d&&(async()=>{try{let C=await T(`/tasks/${a.taskId}`);u&&C.sourceSessionId===d&&t({type:"SET_ACTIVE_TASK",taskId:a.taskId})}catch{}})()}),m.on("stats_update",r=>{if(!u)return;let a=r;t({type:"UPDATE_STATS",activeTasks:a.activeTasks,queuedTasks:a.queuedTasks,costToday:a.totalCostToday})}),m.connect().then(async()=>{if(u){l(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await T("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{u&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{u&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{u=!1,l(),m?.close()}},[t])}import{useEffect as $r,useRef as Or,useState as $o,useCallback as qr}from"react";function Oo(e){let[t,o]=$o([]),[c,u]=$o(!1),m=Or(null),l=qr(()=>{o([]),u(!1)},[]);return $r(()=>{if(!e)return;let i=!0;o([]),u(!0);try{let n=new Ro(e);return m.current=n,n.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(C=>{let p=C[C.length-1];if(p?.type==="reasoning"){let b=[...C];return b[b.length-1]={...p,content:p.content+d},b}return[...C,{type:"reasoning",content:d,timestamp:Date.now()}]})}),n.on("tool_call",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_call",content:a.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:a.toolName}}])}),n.on("tool_result",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_result",content:a.content??"",timestamp:Date.now()}])}),n.on("error",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"error",content:a.error??"unknown error",timestamp:Date.now()}])}),n.on("complete",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"complete",content:a.result??"",timestamp:Date.now(),metadata:{cost:a.costUsd,turns:a.numTurns,duration:a.totalDurationMs}}]),u(!1)}),n.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),u(!1))}),()=>{i=!1,n.close()}}catch{u(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as io,useEffect as Fr,useCallback as Dt}from"react";function ao(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function qo(){let[e,t]=io(null),[o,c]=io(!0),[u,m]=io(null),l=Dt(async()=>{try{let C=(await T("/chat/sessions?status=active")).sessions.find(p=>p.source.type==="tui");return C?ao(C):null}catch{return null}},[]),i=Dt(async()=>{try{let d=await T("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),C=ao(d.session);return t(C),C}catch{return m("Failed to create session"),null}},[]),n=Dt(async d=>{try{let C=await T("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(p=>p&&{...p,messageCount:p.messageCount+1,lastActiveAt:Date.now()}),C}catch{return null}},[]),r=Dt(async()=>{if(!e)return!1;try{return await T(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),a=Dt(async()=>{if(e)try{let d=await T(`/chat/sessions/${e.id}`);t(ao(d.session))}catch{t(null)}},[e]);return Fr(()=>{let d=!1;async function C(){c(!0);let p=await l();d||(p?t(p):await i(),d||c(!1))}return C(),()=>{d=!0}},[]),{session:e,loading:o,error:u,sendMessage:n,createNewSession:i,archiveCurrentSession:r,refreshSession:a,setSession:t}}import{useEffect as Fo,useRef as Ur,useState as Wr}from"react";function Uo(e){let[t,o]=Wr(null),c=Ur(new Set);return Fo(()=>{if(!e)return;let u=!0,m=null;try{m=new jt("/chat/stream"),m.on("chat_message",l=>{if(!u)return;let n=l.message;n&&n.sessionId===e&&n.role==="assistant"&&(c.current.has(n.id)||(c.current.add(n.id),o(n)))}),m.connect().catch(()=>{})}catch{}return()=>{u=!1,m?.close()}},[e]),Fo(()=>{c.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as co,Text as _e}from"ink";import Le from"chalk";var lo={connected:Le.green,disconnected:Le.red,warning:Le.yellow,reasoning:Le.gray,toolCall:Le.blue,toolResult:Le.green,error:Le.red,dim:Le.dim,bold:Le.bold,statusUp:Le.green("\u25CF"),statusDown:Le.red("\u25CF")};import{Fragment as Gr,jsx as ut,jsxs as it}from"react/jsx-runtime";function Wo(){let{state:e}=st(),t=e.connected?`${lo.statusUp} Server: up`:`${lo.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,m=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return it(co,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[it(co,{children:[ut(_e,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ut(_e,{children:" \u2502 "}),ut(_e,{children:t}),ut(_e,{children:" \u2502 "}),it(_e,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&it(Gr,{children:[ut(_e,{children:" \u2502 "}),it(_e,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),m&&ut(_e,{color:"yellow",children:" timeout soon"})]})]}),it(co,{children:[it(_e,{children:["Tasks: ",o]}),ut(_e,{children:" \u2502 "}),it(_e,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Kt,Text as zt,useInput as jr}from"ink";import{useState as mo,useMemo as Kr}from"react";import zr from"ink-text-input";var Hr=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function uo(e){let t=e.toLowerCase();return Hr.filter(o=>o.name.startsWith(t))}function Go(e){let t=uo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Qt,jsxs as Rt}from"react/jsx-runtime";function Ho({onSubmit:e}){let[t,o]=mo(""),[c,u]=mo(0),[m,l]=mo(!1),i=t.startsWith("/")&&t.length>=1,n=t.slice(1),r=Kr(()=>i?uo(n):[],[i,n]),a=p=>{o(p),p.startsWith("/")?(l(!0),u(0)):l(!1)},d=()=>{let p=t.trim();if(p){if(p.startsWith("/")){let b=p.slice(1),s=Go(b);e(s?`/${s.name}`:p)}else e(p);o(""),l(!1)}},C=p=>{e(`/${p.name}`),o(""),l(!1)};return jr((p,b)=>{if(!(!m||!i||r.length===0)){if(b.upArrow){u(s=>s<=0?r.length-1:s-1);return}if(b.downArrow){u(s=>s>=r.length-1?0:s+1);return}if(b.tab){let s=r[c];s&&C(s);return}if(b.escape){l(!1),o("");return}}},{isActive:m&&i&&r.length>0}),Rt(Kt,{flexDirection:"column",children:[m&&i&&r.length>0&&Qt(Kt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((p,b)=>{let s=b===c;return Rt(Kt,{children:[Qt(zt,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),Rt(zt,{color:s?"cyan":"white",bold:s,children:["/",p.name]}),Rt(zt,{dimColor:!0,children:[" \u2014 ",p.description]})]},p.name)})}),Rt(Kt,{borderStyle:"round",borderDimColor:!0,children:[Qt(zt,{bold:!0,children:"\u25B8 "}),Qt(zr,{value:t,onChange:a,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as ht,Text as Ce}from"ink";import{useState as Qr}from"react";import{jsx as Ae,jsxs as We}from"react/jsx-runtime";function Xr({content:e}){let[t,o]=Qr(!1),c=e.split(`
|
|
2
|
-
`);return c.length<=5?Ae(Ce,{color:"green",children:e}):t?Ae(Ce,{color:"green",children:e}):We(Ce,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
-
`),`
|
|
4
|
-
`,We(Ce,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function Yr({event:e}){switch(e.type){case"reasoning":return Ae(ht,{children:Ae(Ce,{color:"gray",children:e.content})});case"tool_call":return Ae(ht,{children:We(Ce,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return We(ht,{flexDirection:"column",children:[Ae(Ce,{color:"blue",dimColor:!0,children:"[result]"}),Ae(Xr,{content:e.content})]});case"error":return Ae(ht,{children:We(Ce,{color:"red",children:["[error] ",e.content]})});case"complete":return We(ht,{flexDirection:"column",marginTop:1,children:[e.content&&Ae(Ce,{children:e.content}),Ae(Ce,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&We(Ce,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&We(Ce,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&We(Ce,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function jo({events:e,isStreaming:t}){return e.length===0&&!t?null:We(ht,{flexDirection:"column",children:[t&&e.length===0&&Ae(Ce,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>Ae(Yr,{event:o},c))]})}import{Box as Ko,Text as zo}from"ink";import{jsx as go,jsxs as Jr}from"react/jsx-runtime";function Qo({messages:e}){return e.length===0?null:go(Ko,{flexDirection:"column",children:e.map((t,o)=>Jr(Ko,{flexDirection:"column",marginBottom:1,children:[go(zo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),go(zo,{children:t.content})]},o))})}import{Box as Mt,Text as Ge,useInput as Zr}from"ink";import{jsx as He,jsxs as Nt}from"react/jsx-runtime";function Xo({approval:e,onResolved:t}){return Zr(o=>{o==="a"?T(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&T(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Nt(Mt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[He(Ge,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Nt(Mt,{marginTop:1,children:[He(Ge,{children:"Tool: "}),He(Ge,{bold:!0,children:e.toolName})]}),Nt(Mt,{children:[He(Ge,{children:"Input: "}),He(Ge,{children:JSON.stringify(e.toolInput)})]}),Nt(Mt,{children:[He(Ge,{children:"Pattern: "}),He(Ge,{dimColor:!0,children:e.matchedPattern})]}),Nt(Mt,{marginTop:1,children:[He(Ge,{color:"green",children:"[a] Approve"}),He(Ge,{children:" "}),He(Ge,{color:"red",children:"[r] Reject"})]})]})}import{Box as Lt,Text as he,useInput as en}from"ink";import{useState as tn,useEffect as on}from"react";import{jsx as Ye,jsxs as Ve}from"react/jsx-runtime";var rn=300;function Yo({approval:e,onResolved:t,onTimeout:o}){let[c,u]=tn(rn);on(()=>{let l=setInterval(()=>{u(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),en(l=>{l==="a"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let m=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ve(Lt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Ye(he,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ve(he,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ve(he,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ve(Lt,{marginTop:1,children:[Ye(he,{children:"Overall Risk: "}),Ye(he,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),Ve(he,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return Ve(Lt,{paddingLeft:2,children:[Ve(he,{children:["[",l.index,"] "]}),Ye(he,{children:l.description}),Ve(he,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ve(he,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ve(Lt,{marginTop:1,children:[Ye(he,{dimColor:!0,children:"Permissions: "}),Ye(he,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ve(Lt,{marginTop:1,children:[Ye(he,{color:"green",children:"[a] Allow once "}),Ye(he,{color:"green",children:"[p] Allow permanent "}),Ye(he,{color:"red",children:"[r] Deny"})]})]})}import{Box as mt,Text as ae,useInput as an}from"ink";import{useEffect as ln,useState as Je,useCallback as Zo}from"react";import{Box as oe,Text as _,useInput as nn}from"ink";import{useState as fo,useEffect as sn}from"react";import{jsx as U,jsxs as K}from"react/jsx-runtime";function Jo({taskId:e,onBack:t}){let[o,c]=fo(null),[u,m]=fo([]),[l,i]=fo(null);if(sn(()=>{T(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),T(`/tasks/${e}/plan`).then(r=>m(r.plans)).catch(()=>m([]))},[e]),nn((r,a)=>{(r==="b"||a.escape)&&t()}),l)return K(oe,{flexDirection:"column",children:[K(_,{color:"red",children:["Error: ",l]}),U(_,{dimColor:!0,children:"[b] Back"})]});if(!o)return K(_,{dimColor:!0,children:["Loading task ",e,"..."]});let n=u[0];return K(oe,{flexDirection:"column",children:[U(_,{bold:!0,color:"cyan",children:"Task Detail"}),K(oe,{marginTop:1,flexDirection:"column",children:[K(oe,{children:[U(_,{children:"ID: "}),U(_,{dimColor:!0,children:String(o.id)})]}),K(oe,{children:[U(_,{children:"Status: "}),U(_,{bold:!0,children:String(o.status)})]}),K(oe,{children:[U(_,{children:"Prompt: "}),U(_,{children:String(o.prompt)})]}),o.result?K(oe,{children:[U(_,{children:"Result: "}),U(_,{children:String(o.result).slice(0,200)})]}):null,o.error?K(oe,{children:[U(_,{color:"red",children:"Error: "}),U(_,{children:String(o.error)})]}):null,o.deliverTo?.length?K(oe,{children:[U(_,{children:"DeliverTo: "}),U(_,{dimColor:!0,children:o.deliverTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null,o.reportTo?.length?K(oe,{children:[U(_,{children:"ReportTo: "}),U(_,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),n&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"cyan",children:"Execution Plan"}),K(oe,{children:[U(_,{children:"Plan ID: "}),U(_,{dimColor:!0,children:n.id})]}),K(oe,{children:[U(_,{children:"Status: "}),U(_,{children:n.status})]}),n.plan.overallRisk&&K(oe,{children:[U(_,{children:"Overall Risk: "}),U(_,{bold:!0,color:n.plan.overallRisk==="high"?"red":n.plan.overallRisk==="medium"?"yellow":"green",children:n.plan.overallRisk.toUpperCase()})]}),K(_,{bold:!0,children:["Steps (",n.plan.steps.length,"):"]}),n.plan.steps.map(r=>{let a=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return K(oe,{paddingLeft:2,children:[K(_,{children:["[",r.index,"] ",r.description]}),K(_,{color:a,children:[" [",r.riskLevel,"]"]})]},r.index)}),n.deviationReport&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"yellow",children:"Deviation Report"}),K(_,{children:["Planned: ",n.deviationReport.stepsPlanned," | Executed: ",n.deviationReport.stepsExecuted," | Accuracy: ",(n.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),n.deviationReport.deviations.map((r,a)=>K(oe,{paddingLeft:2,children:[K(_,{color:"yellow",children:["[",r.deviationType,"] "]}),K(_,{children:["Step ",r.stepIndex,": ",r.actual]})]},a))]}),n.learnedRules&&n.learnedRules.length>0&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"blue",children:"Learned Rules"}),n.learnedRules.map((r,a)=>U(oe,{paddingLeft:2,children:K(_,{children:["* ",r]})},a))]})]}),!n&&u.length===0&&U(oe,{marginTop:1,children:U(_,{dimColor:!0,children:"No execution plan for this task."})}),U(oe,{marginTop:1,children:U(_,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as un,jsx as ye,jsxs as Ie}from"react/jsx-runtime";var cn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Xt=["all","pending","queued","running","completed","failed","cancelled"],po=15;function Yt({onBack:e}){let[t,o]=Je([]),[c,u]=Je(!0),[m,l]=Je("list"),[i,n]=Je(0),[r,a]=Je("all"),[d,C]=Je(0),[p,b]=Je(0),[s,g]=Je(null),[V,N]=Je([]),Z=Zo(async()=>{u(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let k=await T(`/tasks?${I}`);o(k.tasks)}catch{o([])}finally{u(!1)}},[r]);ln(()=>{Z()},[Z]);let j=Math.max(1,Math.ceil(t.length/po)),q=t.slice(p*po,(p+1)*po),de=Zo(async()=>{let I=q[i];if(I)try{await T(`/tasks/${I.id}/cancel`,{method:"POST"}),g(`Cancelled: ${I.id.slice(0,8)}`),l("list"),Z()}catch(k){g(`Failed: ${k instanceof Error?k.message:String(k)}`),l("list")}},[q,i,Z]);return an((I,k)=>{if(m==="detail"){(k.escape||k.return||I==="q")&&l("list");return}if(m==="cancelling"){I==="y"?de():l("list");return}if(m==="filter"){if(k.escape){l("list");return}k.upArrow&&d>0&&C(S=>S-1),k.downArrow&&d<Xt.length-1&&C(S=>S+1),k.return&&(a(Xt[d]),b(0),n(0),l("list"));return}if(k.escape||I==="q"){e();return}if(k.upArrow&&i>0&&n(S=>S-1),k.downArrow&&i<q.length-1&&n(S=>S+1),k.return){let S=q[i];S&&(N([]),l("detail"),T(`/tasks/${S.id}/logs?limit=20`).then(({logs:Q})=>N(Q)).catch(()=>N([])))}if(I==="x"&&q[i]){let S=q[i];["running","pending","queued","paused"].includes(S.status)?(l("cancelling"),g(null)):g(`Cannot cancel task in status: ${S.status}`)}I==="f"&&(C(Xt.indexOf(r)),l("filter")),I==="r"&&Z(),(k.pageDown||I==="n")&&p<j-1&&(b(S=>S+1),n(0)),(k.pageUp||I==="p")&&p>0&&(b(S=>S-1),n(0))}),c?ye(ae,{dimColor:!0,children:"Loading tasks..."}):m==="filter"?Ie(mt,{flexDirection:"column",children:[ye(ae,{bold:!0,children:"Filter by status:"}),Xt.map((I,k)=>ye(mt,{children:Ie(ae,{color:k===d?"cyan":"white",children:[k===d?"> ":" ",I,I===r?" (current)":""]})},I)),ye(ae,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):m==="detail"&&q[i]?ye(Jo,{taskId:q[i].id,onBack:()=>l("list")}):m==="cancelling"&&q[i]?Ie(mt,{flexDirection:"column",children:[Ie(ae,{color:"red",children:['Cancel task "',q[i].id.slice(0,8),'"? (y/n)']}),s&&ye(ae,{color:"red",children:s})]}):Ie(mt,{flexDirection:"column",children:[Ie(mt,{children:[Ie(ae,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&Ie(ae,{dimColor:!0,children:[" [filter: ",r,"]"]}),Ie(ae,{dimColor:!0,children:[" \u2014 Page ",p+1,"/",j]})]}),s&&ye(ae,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?Ie(ae,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):Ie(un,{children:[ye(mt,{marginTop:1,children:Ie(ae,{bold:!0,children:[" ",at("ID",10),at("STATUS",12),at("PROMPT",40),at("DURATION",10),"COST"]})}),q.map((I,k)=>{let S=k===i,Q=I.totalDurationMs?`${(I.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",ee=I.costUsd!==void 0?`$${I.costUsd.toFixed(4)}`:"\u2014",Me=cn[I.status]??"white";return Ie(mt,{children:[ye(ae,{color:S?"cyan":"white",children:S?"> ":" "}),ye(ae,{dimColor:!0,children:at(I.id.slice(0,8),10)}),ye(ae,{color:Me,children:at(I.status,12)}),ye(ae,{children:at(dn(I.prompt,38),40)}),ye(ae,{dimColor:!0,children:at(Q,10)}),ye(ae,{dimColor:!0,children:ee})]},I.id)})]}),ye(ae,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function at(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function dn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}Do();import{Box as _t,Text as $e,useInput as mn}from"ink";import{useEffect as gn,useState as er}from"react";import{readFileSync as fn,existsSync as pn}from"fs";import{parse as xn}from"yaml";import{Fragment as Tn,jsx as Oe,jsxs as lt}from"react/jsx-runtime";function or({onBack:e}){let[t,o]=er(null),[c,u]=er(null);return mn((m,l)=>{(l.escape||m==="q")&&e()}),gn(()=>{try{let m=Ao;if(!pn(m)){u(`Config file not found: ${m}`);return}let l=fn(m,"utf-8");o(xn(l))}catch(m){u(m.message)}},[]),c?lt(_t,{flexDirection:"column",children:[Oe($e,{color:"red",children:c}),Oe($e,{dimColor:!0,children:"Press Esc to go back"})]}):t?lt(_t,{flexDirection:"column",children:[Oe($e,{bold:!0,children:"Configuration (Esc to go back)"}),Oe(_t,{marginTop:1,flexDirection:"column",children:Oe(rr,{obj:t,indent:0})})]}):Oe($e,{dimColor:!0,children:"Loading config..."})}function rr({obj:e,indent:t}){let o=" ".repeat(t);return Oe(Tn,{children:Object.entries(e).map(([c,u])=>u&&typeof u=="object"&&!Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),":"]}),Oe(rr,{obj:u,indent:t+1})]},c):Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),":"]}),u.map((m,l)=>lt($e,{children:[o," - ",tr(c,String(m))]},l))]},c):lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),": ",tr(c,String(u))]},c))})}function tr(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as Jt,Text as qe,useInput as hn}from"ink";import{useEffect as yn,useState as xo}from"react";import{jsx as Vt,jsxs as je}from"react/jsx-runtime";function nr({onBack:e}){let[t,o]=xo([]),[c,u]=xo(!0),[m,l]=xo(null);return hn((i,n)=>{(n.escape||i==="q")&&e()}),yn(()=>{T("/evolution-audit?limit=20").then(i=>{o(i),u(!1)}).catch(i=>{l(i.message),u(!1)})},[]),c?Vt(qe,{dimColor:!0,children:"Loading evolution log..."}):m?je(Jt,{flexDirection:"column",children:[Vt(qe,{color:"red",children:m}),Vt(qe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?je(Jt,{flexDirection:"column",children:[Vt(qe,{dimColor:!0,children:"No evolution records yet"}),Vt(qe,{dimColor:!0,children:"Press Esc to go back"})]}):je(Jt,{flexDirection:"column",children:[je(qe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>je(Jt,{flexDirection:"column",marginTop:1,children:[je(qe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&je(qe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
-
`).map((n,r)=>n.startsWith("+")?je(qe,{color:"green",children:[" ",n]},r):n.startsWith("-")?je(qe,{color:"red",children:[" ",n]},r):je(qe,{dimColor:!0,children:[" ",n]},r))]},i.id))]})}import{Box as Ze,Text as re,useInput as vn}from"ink";import bn from"ink-text-input";import{useEffect as Sn,useState as yt}from"react";import{jsx as we,jsxs as ge}from"react/jsx-runtime";var Cn={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function wn(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Bn(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Zt({onBack:e}){let[t,o]=yt([]),[c,u]=yt(null),[m,l]=yt("list"),[i,n]=yt(""),[r,a]=yt(!1),[d,C]=yt(null);vn((s,g)=>{if(m==="create"){g.escape&&(l("list"),n(""),C(null));return}(g.escape||s==="q")&&e(),s==="c"&&(l("create"),C(null)),s==="r"&&p()});let p=()=>{T("/goals?limit=20").then(({goals:s})=>o(s)).catch(s=>u(s.message))};Sn(()=>{p()},[]);let b=async s=>{if(s.trim()){a(!0),C(null);try{let g=await T("/goals",{method:"POST",body:{input:s.trim()}});C(`Goal created: ${g.goal.name}`),n(""),l("list"),p()}catch(g){C(`Failed: ${g instanceof Error?g.message:String(g)}`)}finally{a(!1)}}};return c?ge(Ze,{flexDirection:"column",children:[ge(re,{color:"red",children:["Failed to load goals: ",c]}),we(re,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?ge(Ze,{flexDirection:"column",children:[we(re,{bold:!0,children:"Create Goal"}),we(re,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),ge(Ze,{marginTop:1,children:[we(re,{color:"cyan",children:"> "}),we(bn,{value:i,onChange:n,onSubmit:b})]}),r&&we(re,{color:"yellow",children:"Creating goal..."}),d&&we(re,{color:d.startsWith("Failed")?"red":"green",children:d}),we(re,{dimColor:!0,children:"Press Esc to cancel"})]}):ge(Ze,{flexDirection:"column",children:[ge(re,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?we(re,{dimColor:!0,children:"No goals found. Press c to create one."}):we(Ze,{marginTop:1,flexDirection:"column",children:t.map(s=>{let g=s.targetValue>0?s.currentValue/s.targetValue:0,V=Cn[s.status]??"white";return ge(Ze,{marginBottom:1,flexDirection:"column",children:[ge(Ze,{children:[we(re,{bold:!0,color:V,children:s.name}),ge(re,{dimColor:!0,children:[" (",s.role,")"]}),we(re,{dimColor:!0,children:" \u2014 "}),we(re,{color:V,children:s.status})]}),ge(Ze,{children:[ge(re,{dimColor:!0,children:[" ",wn(g)," "]}),ge(re,{color:g>=1?"green":"white",children:[Math.round(g*100),"%"]}),ge(re,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),ge(Ze,{children:[ge(re,{dimColor:!0,children:[" \u23F0 ",Bn(s.deadline)," left"]}),ge(re,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),ge(re,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),we(re,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as vt,Text as De,useInput as En}from"ink";import{useEffect as In,useState as sr}from"react";import{jsx as tt,jsxs as et}from"react/jsx-runtime";function kn(e,t,o=15){let c=e/(e+t),u=Math.round(c*o);return"\u2593".repeat(u)+"\u2591".repeat(o-u)}function ir({onBack:e}){let[t,o]=sr([]),[c,u]=sr(null);if(En((l,i)=>{(i.escape||l==="q")&&e()}),In(()=>{T("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>u(l.message))},[]),c)return et(vt,{flexDirection:"column",children:[et(De,{color:"red",children:["Failed to load strategies: ",c]}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return et(vt,{flexDirection:"column",children:[tt(De,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]});let m=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,n=m.get(i)??[];n.push(l),m.set(i,n)}return et(vt,{flexDirection:"column",children:[tt(De,{bold:!0,children:"Strategy Lab"}),tt(De,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),tt(vt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([l,i])=>et(vt,{marginBottom:1,flexDirection:"column",children:[tt(De,{bold:!0,color:"cyan",children:l}),i.sort((n,r)=>{let a=n.alpha/(n.alpha+n.beta);return r.alpha/(r.alpha+r.beta)-a}).map(n=>{let r=n.alpha/(n.alpha+n.beta);return et(vt,{children:[tt(De,{dimColor:!0,children:" "}),et(De,{children:[kn(n.alpha,n.beta)," "]}),et(De,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),et(De,{dimColor:!0,children:[" ",n.name," (\u03B1=",n.alpha.toFixed(1)," \u03B2=",n.beta.toFixed(1)," trials=",n.totalTrials,")"]})]},n.id)})]},l))}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as xe,Text as G,useInput as Mn}from"ink";import To from"ink-text-input";import{useEffect as Nn,useState as Ke,useCallback as bt}from"react";import{CronExpressionParser as Ln}from"cron-parser";import{useState as Pn,useEffect as An,useCallback as ar,useRef as Dn}from"react";var Rn=3e3;function ct(){let[e,t]=Pn(null),o=Dn(null),c=ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),u=ar((m,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:m,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},Rn))},[]);return An(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:u,clearMessage:c}}import{jsx as X,jsxs as te}from"react/jsx-runtime";var ho=["manual","cron","event"],eo={name:"",triggerType:"manual",cron:"",stepPrompt:""};function _n(e){try{return Ln.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function to({onBack:e}){let[t,o]=Ke([]),[c,u]=Ke(!0),[m,l]=Ke(0),[i,n]=Ke("list"),[r,a]=Ke({...eo}),[d,C]=Ke("name"),[p,b]=Ke(null),{message:s,setMessage:g,clearMessage:V}=ct(),[N,Z]=Ke(!1),[j,q]=Ke(!1),[de,I]=Ke({}),k=bt(()=>{u(!0),T("/task-templates").then(({templates:v})=>{o(v),new Set(v.flatMap(A=>A.steps?.map(z=>z.roleId).filter(Boolean)??[])).size>0?T("/roles").then(({roles:A})=>{if(!Array.isArray(A)){I({});return}I(Object.fromEntries(A.map(z=>[z.id,z.name])))}).catch(()=>I({})):I({}),u(!1)}).catch(()=>u(!1))},[]);Nn(()=>{k()},[k]);let S=i==="create"||i==="edit",Q=bt(async()=>{let v=t[m];if(!(!v||N)){Z(!0),g(`Triggering ${v.name}...`,"loading");try{let M=await T(`/task-templates/${v.id}/run`,{method:"POST"});g(`Triggered: ${v.name} (${M.executionId})`,"success")}catch(M){g(`Trigger failed: ${M instanceof Error?M.message:String(M)}`,"error")}finally{Z(!1)}}},[t,m,N,g]),ee=bt(async()=>{let v=t[m];if(!v||j)return;if(v.trigger?.type!=="cron"&&v.trigger?.type!=="event"){g("Toggle not applicable for manual triggers","error");return}let M=!v.enabled;q(!0),g(`${v.name} \u2192 ${M?"enabling":"disabling"}...`,"loading");try{await T(`/task-templates/${v.id}`,{method:"PATCH",body:{enabled:M}}),o(A=>A.map(z=>z.id===v.id?{...z,enabled:M}:z)),g(`${v.name} ${M?"enabled":"disabled"}`,"success")}catch(A){g(`Toggle failed: ${A instanceof Error?A.message:String(A)}`,"error")}finally{q(!1)}},[t,m,j,g]),Me=bt(async()=>{let v=t[m];if(v)try{await T(`/task-templates/${v.id}`,{method:"DELETE"}),g(`Deleted: ${v.name}`,"success"),k(),l(M=>Math.max(0,Math.min(M,t.length-2)))}catch(M){g(`Delete failed: ${M instanceof Error?M.message:String(M)}`,"error")}},[t,m,k]),pt=bt(()=>{let v=t[m];v&&(b(v.id),a({name:v.name,triggerType:v.trigger?.type??"manual",cron:v.trigger?.cron??"",stepPrompt:v.steps?.[0]?.prompt??""}),C("name"),n("edit"))},[t,m]),Ee=bt(async()=>{let v={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await T("/task-templates",{method:"POST",body:v}),g(`Created: ${r.name}`,"success")):i==="edit"&&p&&(await T(`/task-templates/${p}`,{method:"PATCH",body:v}),g(`Updated: ${r.name}`,"success"))}catch(M){g(`Save failed: ${M instanceof Error?M.message:String(M)}`,"error")}n("list"),a({...eo}),b(null),k()},[r,i,p,k]);return Mn((v,M)=>{if(S){if(M.escape){n("list"),a({...eo}),b(null);return}if(M.return){let A=["name","triggerType","cron","stepPrompt"],z=A.indexOf(d);if(z<A.length-1){let Se=z+1;if(A[Se]==="cron"&&r.triggerType!=="cron"&&Se++,Se<A.length){C(A[Se]);return}}Ee();return}if(M.tab&&d==="triggerType"){a(A=>{let z=ho.indexOf(A.triggerType);return{...A,triggerType:ho[(z+1)%ho.length]}});return}return}if(M.escape||v==="q"){e();return}if(M.upArrow){l(A=>Math.max(0,A-1));return}if(M.downArrow){l(A=>Math.min(t.length-1,A+1));return}if(v==="t"){Q();return}if(v==="d"){Me();return}if(v==="e"){pt();return}if(v==="c"){a({...eo}),C("name"),n("create");return}if(v==="s"||v===" "){ee();return}v==="r"&&(k(),V())}),c?X(G,{dimColor:!0,children:"Loading templates..."}):S?te(xe,{flexDirection:"column",children:[te(G,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),te(xe,{marginTop:1,flexDirection:"column",children:[te(xe,{children:[te(G,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?X(To,{value:r.name,onChange:v=>a(M=>({...M,name:v})),placeholder:"template name"}):X(G,{children:r.name||"(empty)"})]}),te(xe,{children:[te(G,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),X(G,{children:r.triggerType}),d==="triggerType"&&X(G,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&te(xe,{children:[te(G,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?X(To,{value:r.cron,onChange:v=>a(M=>({...M,cron:v})),placeholder:"*/5 * * * *"}):X(G,{children:r.cron||"(empty)"})]}),te(xe,{children:[te(G,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?X(To,{value:r.stepPrompt,onChange:v=>a(M=>({...M,stepPrompt:v})),placeholder:"What should this template do?"}):X(G,{children:r.stepPrompt||"(empty)"})]})]}),X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):te(xe,{flexDirection:"column",children:[te(G,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&X(xe,{marginTop:1,children:te(G,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"No templates found. Press c to create one."})}):X(xe,{marginTop:1,flexDirection:"column",children:t.map((v,M)=>{let A=M===m,z=v.trigger?.type==="cron"&&v.trigger?.cron?_n(v.trigger.cron):"",Se=new Set(v.steps?.filter(E=>E.roleId).map(E=>E.roleId)),D=v.steps?.length>1?`${v.steps.length} steps${Se.size>0?` / ${Se.size} roles`:""}`:`${v.steps?.length??0} step`;return te(xe,{flexDirection:"column",children:[te(xe,{children:[X(G,{color:A?"cyan":void 0,bold:A,children:A?"> ":" "}),X(G,{color:A?"cyan":void 0,bold:A,children:$t(v.name,24)}),X(G,{dimColor:!0,children:$t(v.trigger?.type,10)}),v.trigger?.type!=="cron"&&v.trigger?.type!=="event"?X(G,{dimColor:!0,children:$t("\u2014",6)}):X(G,{color:v.enabled?"green":"gray",children:$t(v.enabled?"on":"off",6)}),X(G,{dimColor:!0,children:$t(D,18)}),z&&te(G,{dimColor:!0,children:["next: ",z]})]}),A&&v.steps?.length>1&&X(xe,{flexDirection:"column",marginLeft:4,marginTop:0,children:v.steps.map((E,O)=>te(xe,{children:[te(G,{dimColor:!0,children:[" ",O+1,". "]}),X(G,{dimColor:!0,children:E.id}),E.roleId&&te(G,{color:"yellow",children:[" @",de[E.roleId]??E.roleId]}),E.dependsOn&&E.dependsOn.length>0&&te(G,{dimColor:!0,children:[" (after: ",E.dependsOn.join(", "),")"]}),E.config&&te(G,{dimColor:!0,children:[" ","[",[E.config.timeout!==void 0?`timeout:${E.config.timeout}s`:"",E.config.maxTurns!==void 0?`turns:${E.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},E.id))})]},v.id)})}),X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function $t(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as dt,Text as ke,useInput as Vn}from"ink";import $n from"ink-text-input";import{useEffect as On,useState as St,useCallback as lr}from"react";import{jsx as ve,jsxs as gt}from"react/jsx-runtime";function cr({onBack:e}){let[t,o]=St([]),[c,u]=St(""),[m,l]=St(!0),[i,n]=St(!1),[r,a]=St(""),[d,C]=St(null),p=lr(()=>{l(!0),T("/webhooks").then(({webhooks:s,auth:g})=>{o(s),u(g),l(!1)}).catch(()=>l(!1))},[]);On(()=>{p()},[p]);let b=lr(async s=>{if(s.trim())try{let g=await T(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});C(`Triggered: ${g.executionId}`)}catch(g){C(`Trigger failed: ${g instanceof Error?g.message:String(g)}`)}},[]);return Vn((s,g)=>{if(i){if(g.escape){n(!1),a("");return}if(g.return){b(r),n(!1),a("");return}return}if(g.escape||s==="q"){e();return}if(s==="t"){n(!0),a(""),C(null);return}s==="r"&&(p(),C(null))}),m?ve(ke,{dimColor:!0,children:"Loading webhooks..."}):gt(dt,{flexDirection:"column",children:[gt(ke,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),gt(ke,{dimColor:!0,children:["Auth: ",c]}),d&&ve(dt,{marginTop:1,children:ve(ke,{color:"yellow",children:d})}),i&>(dt,{marginTop:1,children:[ve(ke,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ve($n,{value:r,onChange:a,placeholder:"webhook name or ID"}),ve(ke,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ve(dt,{marginTop:1,children:ve(ke,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):gt(dt,{marginTop:1,flexDirection:"column",children:[ve(dt,{children:gt(ke,{bold:!0,children:[Ct("NAME",24),Ct("DESCRIPTION",36),Ct("TRIGGER",28),"TAGS"]})}),t.map(s=>gt(dt,{children:[ve(ke,{children:Ct(s.displayName,24)}),ve(ke,{dimColor:!0,children:Ct(qn(s.description??"",34),36)}),ve(ke,{dimColor:!0,children:Ct(s.trigger,28)}),ve(ke,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),ve(dt,{marginTop:1,children:ve(ke,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function Ct(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function qn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as ze,Text as le,useInput as Fn}from"ink";import Un from"ink-text-input";import{useEffect as dr,useState as ot,useCallback as yo}from"react";import{jsx as ce,jsxs as Fe}from"react/jsx-runtime";function Wn(e){return e>=4?"red":e===3?"yellow":"gray"}function Gn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Hn(e){return new Date(e).toLocaleDateString()}function mr({onBack:e}){let[t,o]=ot([]),[c,u]=ot(0),[m,l]=ot([]),[i,n]=ot(!0),[r,a]=ot(!1),[d,C]=ot(""),[p,b]=ot("all"),[s,g]=ot(null),[V,N]=ot(!1),Z=yo(()=>{T("/agents").then(({agents:S})=>{o(S),n(!1)}).catch(()=>n(!1))},[]);dr(()=>{Z()},[Z]);let j=t[c],q=yo(()=>{j&&(N(!1),T(`/memories/${j.id}`).then(({memories:S})=>{l(S),g(null)}).catch(S=>g(`Failed: ${S instanceof Error?S.message:String(S)}`)))},[j]);dr(()=>{j&&q()},[j,q]);let de=yo(async S=>{if(!(!j||!S.trim()))try{let Q=await T("/memories/query",{method:"POST",body:{agentId:j.id,prompt:S.trim()}});l(Q.memories),N(!0),g(`Search: ${Q.count} results`)}catch(Q){g(`Search failed: ${Q instanceof Error?Q.message:String(Q)}`)}},[j]),I=r,k=m.filter(S=>p==="all"?!0:p==="high"?S.importance>3:p==="medium"?S.importance===3:S.importance<3);return Fn((S,Q)=>{if(I){if(Q.escape){a(!1),C("");return}if(Q.return){de(d),a(!1),C("");return}return}if(Q.escape||S==="q"){e();return}if(S==="a"){u(ee=>(ee+1)%Math.max(1,t.length));return}if(Q.leftArrow){u(ee=>(ee-1+t.length)%Math.max(1,t.length));return}if(Q.rightArrow){u(ee=>(ee+1)%Math.max(1,t.length));return}if(S==="s"){a(!0),C(""),g(null);return}if(S==="h"){b(ee=>ee==="high"?"all":"high");return}if(S==="m"){b(ee=>ee==="medium"?"all":"medium");return}if(S==="l"){b(ee=>ee==="low"?"all":"low");return}S==="r"&&q()}),i?ce(le,{dimColor:!0,children:"Loading agents..."}):t.length===0?Fe(ze,{flexDirection:"column",children:[ce(le,{dimColor:!0,children:"No agents found"}),ce(le,{dimColor:!0,children:"Press Esc to go back"})]}):Fe(ze,{flexDirection:"column",children:[ce(le,{bold:!0,children:"Memories (Esc to go back)"}),Fe(ze,{marginTop:1,children:[ce(le,{children:"Agent: "}),ce(le,{bold:!0,color:"cyan",children:j?.name??"?"}),Fe(le,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),ce(ze,{children:Fe(le,{dimColor:!0,children:["Filter: ",p==="all"?"all":p," | ",V?"search results":"all memories"," (",k.length,")"]})}),s&&ce(ze,{children:ce(le,{color:"yellow",children:s})}),r&&Fe(ze,{marginTop:1,children:[ce(le,{bold:!0,color:"cyan",children:"Search: "}),ce(Un,{value:d,onChange:C,placeholder:"search query..."}),ce(le,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),k.length===0?ce(ze,{marginTop:1,children:Fe(le,{dimColor:!0,children:["No memories",p!=="all"?` matching filter '${p}'`:""]})}):ce(ze,{marginTop:1,flexDirection:"column",children:k.map(S=>Fe(ze,{marginBottom:0,children:[Fe(le,{color:Wn(S.importance),bold:!0,children:[Gn(S.importance)," "]}),ce(le,{dimColor:!0,children:ur(S.type??"?",12)}),ce(le,{dimColor:!0,children:ur(`\xD7${S.retrievedCount??0}`,5)}),Fe(le,{children:[jn(S.content,55)," "]}),ce(le,{dimColor:!0,children:Hn(S.createdAt)}),S.score!==void 0&&Fe(le,{dimColor:!0,children:[" (",S.score.toFixed(2),")"]})]},S.id))}),ce(ze,{marginTop:1,children:ce(le,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function ur(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function jn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ue,Text as ne,useInput as Kn}from"ink";import oo from"ink-text-input";import{useState as Be,useEffect as gr,useCallback as vo}from"react";import{jsx as fe,jsxs as me}from"react/jsx-runtime";var fr={Anthropic:["anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel"],Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","defaults.approvalTimeout"],Server:["server.port","server.host","server.apiKey","server.timezone"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"],Workflow:["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},zn={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","defaults.approvalTimeout":"Approval Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold","watchdog.rules.artifactCleanup.enabled":"Artifact Cleanup Enabled","watchdog.rules.artifactCleanup.ttlDays":"Artifact Retention (days)","watchdog.rules.artifactCleanup.orphanGcMinAgeHours":"Orphan GC Min Age (hours)"};function pr({onBack:e}){let{state:t}=st(),[o,c]=Be({}),[u,m]=Be([]),[l,i]=Be(null),[n,r]=Be("view"),[a,d]=Be(0),[C,p]=Be(""),[b,s]=Be(null),[g,V]=Be(!1),[N,Z]=Be([]),[j,q]=Be({}),[de,I]=Be(0),[k,S]=Be(""),[Q,ee]=Be(""),[Me,pt]=Be(""),Ee=Object.values(fr).flat(),v=vo(()=>{T("/config").then(D=>{c(D.config),m(D.mutable)}).catch(D=>i(D.message)),T("/config/env-diff").then(D=>{Z(D.diffs)}).catch(()=>{}),T("/config/env").then(D=>q(D.env??{})).catch(()=>{})},[]);gr(()=>{v()},[v]),gr(()=>{t.configVersion>0&&v()},[t.configVersion,v]);let M=vo(async()=>{let D=Ee[a];if(D){V(!0),s(null);try{let E=C,O=o[D];if(O&&typeof O.value=="number"&&(E=Number(C),isNaN(E))){s("Invalid number"),V(!1);return}let se=await T("/config",{method:"PATCH",body:{[D]:E}});se.updated.length>0&&(s(`Updated: ${D}`),v()),se.errors.length>0&&s(se.errors[0]),r("view")}catch(E){s(`Failed: ${E instanceof Error?E.message:String(E)}`)}finally{V(!1)}}},[Ee,a,C,o,v]),A=Object.keys(j),z=vo(async D=>{try{await T("/config/env",{method:"PUT",body:D}),s("Env vars saved"),v()}catch(E){s(`Failed: ${E instanceof Error?E.message:String(E)}`)}},[v]);if(Kn((D,E)=>{if(n==="edit"){if(E.escape){r("view");return}return}if(n==="env-list"){if(E.escape){r("view");return}if(E.upArrow&&de>0&&I(O=>O-1),E.downArrow&&de<A.length-1&&I(O=>O+1),D==="a"){S(""),r("env-add-key");return}if(D==="d"&&A.length>0){let O=A[de],se={...j};delete se[O],z(se),de>=A.length-1&&de>0&&I(Qe=>Qe-1);return}if(E.return&&A.length>0){pt(j[A[de]]??""),r("env-edit-value");return}return}if(n==="env-add-key"){if(E.escape){r("env-list");return}return}if(n==="env-add-value"){if(E.escape){r("env-list");return}return}if(n==="env-edit-value"){if(E.escape){r("env-list");return}return}if(E.escape||D==="q"){e();return}if(E.upArrow&&a>0&&d(O=>O-1),E.downArrow&&a<Ee.length-1&&d(O=>O+1),E.return||D==="e"){let O=Ee[a],se=o[O];se&&se.mutable?(p(String(se.value??"")),r("edit"),s(null)):se&&!se.mutable&&s("This setting requires a restart to change")}D==="v"&&(I(0),r("env-list"),s(null)),D==="r"&&(v(),s("Refreshed")),D==="s"&&N.length>0&&T("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),Z([]),v()}),D==="l"&&N.length>0&&T("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),v()})}),l)return me(Ue,{flexDirection:"column",children:[me(ne,{color:"red",children:["Failed to load config: ",l]}),fe(ne,{dimColor:!0,children:"Press Esc or q to return"})]});let Se=0;return me(Ue,{flexDirection:"column",children:[fe(ne,{bold:!0,children:"Settings"}),b&&fe(ne,{color:b.startsWith("Failed")||b.startsWith("This setting")?"yellow":"green",children:b}),N&&N.length>0&&me(Ue,{flexDirection:"column",marginBottom:1,children:[me(ne,{color:"yellow",children:[".env differs from DB (",N.length," key(s)): ",N.map(D=>D.envKey).join(", ")]}),fe(ne,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),fe(Ue,{marginTop:1,flexDirection:"column",children:Object.entries(fr).map(([D,E])=>me(Ue,{marginBottom:1,flexDirection:"column",children:[fe(ne,{bold:!0,color:"cyan",children:D}),E.map(O=>{let se=o[O],xt=Se++===a,Tt=u.includes(O),Ut=zn[O]??O,Xe=se?String(se.value??""):"...";return n==="edit"&&xt?me(Ue,{children:[me(ne,{color:"cyan",children:["> ",Ut,": "]}),fe(oo,{value:C,onChange:p,onSubmit:()=>{M()}}),g&&fe(ne,{color:"yellow",children:" saving..."})]},O):me(Ue,{children:[me(ne,{color:xt?"cyan":"white",children:[xt?"> ":" ",Tt?" ":"\u{1F512} ",Ut,": "," "]}),fe(ne,{color:Tt?"white":"gray",children:Xe}),!Tt&&fe(ne,{dimColor:!0,children:" (restart required)"})]},O)})]},D))}),fe(ne,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),n.startsWith("env")&&me(Ue,{flexDirection:"column",marginTop:1,children:[me(ne,{bold:!0,color:"cyan",children:["Environment Variables (",A.length,")"]}),A.length===0&&n==="env-list"&&fe(ne,{dimColor:!0,children:" No env vars. Press a to add."}),A.map((D,E)=>{let O=E===de;return n==="env-edit-value"&&O?me(Ue,{children:[me(ne,{color:"cyan",children:["> ",D," = "]}),fe(oo,{value:Me,onChange:pt,onSubmit:()=>{z({...j,[D]:Me}),r("env-list")}})]},D):me(ne,{color:O&&n==="env-list"?"cyan":"white",children:[O&&n==="env-list"?"> ":" ",D," = ",j[D]]},D)}),n==="env-add-key"&&me(Ue,{children:[fe(ne,{color:"green",children:" New key: "}),fe(oo,{value:k,onChange:S,onSubmit:()=>{k.trim()&&(ee(""),r("env-add-value"))}})]}),n==="env-add-value"&&me(Ue,{children:[me(ne,{color:"green",children:[" ",k," = "]}),fe(oo,{value:Q,onChange:ee,onSubmit:()=>{z({...j,[k.trim()]:Q}),r("env-list")}})]}),fe(ne,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as ft,Text as be,useInput as Qn}from"ink";import{useEffect as Xn,useState as bo,useCallback as Yn}from"react";import{jsx as Te,jsxs as Bt}from"react/jsx-runtime";function xr({onBack:e}){let[t,o]=bo([]),[c,u]=bo(!0),[m,l]=bo(0),{message:i,setMessage:n,clearMessage:r}=ct(),a=Yn(()=>{u(!0),T("/plugins").then(({plugins:d})=>{o(d),u(!1)}).catch(()=>u(!1))},[]);return Xn(()=>{a()},[a]),Qn((d,C)=>{if(C.escape||d==="q"){e();return}if(C.upArrow){l(p=>Math.max(0,p-1));return}if(C.downArrow){l(p=>Math.min(t.length-1,p+1));return}d==="r"&&(a(),r())}),c?Te(be,{dimColor:!0,children:"Loading plugins..."}):Bt(ft,{flexDirection:"column",children:[Bt(be,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Te(ft,{marginTop:1,children:Bt(be,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"No plugins installed."})}):Bt(ft,{marginTop:1,flexDirection:"column",children:[Bt(ft,{children:[Te(be,{dimColor:!0,children:" "}),Te(be,{dimColor:!0,children:wt("Name",24)}),Te(be,{dimColor:!0,children:wt("Scope",8)}),Te(be,{dimColor:!0,children:wt("User",6)}),Te(be,{dimColor:!0,children:"Path"})]}),t.map((d,C)=>{let p=C===m,b=d.id.split("@")[0];return Bt(ft,{children:[Te(be,{color:p?"cyan":void 0,bold:p,children:p?"> ":" "}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(b,24)}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(d.scope,8)}),Te(be,{color:d.globalEnabled?"green":"gray",children:wt(d.globalEnabled?"on":"off",6)}),Te(be,{dimColor:!0,children:d.installPath})]},d.id)})]}),Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"r:refresh"})})]})}function wt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ro,Text as Tr,useInput as Jn}from"ink";import{useState as Zn}from"react";import{jsx as Et,jsxs as So}from"react/jsx-runtime";var es=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function hr({onBack:e}){let[t,o]=Zn("tasks");return Jn((c,u)=>{if(u.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),So(ro,{flexDirection:"column",children:[So(ro,{gap:1,marginBottom:1,children:[es.map(c=>{let u=t===c.id;return Et(ro,{children:So(Tr,{color:u?"cyan":"gray",bold:u,underline:u,children:["[",c.key,":",c.label,"]"]})},c.id)}),Et(ro,{flexGrow:1}),Et(Tr,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&Et(Yt,{onBack:e}),t==="automations"&&Et(to,{onBack:e}),t==="goals"&&Et(Zt,{onBack:e})]})}import{Box as J,Text as W,useInput as ts}from"ink";import{useEffect as os,useState as Ot}from"react";import{jsx as L,jsxs as pe}from"react/jsx-runtime";var yr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function vr({onBack:e}){let[t,o]=Ot([]),[c,u]=Ot(!0),[m,l]=Ot(0),[i,n]=Ot(null),[r,a]=Ot("");os(()=>{d()},[]);async function d(){try{let b=await T("/channels");o(b.channels)}catch{}u(!1)}async function C(b){if(t.find(g=>g.id===b)?.platform==="wechat")try{a("Starting WeChat QR login...");let g=await T(`/channels/${b}/wechat/qr-start`,{method:"POST"});if(g.qrcodeUrl){a(`Scan QR: ${g.qrcodeUrl}
|
|
6
|
-
Waiting for scan...`);let V=await T(`/channels/${b}/wechat/qr-wait`,{method:"POST",body:{sessionKey:g.sessionKey,timeoutMs:12e4}});a(V.message)}else a(g.message);d()}catch{a("WeChat connect failed")}else try{await T(`/channels/${b}/connect`,{method:"POST"}),a("Connecting..."),d()}catch{a("Connect failed")}}async function p(b){try{await T(`/channels/${b}/disconnect`,{method:"POST"}),a("Disconnected"),d()}catch{a("Disconnect failed")}}return ts((b,s)=>{if(i){if(s.escape||b==="q"){n(null);return}if(b==="c"){C(i.id);return}if(b==="d"){p(i.id);return}return}if(s.escape){e();return}if(s.upArrow){l(g=>Math.max(0,g-1));return}if(s.downArrow){l(g=>Math.min(t.length-1,g+1));return}if(s.return&&t[m]){n(t[m]),a("");return}}),c?L(J,{flexDirection:"column",children:L(W,{dimColor:!0,children:"Loading channels..."})}):i?pe(J,{flexDirection:"column",children:[pe(J,{marginBottom:1,children:[pe(W,{bold:!0,children:["Channel: ",i.name]}),L(W,{dimColor:!0,children:" (Esc to go back)"})]}),pe(J,{flexDirection:"column",gap:0,children:[pe(W,{children:["ID: ",i.id]}),pe(W,{children:["Platform: ",i.platform]}),pe(W,{children:["Status: ",L(W,{color:yr[i.status]??"white",children:i.status})]}),pe(W,{children:["Enabled: ",i.enabled?"yes":"no"]}),pe(W,{children:["Messages: ",i.messageCount]}),pe(W,{children:["Config: ",JSON.stringify(i.config)]})]}),L(J,{marginTop:1,children:L(W,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&L(W,{color:"yellow",children:r})]}):pe(J,{flexDirection:"column",children:[pe(J,{marginBottom:1,children:[L(W,{bold:!0,children:"Channels"}),pe(W,{dimColor:!0,children:[" (",t.length," total) "]}),L(W,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?L(W,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):pe(J,{flexDirection:"column",children:[pe(J,{children:[L(J,{width:3,children:L(W,{dimColor:!0,children:" "})}),L(J,{width:12,children:L(W,{bold:!0,dimColor:!0,children:"ID"})}),L(J,{width:16,children:L(W,{bold:!0,dimColor:!0,children:"Name"})}),L(J,{width:12,children:L(W,{bold:!0,dimColor:!0,children:"Platform"})}),L(J,{width:14,children:L(W,{bold:!0,dimColor:!0,children:"Status"})}),L(J,{width:10,children:L(W,{bold:!0,dimColor:!0,children:"Enabled"})}),L(J,{width:10,children:L(W,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((b,s)=>pe(J,{children:[L(J,{width:3,children:L(W,{children:s===m?">":" "})}),L(J,{width:12,children:L(W,{inverse:s===m,children:b.id.slice(0,8)})}),L(J,{width:16,children:L(W,{children:b.name})}),L(J,{width:12,children:L(W,{children:b.platform})}),L(J,{width:14,children:pe(W,{color:yr[b.status]??"white",children:[b.status==="connected"?"\u25CF":b.status==="error"?"\u2717":"\u25CB"," ",b.status]})}),L(J,{width:10,children:L(W,{color:b.enabled?"green":"gray",children:b.enabled?"yes":"no"})}),L(J,{width:10,children:L(W,{children:b.messageCount})})]},b.id))]})]})}import{Box as kt,Text as nt,useInput as ns}from"ink";import{useEffect as ss,useState as qt,useCallback as is}from"react";import{Box as R,Text as h,useInput as rs}from"ink";import rt from"ink-text-input";import{useEffect as br,useState as Y,useCallback as It}from"react";Do();import{Fragment as Sr,jsx as y,jsxs as B}from"react/jsx-runtime";function Cr({roleId:e,onBack:t}){let[o,c]=Y(null),[u,m]=Y([]),[l,i]=Y(!0),[n,r]=Y("view"),[a,d]=Y(""),[C,p]=Y(0),[b,s]=Y(""),[g,V]=Y([]),[N,Z]=Y(0),[j,q]=Y(new Set),[de,I]=Y("inline"),[k,S]=Y(""),[Q,ee]=Y(""),[Me,pt]=Y([]),[Ee,v]=Y(new Set),[M,A]=Y(0),[z,Se]=Y("default"),[D,E]=Y(""),[O,se]=Y(""),[Qe,xt]=Y("mode"),[Tt,Ut]=Y([]),[Xe,Wt]=Y(0),[Gt,Bo]=Y(""),[Eo,Io]=Y(""),[ko,Po]=Y(""),{message:$,setMessage:F}=ct(),ie=It(()=>{i(!0),T(`/roles/${e}`).then(({role:f,boundPlugins:w})=>{c(f),m(w??[]),d(f.cagPrompt??""),q(new Set(f.allowedTools??[])),I(f.executionMode??"inline"),S(f.model??""),ee(f.maxBudgetUsd!=null?String(f.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);br(()=>{ie(),T("/config").then(f=>{let w=f["defaults.deniedReadPaths"]?.value;Array.isArray(w)&&Ut(w)}).catch(()=>{})},[ie]),br(()=>{I(o?.executionMode??"inline"),S(o?.model??""),ee(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Se(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),se((o?.deniedBashPatterns??[]).join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns]);let Br=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:a}}),F("CAG prompt saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,a,ie,F]),Er=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Ne}}),F("Directories saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,ie,F]),Ir=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(j)}}),F("Tool permissions saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,j,ie,F]),kr=It(async()=>{if(!o)return;let f={executionMode:de};k!==void 0&&(f.model=k);let w=parseFloat(Q);isNaN(w)||(f.maxBudgetUsd=w);try{await T(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Execution config saved","success"),r("view"),ie()}catch(x){F(`Save failed: ${x instanceof Error?x.message:String(x)}`,"error")}},[o,de,k,Q,ie,F]),Pr=It(async()=>{if(!o)return;let f={permissionMode:z},w=D.split(",").map(P=>P.trim()).filter(Boolean),x=O.split(",").map(P=>P.trim()).filter(Boolean);f.allowedBashPatterns=w.length>0?w:[],f.deniedBashPatterns=x.length>0?x:[];try{await T(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Permission config saved","success"),r("view"),ie()}catch(P){F(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[o,z,D,O,ie,F]),Ne=o?.additionalDirectories??[];if(rs((f,w)=>{if(w.escape){r("view");return}if(f==="r"){ie();return}switch(n){case"view":{if(f==="c"){r("edit-cag");return}if(f==="d"){r("edit-dirs"),p(0),s("");return}if(f==="t"){r("edit-tools");return}if(f==="x"){r("edit-exec");return}if(f==="h"){T("/channels?enabled=true").then(({channels:x})=>{pt(x.map(P=>({name:P.name,id:P.id}))),v(new Set(o?.allowedChannels??[])),A(0),r("edit-channels")}).catch(()=>F("Failed to load channels","error"));return}if(f==="p"){Se(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),se((o?.deniedBashPatterns??[]).join(", ")),xt("mode"),r("edit-permissions");return}if(f==="v"){Wt(0),r("edit-env");return}if(f==="i"){if(!o)return;let x=!o.inheritUserSettings;T(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:x}}).then(()=>{F(`Inherit user settings: ${x?"ON":"OFF"}`,"success"),ie()}).catch(()=>F("Failed to toggle","error"));return}break}case"edit-cag":{if(w.ctrl&&f==="s"){Br();return}break}case"edit-dirs":{if(f==="s"){Er();return}if(f==="a"){r("edit-dirs-add");return}if(f==="m"&&Ne.length>0){let x=Ne[C];if(x){c(ue=>ue&&{...ue,additionalDirectories:ue.additionalDirectories?.map((Pe,Ar)=>Ar===C?{...typeof Pe=="string"?{path:Pe}:Pe,mode:Pe.mode==="ro"?"rw":"ro"}:Pe)});let P=x.mode==="ro"?"rw":"ro";F(`Mode set to ${P.toUpperCase()}`,"success")}return}if(f==="x"&&Ne.length>0){c(x=>x&&{...x,additionalDirectories:Ne.filter((P,ue)=>ue!==C)}),p(x=>Math.max(0,Math.min(x,Ne.length-2)));return}if(w.upArrow){p(x=>Math.max(0,x-1));return}if(w.downArrow){p(x=>Math.min(Ne.length-1,x+1));return}break}case"edit-dirs-add":{if(w.escape){r("edit-dirs"),s(""),V([]);return}if(w.return&&g.length>0){let x=g[N];x&&(s(x.endsWith("/")?x:x+"/"),V([]));return}if(w.return){let x=b.trim();x&&x.startsWith("/")?(c(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:x,mode:"rw"}]}),s(""),V([]),r("edit-dirs")):F("Path must be absolute (must start with /)","error");return}if(w.tab){let x=b.trim();if(!x||!x.startsWith("/"))return;T(`/fs/suggest-dirs?prefix=${encodeURIComponent(x)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),V([])):P.length>1&&(V(P),Z(0))}).catch(()=>{V([])});return}if(w.upArrow&&g.length>0){Z(x=>Math.max(0,x-1));return}if(w.downArrow&&g.length>0){Z(x=>Math.min(g.length-1,x+1));return}break}case"edit-tools":{if(f==="s"){Ir();return}let x=parseInt(f,10)-1;if(!isNaN(x)&&x>=0&&x<Ht.length){let P=Ht[x];q(ue=>{let Pe=new Set(ue);return Pe.has(P)?Pe.delete(P):Pe.add(P),Pe});return}break}case"edit-exec":{if(f==="s"){kr();return}if(w.tab){I(x=>x==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(f==="s"){Pr();return}if(w.tab){xt(x=>x==="mode"?"allowed":x==="allowed"?"denied":"mode");return}if(Qe==="mode"&&(w.upArrow||w.downArrow)){let x=["default","acceptEdits","dontAsk","bypassPermissions"],P=x.indexOf(z);w.upArrow&&Se(x[Math.max(0,P-1)]),w.downArrow&&Se(x[Math.min(x.length-1,P+1)]);return}break}case"edit-channels":{if(f==="s"){if(!o)return;let x=Ee.size>0?Array.from(Ee):[];T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:x}}).then(()=>{F("Channels saved","success"),r("view"),ie()}).catch(()=>F("Save failed","error"));return}if(f==="u"){if(!o)return;T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{F("Channels: unrestricted","success"),r("view"),ie()}).catch(()=>F("Save failed","error"));return}if(f===" "){let x=Me[M];x&&v(P=>{let ue=new Set(P);return ue.has(x.name)?ue.delete(x.name):ue.add(x.name),ue});return}if(w.upArrow){A(x=>Math.max(0,x-1));return}if(w.downArrow){A(x=>Math.min(Me.length-1,x+1));return}break}case"edit-env":{let x=Object.keys(o?.envVars??{});if(f==="a"){Bo(""),r("edit-env-add-key");return}if(f==="d"&&x.length>0){let P=x[Xe],ue={...o?.envVars??{}};delete ue[P],T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:ue}}).then(()=>{F("Deleted","success"),ie()}).catch(()=>F("Delete failed","error")),Xe>=x.length-1&&Xe>0&&Wt(Pe=>Pe-1);return}if(w.return&&x.length>0){Po((o?.envVars??{})[x[Xe]]??""),r("edit-env-edit-value");return}w.upArrow&&Xe>0&&Wt(P=>P-1),w.downArrow&&Xe<x.length-1&&Wt(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),l)return y(h,{dimColor:!0,children:"Loading role..."});if(!o)return y(h,{dimColor:!0,children:"Role not found."});if(n==="edit-cag")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),y(rt,{value:a,onChange:d,placeholder:"Character And Guidance prompt..."}),$&&y(R,{marginTop:1,children:y(h,{color:$.type==="error"?"red":"green",children:$.text})})]});if(n==="edit-dirs-add")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),y(rt,{value:b,onChange:f=>{s(f),V([])},placeholder:"/absolute/path/to/directory"}),g.length>0&&B(R,{flexDirection:"column",marginTop:1,children:[g.map((f,w)=>B(h,{color:w===N?"cyan":void 0,dimColor:w!==N,children:[w===N?"> ":" ",f,"/"]},f)),y(h,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),$&&y(R,{marginTop:1,children:y(h,{color:$.type==="error"?"red":"green",children:$.text})})]});if(n==="edit-dirs")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),Ne.length===0?y(h,{dimColor:!0,children:"No directories. Press a to add one."}):Ne.map((f,w)=>{let x=typeof f=="string"?{path:f,mode:"rw"}:f,P=x.mode!=="ro";return B(R,{children:[y(h,{color:w===C?"cyan":void 0,bold:w===C,children:w===C?"> ":" "}),B(h,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),y(h,{color:w===C?"cyan":void 0,children:x.path})]},x.path)})]});if(n==="edit-tools")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),Ht.map((f,w)=>{let x=j.has(f);return B(R,{children:[B(h,{dimColor:!0,children:[w+1,". "]}),y(h,{color:x?"green":"red",children:x?"[ON] ":"[OFF] "}),y(h,{children:f})]},f)})]});if(n==="edit-exec")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(R,{children:[y(h,{bold:!0,children:" Mode: "}),y(h,{color:"cyan",children:de}),y(h,{dimColor:!0,children:" (Tab to toggle)"})]}),B(R,{children:[y(h,{bold:!0,children:" Model: "}),y(rt,{value:k,onChange:S,placeholder:"sonnet, opus, haiku, or blank"})]}),B(R,{children:[y(h,{bold:!0,children:" Max Budget (USD): "}),y(rt,{value:Q,onChange:ee,placeholder:"0 = unlimited"})]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n==="edit-permissions")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(R,{children:[y(h,{bold:!0,color:Qe==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(w=>B(h,{color:w===z?"green":"gray",children:[w===z?`[${w}]`:` ${w} `," "]},w))]}),B(R,{children:[y(h,{bold:!0,color:Qe==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),Qe==="allowed"?y(rt,{value:D,onChange:E,placeholder:"git add *, pnpm test*"}):y(h,{children:D||"(none)"})]}),B(R,{children:[y(h,{bold:!0,color:Qe==="denied"?"cyan":void 0,children:" Denied Bash: "}),Qe==="denied"?y(rt,{value:O,onChange:se,placeholder:"rm -rf *, ssh *"}):y(h,{children:O||"(none)"})]}),y(h,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n==="edit-channels")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Me.length===0?y(h,{dimColor:!0,children:"No channels available"}):Me.map((f,w)=>B(R,{children:[B(h,{children:[w===M?">":" "," "]}),B(h,{color:Ee.has(f.name)?"green":"gray",children:["[",Ee.has(f.name)?"x":" ","] ",f.name]})]},f.id)),B(h,{dimColor:!0,children:["Selected: ",Ee.size>0?Array.from(Ee).join(", "):"none (= block all)"]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n.startsWith("edit-env")){let f=Object.keys(o.envVars??{});return B(R,{flexDirection:"column",children:[B(h,{bold:!0,children:["Environment Variables (",f.length,")"]}),f.length===0&&n==="edit-env"&&y(h,{dimColor:!0,children:" No env vars. Press a to add."}),f.map((w,x)=>{let P=x===Xe;return n==="edit-env-edit-value"&&P?B(R,{children:[B(h,{color:"cyan",children:["> ",w," = "]}),y(rt,{value:ko,onChange:Po,onSubmit:()=>{let ue={...o.envVars??{},[w]:ko};T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:ue}}).then(()=>{F("Saved","success"),ie(),r("edit-env")}).catch(()=>F("Save failed","error"))}})]},w):B(h,{color:P&&n==="edit-env"?"cyan":"white",children:[P&&n==="edit-env"?"> ":" ",w," = ",(o.envVars??{})[w]]},w)}),n==="edit-env-add-key"&&B(R,{children:[y(h,{color:"green",children:" New key: "}),y(rt,{value:Gt,onChange:Bo,onSubmit:()=>{Gt.trim()&&(Io(""),r("edit-env-add-value"))}})]}),n==="edit-env-add-value"&&B(R,{children:[B(h,{color:"green",children:[" ",Gt," = "]}),y(rt,{value:Eo,onChange:Io,onSubmit:()=>{let w={...o.envVars??{},[Gt.trim()]:Eo};T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:w}}).then(()=>{F("Added","success"),ie(),r("edit-env")}).catch(()=>F("Add failed","error"))}})]}),y(h,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),$&&y(h,{color:$.type==="error"?"red":"green",children:$.text})]})}return B(R,{flexDirection:"column",children:[B(h,{bold:!0,children:["Role: ",o.name]}),B(R,{children:[y(h,{dimColor:!0,children:"ID: "}),y(h,{children:o.id})]}),B(R,{children:[y(h,{dimColor:!0,children:"Status: "}),y(h,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&B(R,{children:[y(h,{dimColor:!0,children:"Score: "}),B(h,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(R,{children:[y(h,{dimColor:!0,children:"Created: "}),y(h,{children:new Date(o.createdAt).toLocaleString()})]}),B(R,{children:[y(h,{dimColor:!0,children:"Execution: "}),B(h,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),Ne.length>0&&B(Sr,{children:[y(h,{bold:!0,children:"Additional Directories:"}),Ne.map(f=>B(h,{dimColor:!0,children:[" ",f.path]},f.path))]}),B(R,{children:[y(h,{dimColor:!0,children:"Permission: "}),y(h,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(R,{children:[y(h,{dimColor:!0,children:" Bash Allow: "}),y(h,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(R,{children:[y(h,{dimColor:!0,children:" Bash Deny: "}),y(h,{children:o.deniedBashPatterns.join(", ")})]}),Tt.length>0&&B(R,{flexDirection:"column",children:[y(h,{dimColor:!0,children:"Denied Read Paths (global):"}),Tt.map(f=>B(h,{dimColor:!0,children:[" ",f]},f)),B(h,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(R,{children:[y(h,{dimColor:!0,children:"Channels: "}),y(h,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(R,{children:[y(h,{dimColor:!0,children:"Inherit User Settings: "}),y(h,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&B(Sr,{children:[y(h,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(f=>B(h,{dimColor:!0,children:[" - ",f]},f))]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),y(R,{marginTop:1,children:y(h,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as Re,jsxs as no}from"react/jsx-runtime";function wr({onBack:e}){let[t,o]=qt([]),[c,u]=qt(!0),[m,l]=qt(0),[i,n]=qt("list"),[r,a]=qt(null),{message:d,setMessage:C,clearMessage:p}=ct(),b=is(()=>{u(!0),T("/roles").then(({roles:s})=>{o(s.map(g=>({id:g.id,name:g.name,status:g.status,performanceScore:g.performanceScore,createdAt:g.createdAt}))),u(!1)}).catch(()=>u(!1))},[]);return ss(()=>{b()},[b]),ns((s,g)=>{if(g.escape||s==="q"){e();return}if(g.upArrow){l(V=>Math.max(0,V-1));return}if(g.downArrow){l(V=>Math.min(t.length-1,V+1));return}if(s==="r"&&(b(),p()),s===`
|
|
7
|
-
`||s==="o"||s==="e"){t.length>0&&(a(t[m].id),n("detail"));return}}),c?Re(nt,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Re(Cr,{roleId:r,onBack:()=>n("list")}):no(kt,{flexDirection:"column",children:[no(nt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&Re(kt,{marginTop:1,children:no(nt,{color:d.type==="success"?"green":d.type==="error"?"red":"gray",children:[d.type==="success"?"\u2713 ":d.type==="error"?"\u2717 ":"\u2192 ",d.text]})}),t.length===0?Re(kt,{marginTop:1,children:Re(nt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Re(kt,{marginTop:1,flexDirection:"column",children:t.map((s,g)=>{let V=g===m,N=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014";return no(kt,{children:[Re(nt,{color:V?"cyan":void 0,bold:V,children:V?"> ":" "}),Re(nt,{color:V?"cyan":void 0,bold:V,children:Co(s.name,24)}),Re(nt,{color:as(s.status),children:Co(s.status,12)}),Re(nt,{dimColor:!0,children:Co(N,8)})]},s.id)})}),Re(kt,{marginTop:1,children:Re(nt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function as(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Co(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as gs,jsx as H,jsxs as At}from"react/jsx-runtime";function ds(){let{state:e,dispatch:t}=st(),{session:o,sendMessage:c,createNewSession:u,archiveCurrentSession:m}=qo(),[l,i]=cs([]);so(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Vo();let{latestMessage:n}=Uo(o?.id??null),r=wo(null);so(()=>{n&&n.id!==r.current&&(r.current=n.id,i(N=>[...N,{role:"assistant",content:n.content}]))},[n]);let{events:a,isStreaming:d,clearEvents:C}=Oo(e.activeTaskId),p=a[a.length-1],b=p?.type==="complete"&&!d,s=wo(null),g=wo("");so(()=>{g.current=a.filter(N=>N.type==="reasoning").map(N=>N.content).join("")},[a]),so(()=>{if(b&&e.activeTaskId!==s.current){s.current=e.activeTaskId;let N=p?.content||g.current;N&&i(Z=>[...Z,{role:"assistant",content:N}])}},[b,p,e.activeTaskId]);let V=async N=>{let Z=N.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(Z)&&process.exit(0),N.startsWith("/")){let q=N.slice(1),I={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"}[q];if(I){t({type:"SET_VIEW",view:I});return}if(q==="new"){if(await m()){let S=await u();i([]),C(),S&&i([{role:"assistant",content:`Session archived. New session started: ${S.id.slice(0,8)}`}])}return}if(q==="session"){let k=o?`Session: ${o.id}
|
|
8
|
-
Turns: ${o.messageCount}
|
|
9
|
-
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(S=>[...S,{role:"assistant",content:k}]);return}}if(i(q=>[...q,{role:"user",content:N}]),C(),!await c(N)){i(q=>[...q,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}};return At(Ft,{flexDirection:"column",paddingX:1,children:[H(Wo,{}),At(Ft,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&At(gs,{children:[H(Qo,{messages:l}),H(jo,{events:a,isStreaming:d}),!e.connected&&!e.serverUnreachable&&H(Ft,{children:H(Pt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&At(Ft,{flexDirection:"column",children:[H(Pt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),H(Pt,{dimColor:!0,children:"Check: adam server logs"}),H(Pt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&H(hr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&H(Yt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&H(or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&H(nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&H(Zt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&H(ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&H(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&H(cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&H(mr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&H(xr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&H(wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&H(pr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&H(vr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?H(Yo,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?H(Xo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):H(Ho,{onSubmit:V}),e.planTimeoutNotice&&H(us,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function us({planId:e,onDismiss:t}){return ls(o=>{o==="d"&&t()}),At(Ft,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[At(Pt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),H(Pt,{dimColor:!0,children:" [d] Dismiss"})]})}function ms(){return H(No,{children:H(ds,{})})}export{ms as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as a,o as b}from"./chunk-PVYEGQEG.js";import"./chunk-5V36ACKZ.js";import"./chunk-6NUHSHS5.js";import"./chunk-HFN7Y3IM.js";import"./chunk-AKPLOO2V.js";import"./chunk-NDP6LWXX.js";import"./chunk-NLD7WK3R.js";import"./chunk-JZNBFZ7W.js";import"./chunk-CLHSPXZ6.js";import"./chunk-TKDT7EQO.js";import"./chunk-AZBNUSM2.js";import"./chunk-ZQYKT5UY.js";import"./chunk-7IXLL673.js";import"./chunk-L7JP7DUO.js";import"./chunk-P6KWAGAY.js";import"./chunk-2CMR5AG7.js";import"./chunk-IZGTTLTG.js";import"./chunk-IKUBP3SY.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{l as a,m as b,n as c,o as d,p as e}from"./chunk-ZKMDHQJY.js";import"./chunk-6NUHSHS5.js";import"./chunk-HFN7Y3IM.js";import"./chunk-AKPLOO2V.js";import"./chunk-YHVFZB6Q.js";import"./chunk-JZNBFZ7W.js";import"./chunk-YPOTHL7X.js";import"./chunk-4NW2DNDZ.js";import"./chunk-7IXLL673.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-P6KWAGAY.js";import"./chunk-2CMR5AG7.js";import"./chunk-IZGTTLTG.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-7CJGPCSJ.js";import"./chunk-NLD7WK3R.js";import"./chunk-XTHP5JMO.js";import"./chunk-YHVFZB6Q.js";import"./chunk-JZNBFZ7W.js";import"./chunk-WTRM5VO7.js";import"./chunk-CLHSPXZ6.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-IZGTTLTG.js";import"./chunk-IKUBP3SY.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c}from"./chunk-72VLUJ2S.js";import"./chunk-CLHSPXZ6.js";import"./chunk-ZQYKT5UY.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
package/dist/chunk-6NUHSHS5.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{e as I,j as G}from"./chunk-7IXLL673.js";import{a as J}from"./chunk-P6KWAGAY.js";import{a as j}from"./chunk-2CMR5AG7.js";import{a as E,b as S,c as D,j as T}from"./chunk-IZGTTLTG.js";import{b as P,d as B}from"./chunk-4MJF77RD.js";import{c as W,e as q}from"./chunk-FCV2DPZQ.js";var Q={};q(Q,{getGlobalEnabledState:()=>w,getInstalledPlugin:()=>z,getPluginManifest:()=>_,listInstalledPlugins:()=>A,listMarketplaceSources:()=>V,resolvePluginPaths:()=>M,scanDirectoryConfig:()=>x});import{existsSync as y,readFileSync as k,readdirSync as C}from"fs";import{join as p}from"path";import L from"os";function h(t){try{if(!y(t))return null;let e=k(t,"utf-8");return JSON.parse(e)}catch{return null}}function w(){return h(Y())?.enabledPlugins??{}}function _(t){let e=t;function s(n,r){let o={};try{if(!y(n))return o;let d=k(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let m of r){let i=new RegExp(`^${m}:\\s*(.+)$`,"m"),a=d.match(i);a&&(o[m]=a[1].trim())}}catch{}return o}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},r=p(e,".claude-plugin","plugin.json");if(y(r))try{let i=JSON.parse(k(r,"utf-8"));n.name=i.name??"",n.version=i.version,n.description=i.description,Array.isArray(i.lspServers)&&(n.lspServers=i.lspServers),Array.isArray(i.mcpServers)&&(n.mcpServers=i.mcpServers),Array.isArray(i.hooks)&&(n.hooks=i.hooks)}catch{}let o=p(e,"skills");if(y(o)){let i=C(o,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()&&!a.isSymbolicLink())continue;let u=p(o,a.name,"SKILL.md"),f=s(u,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let l=p(e,"agents");if(y(l)){let i=C(l,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(".md"))continue;let u=s(p(l,a.name),["name","description"]);u.name&&n.agents.push({name:u.name,description:u.description??""})}}let d=p(e,".mcp.json");if(y(d))try{let i=JSON.parse(k(d,"utf-8"));i.mcpServers&&typeof i.mcpServers=="object"&&(n.mcpServers=Object.keys(i.mcpServers))}catch{}let m=p(e,"hooks","hooks.json");if(y(m))try{let i=JSON.parse(k(m,"utf-8"));Array.isArray(i)&&(n.hooks=i.map(a=>typeof a=="object"&&a!==null&&"event"in a?String(a.event):String(a)))}catch{}return n}catch{return null}}function A(t){let e=h(R());if(!e?.plugins)return[];let s=w(),n=[];for(let[r,o]of Object.entries(e.plugins))if(!(!Array.isArray(o)||o.length===0))for(let l of o){let d=l.scope??"user";t?.scope&&d!==t.scope||t?.projectPath&&l.projectPath!==t.projectPath||n.push({id:r,name:r.split("@")[0],version:l.version??"",scope:d,projectPath:l.projectPath,installPath:l.installPath??p(v(),r),enabled:s[r]??l.enabled??!0,installedAt:l.installedAt??"",lastUpdated:l.lastUpdated??""})}return n}function z(t){let e=h(R());if(!e?.plugins?.[t])return null;let s=e.plugins[t];if(!Array.isArray(s)||s.length===0)return null;let n=s[0],r=w();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??p(v(),t),enabled:r[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function M(t){let e=h(R()),s=new Map;for(let n of t){let r=e?.plugins?.[n];Array.isArray(r)&&r.length>0&&s.set(n,r[0].installPath??p(v(),n))}return s}function V(){return h(H())?.marketplaces??[]}function x(t){let e=p(t,".claude","settings.json"),s=h(e);return{enabledPlugins:s?.enabledPlugins??{},mcpServers:s?.mcpServers??{},allowedTools:s?.allowedTools??[],disallowedTools:s?.disallowedTools??[]}}var v,R,H,Y,O=W(()=>{"use strict";v=()=>p(L.homedir(),".claude","plugins"),R=()=>p(v(),"installed_plugins.json"),H=()=>p(v(),"known_marketplaces.json"),Y=()=>p(L.homedir(),".claude","settings.json")});import{tool as b}from"@anthropic-ai/claude-agent-sdk";import{z as c}from"zod";import{v4 as X}from"uuid";function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Z={query:c.string().describe("Search query for memory retrieval"),roleId:c.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:c.number().optional().describe("Max results to return (default 5)")},ee={query:c.string().describe("Search query for memory retrieval"),topK:c.number().optional().describe("Max results to return (default 5)")},te={id:c.string().optional().describe("Memory ID to update. Omit to create new."),roleId:c.string().describe("Role ID to save memory under"),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ne={id:c.string().optional().describe("Memory ID to update. Omit to create new."),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:c.string().describe("Memory ID to delete")};async function F(t,e){let s=t??e.roleId,n=e.topK??5,r=await J(s,e.query,{topK:n});return g({results:r.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function $(t,e){let s=t??e.roleId;if(!s)return g({error:"roleId is required"});let n,r=!0;try{n=await j(e.content)}catch{r=!1}if(e.id){if(!S(e.id))return g({error:`Memory ${e.id} not found`});let m=D(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return g({id:e.id,action:"updated",success:m,embeddingUpdated:r})}let o=`mem-${X().slice(0,8)}`,l=Date.now();return E({id:o,roleId:s,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:l,lastAccessed:l,retrievedCount:0,tier:e.tier??"episodic"}),g({id:o,action:"created",success:!0,embeddingUpdated:r})}async function K(t,e){if(t){let s=S(e.id);if(!s)return g({error:`Memory ${e.id} not found`});if(s.roleId!==t)return g({error:`Memory ${e.id} does not belong to this role`})}return T(e.id),g({id:e.id,deleted:!0})}function ye(t){return t?[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ee,async e=>F(t,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ne,async e=>$(t,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Z,async e=>F(void 0,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",te,async e=>$(void 0,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}O();G();var re={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 ve(t,e){let s=t.allowedTools??[];if(s.length===0)return"No tool permissions";let n=new Map,r=[];for(let i of s){let a=re[i];if(a){let u=n.get(a.category)??[];u.push(a.label),n.set(a.category,u)}else r.push(i)}let o=[];for(let[i,a]of n)o.push(`${i} (${a.join(", ")})`);r.length>0&&o.push(r.join(", "));let l=o.join(" \xB7 "),d=Object.keys(t.mcpServers??{});d.length>0&&(l+=` \xB7 MCP: ${d.join(", ")}`);let m=t.additionalDirectories??[];if(m.length>0&&(l+=` \xB7 Dirs: ${m.map(i=>i.path).join(", ")}`),e&&e.plugins.length>0){let i=e.plugins.map(a=>{let u=[];return a.skills.length>0&&u.push(`skills: ${a.skills.map(f=>f.name).join(", ")}`),a.agents.length>0&&u.push(`agents: ${a.agents.map(f=>f.name).join(", ")}`),u.length>0?`${a.name} (${u.join("; ")})`:a.name});l+=` \xB7 Plugins: ${i.join(", ")}`}return l}function oe(t){let e=[],s=t.additionalDirectories??[];for(let n of s){if(!n.inheritPlugins&&!n.inheritMcp)continue;let r=x(n.path),o=Object.entries(r.enabledPlugins).filter(([,d])=>d).map(([d])=>d),l=M(o);for(let[,d]of l)e.includes(d)||e.push(d)}try{let n=I(t.name),r=A({scope:"project",projectPath:n});for(let o of r)o.installPath&&!e.includes(o.installPath)&&e.push(o.installPath)}catch{}return e}function Pe(t){let e=oe(t),s=[];for(let n of e){let r=_(n);r&&s.push({name:r.name||n.split("/").pop()||"unknown",description:r.description,skills:r.skills,agents:r.agents,mcpServers:r.mcpServers,hooks:r.hooks})}return{plugins:s}}B();function se(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var U={low:1,medium:2,high:3};function we(t){P().prepare(`
|
|
2
|
-
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
4
|
-
`).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function _e(t,e,s){let r=P().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let o of r)if(!(o.role_id&&o.role_id!==t)&&!(U[s]>U[o.max_risk_level]))try{if(new RegExp(o.task_pattern,"i").test(e))return se(o)}catch{}}export{we as a,_e as b,w as c,_ as d,A as e,z as f,V as g,x as h,Q as i,O as j,ye as k,ve as l,oe as m,Pe as n};
|
package/dist/chunk-72VLUJ2S.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as ue,b as x,c as X,d as le,e as ge}from"./chunk-CLHSPXZ6.js";import{f as ce}from"./chunk-ZQYKT5UY.js";import{c as _,h as R}from"./chunk-INNDBLZE.js";import{z as g}from"zod/v4";import{v4 as Dt}from"uuid";import{randomUUID as _e}from"crypto";import Ye from"crypto";var me="2.1.7",F="bot";function Ze(t){let e=t.split(".").map(r=>parseInt(r,10)),s=e[0]??0,i=e[1]??0,n=e[2]??0;return(s&255)<<16|(i&255)<<8|n&255}var J=Ze(me),et=35e3,pe=15e3,tt=1e4;function L(){return{channel_version:me}}function nt(t){return t.endsWith("/")?t:`${t}/`}function st(){let t=Ye.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function it(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":st(),"iLink-App-Id":F,"iLink-App-ClientVersion":String(J)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function D(t){let e=nt(t.baseUrl),s=new URL(t.endpoint,e),i=it({token:t.token,routeTag:t.routeTag,body:t.body}),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs);try{let o=await fetch(s.toString(),{method:"POST",headers:i,body:t.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${t.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function fe(t){let e=t.timeoutMs??et;try{let s=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(s)}catch(s){if(s instanceof Error&&s.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw s}}var rt={[-2]:2,[-3]:3},ot=1e3;async function C(t){let e=(await import("./logger-QCJUU7GV.js")).getLogger("channels"),s=new Map;for(;;){let i=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??pe,label:"sendMessage"});e.info({status:200,responseBody:i.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(i);if(n.ret&&n.ret!==0){let r=rt[n.ret],o=(s.get(n.ret)??0)+1;if(s.set(n.ret,o),r!==void 0&&o<r){e.warn({ret:n.ret,attempt:o,maxRetries:r},"sendMessage: retriable iLink error, retrying"),await new Promise(a=>setTimeout(a,ot*o));continue}throw e.error({ret:n.ret,errmsg:n.errmsg,attempt:o},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)e.warn({rawText:i.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function he(t){await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??tt,label:"sendTyping"})}async function ye(t){let e=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??pe,label:"getUploadUrl"});return JSON.parse(e)}var at=5*6e4,dt=35e3,be="3",w=new Map;function Y(t){return Date.now()-t.startedAt<at}function ct(){for(let[t,e]of w)Y(e)||w.delete(t)}async function we(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F};s&&(r.SKRouteTag=s);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 ut(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F,"iLink-App-ClientVersion":String(J)};s&&(r.SKRouteTag=s);let o=new AbortController,a=setTimeout(()=>o.abort(),dt);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function xe(t){let e=t.accountId||_e();ct();let s=w.get(e);if(!t.force&&s&&Y(s)&&s.qrcodeUrl)return{qrcodeUrl:s.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let i=t.botType||be,n=await we(t.apiBaseUrl,i,t.routeTag),r={sessionKey:e,id:_e(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return w.set(e,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(i){return{message:`Failed to start login: ${String(i)}`,sessionKey:e}}}var lt=3;async function Ie(t){let e=w.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Y(e))return w.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let s=Math.max(t.timeoutMs??48e4,1e3),i=Date.now()+s,n=1;for(;Date.now()<i;){try{let r=await ut(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>lt)return w.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=t.botType||be,a=await we(t.apiBaseUrl,o,t.routeTag);e.qrcode=a.qrcode,e.qrcodeUrl=a.qrcode_img_content,e.startedAt=Date.now()}catch(o){return w.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(w.delete(t.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!"}):(w.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return w.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return w.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import T,{promises as q}from"fs";import I from"path";import{homedir as K}from"os";var W={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},E={NONE:0,USER:1,BOT:2},y={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},A={NEW:0,GENERATING:1,FINISH:2},Te={TYPING:1,CANCEL:2};R();var gt=_("channels"),Z=-14,B=3600*1e3,S=new Map;function Re(t){let e=Date.now()+B;S.set(t,e),gt.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${B/1e3}s)`)}function j(t){let e=S.get(t);return e===void 0?!1:Date.now()>=e?(S.delete(t),!1):!0}function Me(t){let e=S.get(t);if(e===void 0)return 0;let s=e-Date.now();return s<=0?(S.delete(t),0):s}function Ue(t){S.delete(t)}R();import Ne from"fs";import $e from"path";import{homedir as wt}from"os";import{createCipheriv as mt,createDecipheriv as pt}from"crypto";function ke(t,e){let s=mt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Se(t,e){let s=pt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ce(t){return Math.ceil((t+1)/16)*16}function ee(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function Ee(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}R();var sn=_("channels");function ft(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function Ae(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function P(t){let{encryptQueryParam:e,aesKeyBase64:s,cdnBaseUrl:i,fullUrl:n}=t,r=ft(s),o=n?.trim()||(e?ee(e,i):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Ae(o);return Se(a,r)}async function Pe(t){let{encryptQueryParam:e,cdnBaseUrl:s,fullUrl:i}=t,n=i?.trim()||(e?ee(e,s):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Ae(n)}R();var Q=_("channels"),ve=24e3;function ht(t,e){let s=t.byteLength,i=44+s,n=Buffer.allocUnsafe(i),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(i-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(e,r),r+=4,n.writeUInt32LE(e*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(s,r),r+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(n,r),n}async function Oe(t){try{let{decode:e}=await import("silk-wasm");Q.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let s=await e(t,ve);Q.debug(`silkToWav: decoded duration=${s.duration}ms pcmBytes=${s.data.byteLength}`);let i=ht(s.data,ve);return Q.debug(`silkToWav: WAV size=${i.length}`),i}catch(e){return Q.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}import yt from"path";var _t={".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",".amr":"audio/amr",".silk":"audio/x-silk",".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"},bt={"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","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function V(t){let e=yt.extname(t).toLowerCase();return _t[e]??"application/octet-stream"}function qe(t){let e=t.split(";")[0].trim().toLowerCase();return bt[e]??".bin"}var k=_("channels"),Fe=100*1024*1024;function xt(t){return qe(t)??".bin"}async function v(t,e,s,i,n=Fe,r){if(t.length>n)throw new Error(`Media too large: ${t.length} bytes exceeds ${n} bytes`);let o=$e.join(wt(),".adam","wechat","media",i,s);await Ne.promises.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let c=e?xt(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${c}`}let d=$e.join(o,a);return await Ne.promises.writeFile(d,t),k.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Le(t,e){let{cdnBaseUrl:s,channelId:i}=e;if(t.type===y.IMAGE){let n=t.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 P({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n.media?.full_url}):await Pe({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:s,fullUrl:n.media?.full_url});return{path:await v(o,"image/png","inbound",i),mimeType:"image/png",type:"image"}}catch(o){return k.error({channelId:i},`Image download/decrypt failed: ${String(o)}`),null}}if(t.type===y.VOICE){let n=t.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=await Oe(r);if(o){let a=await v(o,"audio/wav","inbound",i);return k.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await v(r,"audio/silk","inbound",i);return k.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return k.error({channelId:i},`Voice download/transcode failed: ${String(r)}`),null}}if(t.type===y.FILE){let n=t.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=V(n.file_name??"file.bin");return{path:await v(r,o,"inbound",i,Fe,n.file_name),mimeType:o,type:"file"}}catch(r){return k.error({channelId:i},`File download failed: ${String(r)}`),null}}if(t.type===y.VIDEO){let n=t.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url});return{path:await v(r,"video/mp4","inbound",i),mimeType:"video/mp4",type:"video"}}catch(r){return k.error({channelId:i},`Video download failed: ${String(r)}`),null}}return null}import Be from"path";import te from"crypto";import It from"fs/promises";R();var M=_("channels"),z=3;async function Tt(t){let{buf:e,uploadFullUrl:s,uploadParam:i,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=t,d=ke(e,a),c=s?.trim(),u;if(c)u=c;else if(i)u=Ee({cdnBaseUrl:r,uploadParam:i,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);M.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,l;for(let h=1;h<=z;h++)try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(m.status>=400&&m.status<500){let b=m.headers.get("x-error-message")??await m.text();throw M.error(`${o}: CDN client error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload client error ${m.status}: ${b}`)}if(m.status!==200){let b=m.headers.get("x-error-message")??`status ${m.status}`;throw M.error(`${o}: CDN server error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=m.headers.get("x-encrypted-param")??void 0,!p)throw M.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");M.debug(`${o}: CDN upload success attempt=${h}`);break}catch(m){if(l=m,m instanceof Error&&m.message.includes("client error"))throw m;h<z?M.warn(`${o}: attempt ${h} failed, retrying... err=${String(m)}`):M.error(`${o}: all ${z} attempts failed err=${String(m)}`)}if(!p)throw l instanceof Error?l:new Error(`CDN upload failed after ${z} attempts`);return{downloadParam:p}}async function ne(t){let{filePath:e,toUserId:s,opts:i,cdnBaseUrl:n,mediaType:r,label:o}=t,a=await It.readFile(e),d=a.length,c=te.createHash("md5").update(a).digest("hex"),u=Ce(d),p=te.randomBytes(16).toString("hex"),l=te.randomBytes(16);M.debug(`${o}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let h=await ye({...i,filekey:p,media_type:r,to_user_id:s,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:l.toString("hex")}),m=h.upload_full_url?.trim(),b=h.upload_param;if(!m&&!b)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:Je}=await Tt({buf:a,uploadFullUrl:m||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:n,aeskey:l,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:Je,aeskey:l.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function De(t){return ne({...t,mediaType:W.IMAGE,label:"uploadImageToWeixin"})}async function We(t){return ne({...t,mediaType:W.VIDEO,label:"uploadVideoToWeixin"})}async function se(t){return ne({...t,mediaType:W.FILE,label:"uploadFileAttachmentToWeixin"})}R();var O=_("channels");function Rt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Mt(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(s,i)=>i.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(s,i)=>i.split("|").map(n=>n.trim()).join(" ")),e}async function ie(t){let{to:e,text:s,mediaItem:i,opts:n,label:r}=t,o=[],a=Mt(s);a&&o.push({type:y.TEXT,text_item:{text:a}}),o.push(i);let d="";for(let c of o){d=Rt();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:E.BOT,message_state:A.FINISH,item_list:[c],context_token:n.contextToken}};await C({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return O.debug(`${r}: sent to=${e} messageId=${d}`),{messageId:d}}async function Ut(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.IMAGE,image_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},mid_size:i.fileSizeCiphertext}};return ie({to:e,text:s,mediaItem:r,opts:n,label:"sendImageMessage"})}async function kt(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.VIDEO,video_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},video_size:i.fileSizeCiphertext}};return ie({to:e,text:s,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function je(t){let{to:e,text:s,fileName:i,uploaded:n,opts:r}=t,o={type:y.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:i,len:String(n.fileSize)}};return ie({to:e,text:s,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Qe(t){let{filePath:e,to:s,text:i,opts:n,cdnBaseUrl:r}=t,o=V(e),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){O.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${s}`);let u=await We({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return kt({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("image/")){O.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${s}`);let u=await De({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return Ut({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("audio/")){let u=Be.basename(e);O.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${s}`);let p=await se({filePath:e,fileName:u,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:u,uploaded:p,opts:n})}let d=Be.basename(e);O.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${s}`);let c=await se({filePath:e,fileName:d,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:d,uploaded:c,opts:n})}R();var f=_("channels"),Ve="https://novac2c.cdn.weixin.qq.com/c2c",ae=new Map;function Ke(t){return I.join(K(),".adam","wechat",`${t}.context-tokens.json`)}function St(t){let e=Ke(t);try{let s=T.readFileSync(e,"utf-8"),i=JSON.parse(s);for(let[n,r]of Object.entries(i))typeof r=="string"&&r&&ae.set(`${t}:${n}`,r);f.debug({channelId:t,count:Object.keys(i).length},"Restored context tokens from disk")}catch{}}function Ct(t,e,s){let i=Ke(t);try{let n={};try{let o=T.readFileSync(i,"utf-8");n=JSON.parse(o)}catch{}n[e]=s;let r=I.dirname(i);T.mkdirSync(r,{recursive:!0}),T.writeFileSync(i,JSON.stringify(n),"utf-8")}catch(n){f.warn({channelId:t,userId:e},`Failed to persist context token: ${String(n)}`)}}function Et(t,e,s){ae.set(`${t}:${e}`,s),Ct(t,e,s)}function re(t,e){return ae.get(`${t}:${e}`)}function He(t){return I.join(K(),".adam","wechat",`${t}.sync`)}function At(t){try{return T.readFileSync(He(t),"utf-8")}catch{return""}}function Pt(t,e){let s=He(t);T.mkdirSync(I.dirname(s),{recursive:!0}),T.writeFileSync(s,e,"utf-8")}var oe=1440*60*1e3,ze=10,vt=20,Ge=1440*60*1e3,Ot=1320*60*1e3,qt=1,Nt=7200*1e3;function Xe(t){return I.join(K(),".adam","wechat",`${t}.session.json`)}function $t(t){let e=new Map,s=Xe(t);try{let i=T.readFileSync(s,"utf-8"),n=JSON.parse(i);for(let[r,o]of Object.entries(n))o&&typeof o.lastUserMessageAt=="number"&&e.set(r,o);f.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function N(t,e){let s=Xe(t);try{let i={};for(let[r,o]of e)i[r]=o;let n=I.dirname(s);T.mkdirSync(n,{recursive:!0}),T.writeFileSync(s,JSON.stringify(i),"utf-8")}catch(i){f.warn({channelId:t},`Failed to persist sessions: ${String(i)}`)}}var Ft=0;function $(){return`adam-wechat-${Date.now()}-${++Ft}`}var G=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,s){if(this.id=e,!s.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=s}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=At(this.id),St(this.id),this.sessions=$t(this.id),this.pollAbort=new AbortController,this.status="connected",f.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",f.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&j(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}async sendMessage(e,s){if(j(this.id)){let c=Math.ceil(Me(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let i=this.getOrCreateSession(e),r=this.getSessionRemainingMs(i)/36e5;if(!this.isSessionActive(i))return f.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:i.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;if(i.quotaRemaining<=0)return f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:r.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,s),`queued-${$()}`;let o=$(),a=re(this.id,e),d=this.config.cdnBaseUrl??Ve;try{if(s.mediaUrl){let c=!s.mediaUrl.includes("://")||s.mediaUrl.startsWith("file://"),u=I.join(K(),".adam","wechat","media","outbound-tmp");await q.mkdir(u,{recursive:!0});let p=this.getExtensionFromMediaType(s.mediaType),l;if(c){let m=s.mediaUrl.startsWith("file://")?new URL(s.mediaUrl).pathname:I.isAbsolute(s.mediaUrl)?s.mediaUrl:I.resolve(s.mediaUrl),b=await q.readFile(m);l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await q.writeFile(l,b)}else{let m=await fetch(s.mediaUrl);if(!m.ok)throw new Error(`Failed to fetch media: ${m.status}`);let b=Buffer.from(await m.arrayBuffer());l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await q.writeFile(l,b)}let h=await Qe({filePath:l,to:e,text:s.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:a},cdnBaseUrl:d});return await q.unlink(l).catch(()=>{}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(m=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(m)}`)}),h.messageId}return await C({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:o,message_type:E.BOT,message_state:A.FINISH,item_list:s.content?[{type:y.TEXT,text_item:{text:s.content}}]:void 0,context_token:a}}}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(c=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(c)}`)}),o}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return i.quotaRemaining=0,N(this.id,this.sessions),f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(j(this.id))return;let s=re(this.id,e);try{await he({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:Te.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}getOrCreateSession(e){let s=this.sessions.get(e);return s||(s={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,s)),s}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=oe}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,oe-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,s){let i=this.pendingQueue.get(e);i||(i=[],this.pendingQueue.set(e,i));let n=Date.now();i=i.filter(r=>n-r.queuedAt<Ge),i.length>=vt&&(i.shift(),f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),i.push({message:s,queuedAt:n}),this.pendingQueue.set(e,i),f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:i.length},"Message enqueued")}async flushQueue(e){let s=this.pendingQueue.get(e);if(!s||s.length===0)return;let i=this.getOrCreateSession(e),n=Math.min(s.length,Math.max(0,i.quotaRemaining-2));if(n<=0){f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:s.length,sending:n,quotaRemaining:i.quotaRemaining},"Flushing queued messages");let r=0;for(;r<n&&s.length>0;){let o=s[0];if(Date.now()-o.queuedAt>Ge){s.shift();continue}try{if(await this.sendMessage(e,o.message),s.shift(),r++,i.quotaRemaining<=0)break}catch{f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}s.length===0&&this.pendingQueue.delete(e),f.info({channelId:this.id,chatId:e.slice(0,12),sent:r,remaining:s.length},"Queue flush complete")}async checkAndSendReminder(e,s){let i=Date.now(),n=this.lastReminderAt.get(e)??0;if(i-n<Nt)return;let r=this.getSessionRemainingMs(s),a=i-s.lastUserMessageAt>=Ot,d=s.quotaRemaining<=qt;if(!a&&!d)return;let c=(r/36e5).toFixed(1),u;a&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${s.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:a?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${s.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=re(this.id,e);try{await C({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:$(),message_type:E.BOT,message_state:A.FINISH,item_list:[{type:y.TEXT,text_item:{text:u}}],context_token:p}}}),s.quotaRemaining--,this.lastReminderAt.set(e,i),N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:s.quotaRemaining,trigger:a?"time":"quota"},"iLink session reminder sent")}catch(l){f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,s=0,i=3,n=3e4,r=2e3;for(;!e?.aborted;)try{let o=await fe({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===Z||o.errcode===Z){Re(this.id),this.status="error",f.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(B,e),Ue(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){s++,f.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e);continue}s=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Pt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(e?.aborted)return;s++,f.error({channelId:this.id,error:o},"getUpdates error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e)}}async processInbound(e){if(!this.messageHandler)return;let s=!!e.group_id,i=s?e.group_id:e.from_user_id??"",n=e.from_user_id??"";e.context_token&&i&&Et(this.id,i,e.context_token);let r=this.getOrCreateSession(i),o=r.quotaRemaining;r.lastUserMessageAt=Date.now(),r.quotaRemaining=ze,N(this.id,this.sessions),f.info({channelId:this.id,chatId:i.slice(0,12),quotaReset:!0,prevQuota:o,newQuota:ze,sessionWindowMs:oe},"iLink session reset: user message received, quota restored"),this.flushQueue(i);let a="",d,c=[];for(let l of e.item_list??[])l.type===y.TEXT&&l.text_item?.text&&(a+=l.text_item.text),l.type===y.IMAGE&&(d="image",c.push(l)),l.type===y.VOICE&&(d="audio",c.push(l),l.voice_item?.text&&!a&&(a=l.voice_item.text)),l.type===y.FILE&&(d="file",c.push(l)),l.type===y.VIDEO&&(d="video",c.push(l));if(!a&&!d)return;let u;if(c.length>0){let l=this.config.cdnBaseUrl??Ve;try{let h=await Le(c[0],{cdnBaseUrl:l,channelId:this.id});h&&(u=h.path,d=h.type)}catch(h){f.error({channelId:this.id},`Media download failed: ${String(h)}`)}}let p={channelId:this.id,platform:"wechat",chatId:i,senderId:n,content:a,mediaType:d,mediaPath:u,isGroup:s,timestamp:e.create_time_ms??Date.now(),raw:e};this.messageHandler(p)}getExtensionFromMediaType(e){switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,s){return new Promise((i,n)=>{let r=setTimeout(i,e);s?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};R();var Lt=_("channels"),H=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,s){if(this.id=e,!s.botToken)throw new Error("Discord adapter requires botToken");this.config=s}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:s}=await import("discord.js");this.client=new e({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]});let i=this.client;i.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let r={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(r)}),await i.login(this.config.botToken),this.status="connected",Lt.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}async sendMessage(e,s){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(e);if(!n||!("send"in n))throw new Error(`Channel ${e} not found or not text channel`);return(await n.send({content:s.content,reply:s.replyToMessageId?{messageReference:s.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let i=await this.client.channels.fetch(e);i&&"sendTyping"in i&&await i.sendTyping()}};var U=g.object({id:g.string().uuid()}),Wt=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),Bt=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),de;function es(t){de=t}function ts(){return de}async function ns(t){let e=de;t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(s,i)=>({channels:le(s.query.enabled)})),t.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(s,i)=>{let n=Wt.safeParse(s.body);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:c,allowedChatIds:u}=n.data,p={id:Dt(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:c,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return ue(p),i.status(201).send({channel:p})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?{channel:r}:i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.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(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Bt.safeParse(s.body);return o.success?(X(r.id,o.data),{channel:x(r.id)}):i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?(ge(r.id),i.status(204).send()):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e.hasAdapter(r.id)&&r.platform==="discord"){let o=r.config;if(!o.botToken)return i.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new H(r.id,{botToken:o.botToken});await e.addChannel(r,a)}if(!e.hasAdapter(r.id))return i.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await e.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return i.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);return r?(await e.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.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(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=s.query;return{messages:ce(r.id,o,a)}}),t.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(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await xe({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.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(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=s.body??{},c=await Ie({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(c.connected&&c.botToken){let u={...o,botToken:c.botToken,accountId:c.accountId,baseUrl:c.baseUrl??o.baseUrl,userId:c.userId};if(X(r.id,{config:u}),e){let p=new G(r.id,u),l=x(r.id);l&&await e.addChannel(l,p)}}return{connected:c.connected,accountId:c.accountId,message:c.message}})}export{G as a,H as b,es as c,ts as d,ns as e};
|
package/dist/chunk-7CJGPCSJ.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{a as I,b as C}from"./chunk-NLD7WK3R.js";import{d as _}from"./chunk-XTHP5JMO.js";import{a as k,b as T}from"./chunk-JZNBFZ7W.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as y}from"./chunk-IZGTTLTG.js";import{a as b,b as l,d,f as x}from"./chunk-IKUBP3SY.js";import{d as w}from"./chunk-7K4AQBDD.js";import{h as v,k as O}from"./chunk-OTH4M5L3.js";import{c as h,h as E}from"./chunk-INNDBLZE.js";E();O();import{v4 as c}from"uuid";import{CronExpressionParser as D}from"cron-parser";var n=h("scheduler"),m="ai-hourly-digest";function H(){if(l(m)){n.debug({templateId:m},"Built-in template already exists");return}let e={id:m,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},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};b(e),n.info({templateId:m,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var A=class{cronJobs=new Map;workflowExecutor=new _;started=!1;taskCompletionHandler=null;workflowCompletionHandler=null;async start(){if(this.started)return;this.started=!0,H();let e=d(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let i=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),i++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(o=>{n.error({taskId:r.taskId,error:o},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.workflowCompletionHandler=r=>{(r.status==="completed"||r.status==="partial")&&this.checkWorkflowEventTriggers(r.templateId).catch(o=>{n.error({templateId:r.templateId,error:o},"Workflow event trigger check failed")})},u.on("workflow_status_change",this.workflowCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:i},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=v(void 0,1e3,0),t=0;for(let i of e)t+=y(i.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.workflowCompletionHandler&&(u.off("workflow_status_change",this.workflowCompletionHandler),this.workflowCompletionHandler=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 i;try{i=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=i.next().getTime()-Date.now();return Math.max(p,1e3)},o=()=>{this.executeCronTrigger(e.id).catch(p=>{n.error({templateId:e.id,error:p},"Cron trigger failed")});let f=setTimeout(o,r());this.cronJobs.set(t,f)},s=r(),a=setTimeout(o,s);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+s).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,c()))}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}`,i=this.cronJobs.get(t);i&&(clearTimeout(i),this.cronJobs.delete(t))}async runNow(e){let t=l(e);if(!t)throw new Error(`Template ${e} not found`);let i=c();return this.executeWorkflow(t,i).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),i}async checkEventTriggers(e){let t=T(e);if(!t)return;let i=d(!0),r=i.filter(o=>o.trigger.type==="event"&&o.trigger.event==="task_complete");for(let o of r)n.debug({templateName:o.name},"Event trigger matched"),await this.executeWorkflow(o,c());if(t.templateId){let o=i.filter(s=>s.trigger.type!=="event"||!s.trigger.event?!1:s.trigger.event===`template_complete:${t.templateId}`);for(let s of o)n.info({templateName:s.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(s,c())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let r of e.goalIds){let o=C(r);if(!o){n.warn({goalId:r,templateId:e.id},"Goal reference not found, skipping");continue}let s=c();I({id:s,name:o.name,description:o.description,roleId:o.roleId,metricType:o.metricType,targetValue:o.targetValue,currentValue:0,deadline:o.deadline,budgetUsd:o.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let a=c();k({id:a,status:"pending",prompt:`Decompose and execute goal: ${o.name}. ${o.description??""}`,parentId:s,config:w(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:a}),n.info({templateId:e.id,sourceGoalId:r,newGoalId:s,taskId:a},"Goal reference triggered, dispatched decomposition task")}return}let i=await this.workflowExecutor.execute(e,t);n.info({templateName:e.name,executionId:t,status:i.status,steps:i.stepResults.size},"Workflow execution finished")}async checkWorkflowEventTriggers(e){let i=d(!0).filter(r=>r.trigger.type!=="event"||!r.trigger.event?!1:r.trigger.event===`workflow_complete:${e}`);for(let r of i)n.info({templateName:r.name,sourceTemplateId:e},"Workflow complete trigger matched"),await this.executeWorkflow(r,c())}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 o=`template-${e}`;this.cronJobs.has(o)&&clearTimeout(this.cronJobs.get(o));let s=setTimeout(()=>{this.cronJobs.delete(o),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(o,s),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,c()),x(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},J=null;function U(){return J}function z(g){J=g}export{A as a,U as b,z as c};
|
package/dist/chunk-NLD7WK3R.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{b as i,d as l}from"./chunk-4MJF77RD.js";l();function o(e){return{id:e.id,name:e.name,description:e.description??void 0,roleId:e.role,metricType:e.metric_type,targetValue:e.target_value,currentValue:e.current_value,deadline:e.deadline,budgetUsd:e.budget_usd,status:e.status,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0}}function c(e){i().prepare(`
|
|
2
|
-
INSERT INTO goals (id, name, description, role, metric_type, target_value,
|
|
3
|
-
current_value, deadline, budget_usd, status, created_at, updated_at,
|
|
4
|
-
source_session_id, deliver_to, report_to)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(e.id,e.name,e.description??null,e.roleId,e.metricType,e.targetValue,e.currentValue,e.deadline,e.budgetUsd,e.status,e.createdAt,e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null)}function _(e){let s=i().prepare("SELECT * FROM goals WHERE id = ?").get(e);return s?o(s):void 0}function g(e,t){let s=i(),n=[],r=[],d={name:"name",description:"description",roleId:"role",metricType:"metric_type",targetValue:"target_value",currentValue:"current_value",deadline:"deadline",budgetUsd:"budget_usd",status:"status",updatedAt:"updated_at",sourceSessionId:"source_session_id"};for(let[u,a]of Object.entries(d))u in t&&(n.push(`${a} = ?`),r.push(t[u]??null));"deliverTo"in t&&(n.push("deliver_to = ?"),r.push(JSON.stringify(t.deliverTo))),"reportTo"in t&&(n.push("report_to = ?"),r.push(JSON.stringify(t.reportTo))),n.length!==0&&(r.push(e),s.prepare(`UPDATE goals SET ${n.join(", ")} WHERE id = ?`).run(...r))}function f(e,t=100,s=0){let n=i(),r="SELECT * FROM goals",d=[];return e&&(r+=" WHERE status = ?",d.push(e)),r+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(t,s),n.prepare(r).all(...d).map(o)}function m(e){i().prepare("DELETE FROM goals WHERE id = ?").run(e)}export{c as a,_ as b,g as c,f as d,m as e};
|
package/dist/chunk-OTH4M5L3.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{a as u,g as O}from"./chunk-WKS7QVIX.js";import{b as l,d as R}from"./chunk-4MJF77RD.js";import{b as a,h}from"./chunk-WBAPIPST.js";import{c as m,e as v}from"./chunk-FCV2DPZQ.js";import*as _ from"os";import*as g from"path";function d(e){return e.startsWith("~/")||e==="~"?g.join(_.homedir(),e.slice(1)):e}var S=m(()=>{"use strict";h()});var x={};v(x,{createRole:()=>E,deleteRole:()=>T,getRole:()=>N,getRoleByName:()=>b,listRoles:()=>J,updateRole:()=>w,validateAdditionalDirectories:()=>p});import{existsSync as y}from"fs";import{resolve as c}from"path";function p(e,n){for(let s of e){let i=typeof s=="string"?s:s.path;if(!i.startsWith("/")&&!i.startsWith("~/")&&i!=="~")throw new Error(`additionalDirectories must be absolute paths: '${i}' is not absolute`);let r=c(d(i));if(!r.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${i}' is not absolute`);for(let t of a){let o=c(d(t));if(r.startsWith(o))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${i}' matches '${t}'`)}if(n?.length)for(let t of n){let o=c(d(t));if(r.startsWith(o)||o.startsWith(r))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${i}' conflicts with '${t}'`)}if(!y(r))throw new Error(`additionalDirectories path does not exist: '${i}'`)}}function f(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let n=JSON.parse(e.additional_directories);return Array.isArray(n)?n.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0}}function E(e){let n=u("defaults.deniedReadPaths")??[...a];e.additionalDirectories&&p(e.additionalDirectories,n),l().prepare(`
|
|
2
|
-
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
3
|
-
performance_score, preferences, created_at, updated_at,
|
|
4
|
-
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
5
|
-
max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings,
|
|
6
|
-
permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars)
|
|
7
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
-
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null)}function N(e){let s=l().prepare("SELECT * FROM roles WHERE id = ?").get(e);return s?f(s):void 0}function b(e){let s=l().prepare("SELECT * FROM roles WHERE name = ?").get(e);return s?f(s):void 0}function w(e,n){let s=l(),i=[],r=[];if("name"in n&&(i.push("name = ?"),r.push(n.name)),"cagPrompt"in n&&(i.push("cag_prompt = ?"),r.push(n.cagPrompt)),"learnedRules"in n&&(i.push("learned_rules = ?"),r.push(JSON.stringify(n.learnedRules))),"memoryStreamId"in n&&(i.push("memory_stream_id = ?"),r.push(n.memoryStreamId)),"status"in n&&(i.push("status = ?"),r.push(n.status)),"performanceScore"in n&&(i.push("performance_score = ?"),r.push(n.performanceScore??null)),"preferences"in n&&(i.push("preferences = ?"),r.push(n.preferences?JSON.stringify(n.preferences):null)),"updatedAt"in n&&(i.push("updated_at = ?"),r.push(n.updatedAt??null)),"allowedTools"in n&&(i.push("allowed_tools = ?"),r.push(n.allowedTools?JSON.stringify(n.allowedTools):null)),"disallowedTools"in n&&(i.push("disallowed_tools = ?"),r.push(n.disallowedTools?JSON.stringify(n.disallowedTools):null)),"evaluationCriteria"in n&&(i.push("evaluation_criteria = ?"),r.push(n.evaluationCriteria?JSON.stringify(n.evaluationCriteria):null)),"executionMode"in n&&(i.push("execution_mode = ?"),r.push(n.executionMode??null)),"model"in n&&(i.push("model = ?"),r.push(n.model??null)),"maxBudgetUsd"in n&&(i.push("max_budget_usd = ?"),r.push(n.maxBudgetUsd??null)),"approvalRequired"in n&&(i.push("approval_required = ?"),r.push(n.approvalRequired?JSON.stringify(n.approvalRequired):null)),"source"in n&&(i.push("source = ?"),r.push(n.source??null)),"additionalDirectories"in n){let t=u("defaults.deniedReadPaths")??[...a];n.additionalDirectories&&p(n.additionalDirectories,t),i.push("additional_directories = ?"),r.push(n.additionalDirectories?JSON.stringify(n.additionalDirectories):null)}"allowedChannels"in n&&(i.push("allowed_channels = ?"),r.push(n.allowedChannels?JSON.stringify(n.allowedChannels):null)),"mcpServers"in n&&(i.push("mcp_servers = ?"),r.push(n.mcpServers?JSON.stringify(n.mcpServers):null)),"inheritUserSettings"in n&&(i.push("inherit_user_settings = ?"),r.push(n.inheritUserSettings?1:0)),"permissionMode"in n&&(i.push("permission_mode = ?"),r.push(n.permissionMode??null)),"allowedBashPatterns"in n&&(i.push("allowed_bash_patterns = ?"),r.push(n.allowedBashPatterns?JSON.stringify(n.allowedBashPatterns):null)),"deniedBashPatterns"in n&&(i.push("denied_bash_patterns = ?"),r.push(n.deniedBashPatterns?JSON.stringify(n.deniedBashPatterns):null)),"envVars"in n&&(i.push("env_vars = ?"),r.push(n.envVars?JSON.stringify(n.envVars):null)),i.length!==0&&(r.push(e),s.prepare(`UPDATE roles SET ${i.join(", ")} WHERE id = ?`).run(...r))}function J(e,n=100,s=0){let i=l(),r="SELECT * FROM roles",t=[];return e&&(r+=" WHERE status = ?",t.push(e)),r+=" ORDER BY created_at ASC LIMIT ? OFFSET ?",t.push(n,s),i.prepare(r).all(...t).map(f)}function T(e){l().prepare("DELETE FROM roles WHERE id = ?").run(e)}var D=m(()=>{R();h();S();O()});export{d as a,S as b,p as c,E as d,N as e,b as f,w as g,J as h,T as i,x as j,D as k};
|