adam-agent-server 0.5.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -4
- package/dist/App-RIYRYLKD.js +9 -0
- package/dist/adam-tools-YBKSTHVJ.js +1 -0
- package/dist/approval-handler-JYIS2PKQ.js +1 -0
- package/dist/audit-manager-7M2CDMP5.js +1 -0
- package/dist/bree-engine-Y24K4PXN.js +1 -0
- package/dist/channels-WMCY4QC3.js +1 -0
- package/dist/channels-WZOYE4O4.js +1 -0
- package/dist/chunk-2CMR5AG7.js +1 -0
- package/dist/chunk-2HN2TSP6.js +5 -0
- package/dist/{chunk-L7426WNY.js → chunk-3RAFA6QK.js} +1 -1
- package/dist/{chunk-HAWA62R2.js → chunk-4TCP2AT7.js} +1 -1
- package/dist/chunk-5V36ACKZ.js +1 -0
- package/dist/{chunk-VF6GJGD6.js → chunk-6DXNXLYG.js} +1 -1
- package/dist/chunk-6HD6NYIB.js +1 -0
- package/dist/chunk-6KLG4APZ.js +1 -0
- package/dist/{chunk-KICPHTI2.js → chunk-6YURWVQG.js} +1 -1
- package/dist/chunk-7IFLU3CY.js +4 -0
- package/dist/chunk-7LBDLAUQ.js +2 -0
- package/dist/{chunk-5ASEAZCR.js → chunk-AJVN3KPM.js} +1 -1
- package/dist/{chunk-742NWPTQ.js → chunk-AR2IZMM2.js} +1 -1
- package/dist/chunk-B4WHT7DX.js +8 -0
- package/dist/{chunk-TN6H2WM2.js → chunk-BIIP363C.js} +3 -3
- package/dist/{chunk-WXN3PSVX.js → chunk-CDVIT7L5.js} +1 -1
- package/dist/chunk-EGS6U3V5.js +3 -0
- package/dist/{chunk-IXF3XBGX.js → chunk-EJVUUIAV.js} +1 -1
- package/dist/{chunk-AXMXXUPO.js → chunk-GMCIKDTC.js} +1 -1
- package/dist/{chunk-2GXYBWLS.js → chunk-GUQAIWCQ.js} +1 -1
- package/dist/chunk-IHP7JV6J.js +1 -0
- package/dist/chunk-INNDBLZE.js +1 -0
- package/dist/chunk-JTMFEUDA.js +1 -0
- package/dist/chunk-KLQOILIJ.js +21 -0
- package/dist/{chunk-PCSZW2PE.js → chunk-KVSO3KGZ.js} +7 -7
- package/dist/{chunk-FUGJMHY4.js → chunk-MPRAVJUO.js} +1 -1
- package/dist/chunk-OEKM2W3K.js +4 -0
- package/dist/{chunk-FDWW245P.js → chunk-OFOVSC72.js} +1 -1
- package/dist/chunk-PMHNW5IL.js +49 -0
- package/dist/chunk-Q4YE5BU7.js +49 -0
- package/dist/{chunk-B6S2AEOD.js → chunk-QN6BEJF5.js} +1 -1
- package/dist/{chunk-PQ7KPALO.js → chunk-SWPXG2CY.js} +1 -1
- package/dist/chunk-U5NRQNBB.js +67 -0
- package/dist/chunk-UW3OJG7U.js +83 -0
- package/dist/chunk-VRP4LTHY.js +1 -0
- package/dist/chunk-WBAPIPST.js +1 -0
- package/dist/chunk-WVGNP2LQ.js +3 -0
- package/dist/cli.js +5 -5
- package/dist/config-EI3SCA4W.js +1 -0
- package/dist/config-OH6Q2D2Y.js +1 -0
- package/dist/db-4NY7ZOS2.js +1 -0
- package/dist/delivery-log-SC2ULFCK.js +1 -0
- package/dist/engine-JKSNQQDM.js +1 -0
- package/dist/evolution-audit-KUBXFUHI.js +1 -0
- package/dist/external-api-I6CENLIS.js +1 -0
- package/dist/index.js +12 -57
- package/dist/learner-UYDFNURD.js +1 -0
- package/dist/logger-QCJUU7GV.js +1 -0
- package/dist/memories-FQCRKMK6.js +1 -0
- package/dist/{memory-extractor-GOISDQTO.js → memory-extractor-FUOJ5D77.js} +2 -2
- package/dist/memory-service-ANR67OPY.js +1 -0
- package/dist/outbound-gateway-6FQRWYFF.js +1 -0
- package/dist/role-presets-LRP6P5O2.js +1 -0
- package/dist/roles-3UTFKSHI.js +1 -0
- package/dist/runtime-B2DP3JNB.js +1 -0
- package/dist/session-manager-VYKNKQ46.js +1 -0
- package/dist/task-templates-PSP7GOJJ.js +1 -0
- package/package.json +2 -1
- package/web/dist/assets/Card-4mOZntHG.js +1 -0
- package/web/dist/assets/ChannelDetail-e6rVX_y8.js +1 -0
- package/web/dist/assets/Channels-DJvZPKer.js +12 -0
- package/web/dist/assets/Chat-hTZdEwyE.js +1 -0
- package/web/dist/assets/Dashboard-B4rL_ePs.js +1 -0
- package/web/dist/assets/{EmptyState-DBFJc4PL.js → EmptyState-BlgMMAr-.js} +1 -1
- package/web/dist/assets/EnvVarEditor-C8kRWejV.js +1 -0
- package/web/dist/assets/Evolution-BGwFCo7X.js +6 -0
- package/web/dist/assets/GoalDetail-BH2ku-0t.js +1 -0
- package/web/dist/assets/Goals-DynDtpMC.js +1 -0
- package/web/dist/assets/Logs-CyJFouE6.js +1 -0
- package/web/dist/assets/Memories-ClcFD7OG.js +1 -0
- package/web/dist/assets/{NotFound-Cidygwnn.js → NotFound-CSjhzSGa.js} +1 -1
- package/web/dist/assets/Plugins-SNOQNNcL.js +1 -0
- package/web/dist/assets/RoleDetail-vlTPiYwY.js +33 -0
- package/web/dist/assets/Roles-CFcuHIvA.js +1 -0
- package/web/dist/assets/Settings-C9Kuz-6D.js +1 -0
- package/web/dist/assets/Strategies-DZWlQCHp.js +1 -0
- package/web/dist/assets/Switch-DOi0EFHj.js +1 -0
- package/web/dist/assets/Table-BxbnOSbq.js +1 -0
- package/web/dist/assets/TaskDetail-DjmmnldI.js +2 -0
- package/web/dist/assets/Work-CvESHC3Y.js +1 -0
- package/web/dist/assets/index-BFmC20R2.js +52 -0
- package/web/dist/assets/index-CaocwyO8.css +2 -0
- package/web/dist/assets/{vendor-icons-ZPvC5PUS.js → vendor-icons-CkI4-NxL.js} +1 -1
- package/web/dist/assets/{vendor-react--nRVf2Ep.js → vendor-react-DLRtONKt.js} +1 -1
- package/web/dist/assets/vendor-state-B_-GdGNJ.js +1 -0
- package/web/dist/index.html +5 -5
- package/dist/App-XZABZ2AF.js +0 -9
- package/dist/adam-tools-BB7WQGVT.js +0 -1
- package/dist/approval-handler-HK7GQPHU.js +0 -4
- package/dist/bree-engine-25VACELK.js +0 -1
- package/dist/channels-JEBBMFUQ.js +0 -1
- package/dist/channels-VEUBY2NZ.js +0 -1
- package/dist/chunk-3DAK2XWP.js +0 -1
- package/dist/chunk-5JLMSNIW.js +0 -1
- package/dist/chunk-7SPKRIMZ.js +0 -15
- package/dist/chunk-BREBCBG4.js +0 -49
- package/dist/chunk-D6WM2OQS.js +0 -86
- package/dist/chunk-DWMMWYLD.js +0 -1
- package/dist/chunk-ETQ7KC73.js +0 -1
- package/dist/chunk-FYDFMYUP.js +0 -1
- package/dist/chunk-JXD6ZPV7.js +0 -2
- package/dist/chunk-NSJAV7IH.js +0 -1
- package/dist/chunk-NXTTKAQX.js +0 -3
- package/dist/chunk-SFUS33SO.js +0 -1
- package/dist/chunk-T25NLVMY.js +0 -1
- package/dist/chunk-T7WVM27S.js +0 -52
- package/dist/chunk-U36NBCR3.js +0 -17
- package/dist/chunk-URW2DJQF.js +0 -1
- package/dist/chunk-WZOMGJSY.js +0 -1
- package/dist/chunk-XNWZZYAV.js +0 -7
- package/dist/config-WHXCZCI4.js +0 -1
- package/dist/config-Y4QWELO3.js +0 -1
- package/dist/db-PNZ3UJOE.js +0 -1
- package/dist/delivery-log-VYTYUFCK.js +0 -1
- package/dist/engine-3PNNEZNK.js +0 -1
- package/dist/evolution-audit-B7WKMOVR.js +0 -1
- package/dist/external-api-XGEOKAWR.js +0 -1
- package/dist/learner-VMD5NQCD.js +0 -1
- package/dist/logger-BEG4WFIM.js +0 -1
- package/dist/memories-EFQ4SFZG.js +0 -1
- package/dist/memory-service-BKLZIRK6.js +0 -1
- package/dist/monitor-K7CGTLA6.js +0 -1
- package/dist/outbound-gateway-DZTXBUTP.js +0 -1
- package/dist/role-presets-FN2RWUCP.js +0 -1
- package/dist/roles-SG2YAR64.js +0 -1
- package/dist/runtime-6UTYEONR.js +0 -1
- package/dist/session-manager-45LFTPBA.js +0 -1
- package/dist/task-templates-7LSQ6OST.js +0 -1
- package/web/dist/assets/Card-BecEmnPW.js +0 -1
- package/web/dist/assets/ChannelDetail-dZfZlLgQ.js +0 -1
- package/web/dist/assets/Channels-Cw04c7YJ.js +0 -12
- package/web/dist/assets/Chat-D4PHqHPE.js +0 -1
- package/web/dist/assets/Dashboard-BFewwmAg.js +0 -1
- package/web/dist/assets/Evolution-DY1OC6Oc.js +0 -6
- package/web/dist/assets/GoalDetail-DZIEpHs2.js +0 -1
- package/web/dist/assets/Goals-COCCVLnp.js +0 -1
- package/web/dist/assets/Logs-DsDeimLt.js +0 -1
- package/web/dist/assets/Memories-D5IEEI1u.js +0 -1
- package/web/dist/assets/Plugins-DUwZVjPc.js +0 -1
- package/web/dist/assets/RoleDetail-B-GKMfMG.js +0 -33
- package/web/dist/assets/Roles-JeVjD0Ew.js +0 -1
- package/web/dist/assets/Settings-CvEyZp5t.js +0 -1
- package/web/dist/assets/Strategies-KAmpqrcQ.js +0 -1
- package/web/dist/assets/Switch-Jpdn6Yux.js +0 -1
- package/web/dist/assets/Table-tkJ-cuiE.js +0 -1
- package/web/dist/assets/TaskDetail-C4NpqwNT.js +0 -2
- package/web/dist/assets/Work-DhaxNYnd.js +0 -1
- package/web/dist/assets/index-CfKqiQIe.js +0 -52
- package/web/dist/assets/index-LDFr0VVR.css +0 -2
- package/web/dist/assets/vendor-state-CH64feAE.js +0 -1
package/README.md
CHANGED
|
@@ -182,10 +182,8 @@ defaults:
|
|
|
182
182
|
effort: high # low | medium | high | max
|
|
183
183
|
model: claude-sonnet-4-6
|
|
184
184
|
settingSources: ["user", "project"]
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
deniedPaths: ["~/.ssh", "~/.aws", "~/.config"]
|
|
188
|
-
approvalRequired: ["rm -rf", "git push", "git reset"]
|
|
185
|
+
deniedReadPaths: ["~/.ssh", "~/.aws", "~/.gnupg", "/etc/shadow"]
|
|
186
|
+
approvalRequired: ["rm -rf *", "git push*", "git reset*"]
|
|
189
187
|
approvalTimeout: 300
|
|
190
188
|
|
|
191
189
|
execution:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{b as v,d as Ht,e as Ro}from"./chunk-VRP4LTHY.js";import{a as Gt,f as Ao,h as Do}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as qt,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 Ht("/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 b=await v(`/tasks/${a.taskId}`);u&&b.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 v("/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(b=>{let p=b[b.length-1];if(p?.type==="reasoning"){let y=[...b];return y[y.length-1]={...p,content:p.content+d},y}return[...b,{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 b=(await v("/chat/sessions?status=active")).sessions.find(p=>p.source.type==="tui");return b?ao(b):null}catch{return null}},[]),i=Dt(async()=>{try{let d=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),b=ao(d.session);return t(b),b}catch{return m("Failed to create session"),null}},[]),n=Dt(async d=>{try{let b=await v("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(p=>p&&{...p,messageCount:p.messageCount+1,lastActiveAt:Date.now()}),b}catch{return null}},[]),r=Dt(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),a=Dt(async()=>{if(e)try{let d=await v(`/chat/sessions/${e.id}`);t(ao(d.session))}catch{t(null)}},[e]);return Fr(()=>{let d=!1;async function b(){c(!0);let p=await l();d||(p?t(p):await i(),d||c(!1))}return b(),()=>{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 Ht("/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 Le}from"ink";import Ne from"chalk";var lo={connected:Ne.green,disconnected:Ne.red,warning:Ne.yellow,reasoning:Ne.gray,toolCall:Ne.blue,toolResult:Ne.green,error:Ne.red,dim:Ne.dim,bold:Ne.bold,statusUp:Ne.green("\u25CF"),statusDown:Ne.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(Le,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ut(Le,{children:" \u2502 "}),ut(Le,{children:t}),ut(Le,{children:" \u2502 "}),it(Le,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&it(Gr,{children:[ut(Le,{children:" \u2502 "}),it(Le,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),m&&ut(Le,{color:"yellow",children:" timeout soon"})]})]}),it(co,{children:[it(Le,{children:["Tasks: ",o]}),ut(Le,{children:" \u2502 "}),it(Le,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Kt,Text as jt,useInput as Kr}from"ink";import{useState as mo,useMemo as jr}from"react";import Qr 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=jr(()=>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 y=p.slice(1),s=Go(y);e(s?`/${s.name}`:p)}else e(p);o(""),l(!1)}},b=p=>{e(`/${p.name}`),o(""),l(!1)};return Kr((p,y)=>{if(!(!m||!i||r.length===0)){if(y.upArrow){u(s=>s<=0?r.length-1:s-1);return}if(y.downArrow){u(s=>s>=r.length-1?0:s+1);return}if(y.tab){let s=r[c];s&&b(s);return}if(y.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,y)=>{let s=y===c;return Rt(Kt,{children:[Qt(jt,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),Rt(jt,{color:s?"cyan":"white",bold:s,children:["/",p.name]}),Rt(jt,{dimColor:!0,children:[" \u2014 ",p.description]})]},p.name)})}),Rt(Kt,{borderStyle:"round",borderDimColor:!0,children:[Qt(jt,{bold:!0,children:"\u25B8 "}),Qt(Qr,{value:t,onChange:a,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as ht,Text as Se}from"ink";import{useState as Xr}from"react";import{jsx as Pe,jsxs as Ue}from"react/jsx-runtime";function zr({content:e}){let[t,o]=Xr(!1),c=e.split(`
|
|
2
|
+
`);return c.length<=5?Pe(Se,{color:"green",children:e}):t?Pe(Se,{color:"green",children:e}):Ue(Se,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
+
`),`
|
|
4
|
+
`,Ue(Se,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function Yr({event:e}){switch(e.type){case"reasoning":return Pe(ht,{children:Pe(Se,{color:"gray",children:e.content})});case"tool_call":return Pe(ht,{children:Ue(Se,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ue(ht,{flexDirection:"column",children:[Pe(Se,{color:"blue",dimColor:!0,children:"[result]"}),Pe(zr,{content:e.content})]});case"error":return Pe(ht,{children:Ue(Se,{color:"red",children:["[error] ",e.content]})});case"complete":return Ue(ht,{flexDirection:"column",marginTop:1,children:[e.content&&Pe(Se,{children:e.content}),Pe(Se,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ue(Se,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ue(Se,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ue(Se,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function Ko({events:e,isStreaming:t}){return e.length===0&&!t?null:Ue(ht,{flexDirection:"column",children:[t&&e.length===0&&Pe(Se,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>Pe(Yr,{event:o},c))]})}import{Box as jo,Text as Qo}from"ink";import{jsx as go,jsxs as Jr}from"react/jsx-runtime";function Xo({messages:e}){return e.length===0?null:go(jo,{flexDirection:"column",children:e.map((t,o)=>Jr(jo,{flexDirection:"column",marginBottom:1,children:[go(Qo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),go(Qo,{children:t.content})]},o))})}import{Box as Mt,Text as We,useInput as Zr}from"ink";import{jsx as Ge,jsxs as Nt}from"react/jsx-runtime";function zo({approval:e,onResolved:t}){return Zr(o=>{o==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&v(`/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:[Ge(We,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Nt(Mt,{marginTop:1,children:[Ge(We,{children:"Tool: "}),Ge(We,{bold:!0,children:e.toolName})]}),Nt(Mt,{children:[Ge(We,{children:"Input: "}),Ge(We,{children:JSON.stringify(e.toolInput)})]}),Nt(Mt,{children:[Ge(We,{children:"Pattern: "}),Ge(We,{dimColor:!0,children:e.matchedPattern})]}),Nt(Mt,{marginTop:1,children:[Ge(We,{color:"green",children:"[a] Approve"}),Ge(We,{children:" "}),Ge(We,{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 ze,jsxs as _e}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"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&v(`/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 _e(Lt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ze(he,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),_e(he,{dimColor:!0,children:["Plan ID: ",e.planId]}),_e(he,{dimColor:!0,children:["Time remaining: ",c,"s"]}),_e(Lt,{marginTop:1,children:[ze(he,{children:"Overall Risk: "}),ze(he,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),_e(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 _e(Lt,{paddingLeft:2,children:[_e(he,{children:["[",l.index,"] "]}),ze(he,{children:l.description}),_e(he,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),_e(he,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),_e(Lt,{marginTop:1,children:[ze(he,{dimColor:!0,children:"Permissions: "}),ze(he,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),_e(Lt,{marginTop:1,children:[ze(he,{color:"green",children:"[a] Allow once "}),ze(he,{color:"green",children:"[p] Allow permanent "}),ze(he,{color:"red",children:"[r] Deny"})]})]})}import{Box as mt,Text as ie,useInput as an}from"ink";import{useEffect as ln,useState as Ye,useCallback as Zo}from"react";import{Box as te,Text as L,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(()=>{v(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),v(`/tasks/${e}/plan`).then(r=>m(r.plans)).catch(()=>m([]))},[e]),nn((r,a)=>{(r==="b"||a.escape)&&t()}),l)return K(te,{flexDirection:"column",children:[K(L,{color:"red",children:["Error: ",l]}),U(L,{dimColor:!0,children:"[b] Back"})]});if(!o)return K(L,{dimColor:!0,children:["Loading task ",e,"..."]});let n=u[0];return K(te,{flexDirection:"column",children:[U(L,{bold:!0,color:"cyan",children:"Task Detail"}),K(te,{marginTop:1,flexDirection:"column",children:[K(te,{children:[U(L,{children:"ID: "}),U(L,{dimColor:!0,children:String(o.id)})]}),K(te,{children:[U(L,{children:"Status: "}),U(L,{bold:!0,children:String(o.status)})]}),K(te,{children:[U(L,{children:"Prompt: "}),U(L,{children:String(o.prompt)})]}),o.result?K(te,{children:[U(L,{children:"Result: "}),U(L,{children:String(o.result).slice(0,200)})]}):null,o.error?K(te,{children:[U(L,{color:"red",children:"Error: "}),U(L,{children:String(o.error)})]}):null,o.deliverTo?.length?K(te,{children:[U(L,{children:"DeliverTo: "}),U(L,{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(te,{children:[U(L,{children:"ReportTo: "}),U(L,{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(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"cyan",children:"Execution Plan"}),K(te,{children:[U(L,{children:"Plan ID: "}),U(L,{dimColor:!0,children:n.id})]}),K(te,{children:[U(L,{children:"Status: "}),U(L,{children:n.status})]}),n.plan.overallRisk&&K(te,{children:[U(L,{children:"Overall Risk: "}),U(L,{bold:!0,color:n.plan.overallRisk==="high"?"red":n.plan.overallRisk==="medium"?"yellow":"green",children:n.plan.overallRisk.toUpperCase()})]}),K(L,{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(te,{paddingLeft:2,children:[K(L,{children:["[",r.index,"] ",r.description]}),K(L,{color:a,children:[" [",r.riskLevel,"]"]})]},r.index)}),n.deviationReport&&K(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"yellow",children:"Deviation Report"}),K(L,{children:["Planned: ",n.deviationReport.stepsPlanned," | Executed: ",n.deviationReport.stepsExecuted," | Accuracy: ",(n.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),n.deviationReport.deviations.map((r,a)=>K(te,{paddingLeft:2,children:[K(L,{color:"yellow",children:["[",r.deviationType,"] "]}),K(L,{children:["Step ",r.stepIndex,": ",r.actual]})]},a))]}),n.learnedRules&&n.learnedRules.length>0&&K(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"blue",children:"Learned Rules"}),n.learnedRules.map((r,a)=>U(te,{paddingLeft:2,children:K(L,{children:["* ",r]})},a))]})]}),!n&&u.length===0&&U(te,{marginTop:1,children:U(L,{dimColor:!0,children:"No execution plan for this task."})}),U(te,{marginTop:1,children:U(L,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as un,jsx as ve,jsxs as Be}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 zt({onBack:e}){let[t,o]=Ye([]),[c,u]=Ye(!0),[m,l]=Ye("list"),[i,n]=Ye(0),[r,a]=Ye("all"),[d,b]=Ye(0),[p,y]=Ye(0),[s,g]=Ye(null),[_,M]=Ye([]),Y=Zo(async()=>{u(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let P=await v(`/tasks?${I}`);o(P.tasks)}catch{o([])}finally{u(!1)}},[r]);ln(()=>{Y()},[Y]);let H=Math.max(1,Math.ceil(t.length/po)),O=t.slice(p*po,(p+1)*po),X=Zo(async()=>{let I=O[i];if(I)try{await v(`/tasks/${I.id}/cancel`,{method:"POST"}),g(`Cancelled: ${I.id.slice(0,8)}`),l("list"),Y()}catch(P){g(`Failed: ${P instanceof Error?P.message:String(P)}`),l("list")}},[O,i,Y]);return an((I,P)=>{if(m==="detail"){(P.escape||P.return||I==="q")&&l("list");return}if(m==="cancelling"){I==="y"?X():l("list");return}if(m==="filter"){if(P.escape){l("list");return}P.upArrow&&d>0&&b(S=>S-1),P.downArrow&&d<Xt.length-1&&b(S=>S+1),P.return&&(a(Xt[d]),y(0),n(0),l("list"));return}if(P.escape||I==="q"){e();return}if(P.upArrow&&i>0&&n(S=>S-1),P.downArrow&&i<O.length-1&&n(S=>S+1),P.return){let S=O[i];S&&(M([]),l("detail"),v(`/tasks/${S.id}/logs?limit=20`).then(({logs:j})=>M(j)).catch(()=>M([])))}if(I==="x"&&O[i]){let S=O[i];["running","pending","queued","paused"].includes(S.status)?(l("cancelling"),g(null)):g(`Cannot cancel task in status: ${S.status}`)}I==="f"&&(b(Xt.indexOf(r)),l("filter")),I==="r"&&Y(),(P.pageDown||I==="n")&&p<H-1&&(y(S=>S+1),n(0)),(P.pageUp||I==="p")&&p>0&&(y(S=>S-1),n(0))}),c?ve(ie,{dimColor:!0,children:"Loading tasks..."}):m==="filter"?Be(mt,{flexDirection:"column",children:[ve(ie,{bold:!0,children:"Filter by status:"}),Xt.map((I,P)=>ve(mt,{children:Be(ie,{color:P===d?"cyan":"white",children:[P===d?"> ":" ",I,I===r?" (current)":""]})},I)),ve(ie,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):m==="detail"&&O[i]?ve(Jo,{taskId:O[i].id,onBack:()=>l("list")}):m==="cancelling"&&O[i]?Be(mt,{flexDirection:"column",children:[Be(ie,{color:"red",children:['Cancel task "',O[i].id.slice(0,8),'"? (y/n)']}),s&&ve(ie,{color:"red",children:s})]}):Be(mt,{flexDirection:"column",children:[Be(mt,{children:[Be(ie,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&Be(ie,{dimColor:!0,children:[" [filter: ",r,"]"]}),Be(ie,{dimColor:!0,children:[" \u2014 Page ",p+1,"/",H]})]}),s&&ve(ie,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?Be(ie,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):Be(un,{children:[ve(mt,{marginTop:1,children:Be(ie,{bold:!0,children:[" ",at("ID",10),at("STATUS",12),at("PROMPT",40),at("DURATION",10),"COST"]})}),O.map((I,P)=>{let S=P===i,j=I.totalDurationMs?`${(I.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",J=I.costUsd!==void 0?`$${I.costUsd.toFixed(4)}`:"\u2014",Re=cn[I.status]??"white";return Be(mt,{children:[ve(ie,{color:S?"cyan":"white",children:S?"> ":" "}),ve(ie,{dimColor:!0,children:at(I.id.slice(0,8),10)}),ve(ie,{color:Re,children:at(I.status,12)}),ve(ie,{children:at(dn(I.prompt,38),40)}),ve(ie,{dimColor:!0,children:at(j,10)}),ve(ie,{dimColor:!0,children:J})]},I.id)})]}),ve(ie,{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 Ve,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 $e,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:[$e(Ve,{color:"red",children:c}),$e(Ve,{dimColor:!0,children:"Press Esc to go back"})]}):t?lt(_t,{flexDirection:"column",children:[$e(Ve,{bold:!0,children:"Configuration (Esc to go back)"}),$e(_t,{marginTop:1,flexDirection:"column",children:$e(rr,{obj:t,indent:0})})]}):$e(Ve,{dimColor:!0,children:"Loading config..."})}function rr({obj:e,indent:t}){let o=" ".repeat(t);return $e(Tn,{children:Object.entries(e).map(([c,u])=>u&&typeof u=="object"&&!Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt(Ve,{children:[o,$e(Ve,{color:"cyan",children:c}),":"]}),$e(rr,{obj:u,indent:t+1})]},c):Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt(Ve,{children:[o,$e(Ve,{color:"cyan",children:c}),":"]}),u.map((m,l)=>lt(Ve,{children:[o," - ",tr(c,String(m))]},l))]},c):lt(Ve,{children:[o,$e(Ve,{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 Yt,Text as Oe,useInput as hn}from"ink";import{useEffect as vn,useState as xo}from"react";import{jsx as Vt,jsxs as He}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()}),vn(()=>{v("/evolution-audit?limit=20").then(i=>{o(i),u(!1)}).catch(i=>{l(i.message),u(!1)})},[]),c?Vt(Oe,{dimColor:!0,children:"Loading evolution log..."}):m?He(Yt,{flexDirection:"column",children:[Vt(Oe,{color:"red",children:m}),Vt(Oe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?He(Yt,{flexDirection:"column",children:[Vt(Oe,{dimColor:!0,children:"No evolution records yet"}),Vt(Oe,{dimColor:!0,children:"Press Esc to go back"})]}):He(Yt,{flexDirection:"column",children:[He(Oe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>He(Yt,{flexDirection:"column",marginTop:1,children:[He(Oe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&He(Oe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
+
`).map((n,r)=>n.startsWith("+")?He(Oe,{color:"green",children:[" ",n]},r):n.startsWith("-")?He(Oe,{color:"red",children:[" ",n]},r):He(Oe,{dimColor:!0,children:[" ",n]},r))]},i.id))]})}import{Box as Je,Text as oe,useInput as yn}from"ink";import bn from"ink-text-input";import{useEffect as Sn,useState as vt}from"react";import{jsx as Ce,jsxs as me}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 Jt({onBack:e}){let[t,o]=vt([]),[c,u]=vt(null),[m,l]=vt("list"),[i,n]=vt(""),[r,a]=vt(!1),[d,b]=vt(null);yn((s,g)=>{if(m==="create"){g.escape&&(l("list"),n(""),b(null));return}(g.escape||s==="q")&&e(),s==="c"&&(l("create"),b(null)),s==="r"&&p()});let p=()=>{v("/goals?limit=20").then(({goals:s})=>o(s)).catch(s=>u(s.message))};Sn(()=>{p()},[]);let y=async s=>{if(s.trim()){a(!0),b(null);try{let g=await v("/goals",{method:"POST",body:{input:s.trim()}});b(`Goal created: ${g.goal.name}`),n(""),l("list"),p()}catch(g){b(`Failed: ${g instanceof Error?g.message:String(g)}`)}finally{a(!1)}}};return c?me(Je,{flexDirection:"column",children:[me(oe,{color:"red",children:["Failed to load goals: ",c]}),Ce(oe,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?me(Je,{flexDirection:"column",children:[Ce(oe,{bold:!0,children:"Create Goal"}),Ce(oe,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),me(Je,{marginTop:1,children:[Ce(oe,{color:"cyan",children:"> "}),Ce(bn,{value:i,onChange:n,onSubmit:y})]}),r&&Ce(oe,{color:"yellow",children:"Creating goal..."}),d&&Ce(oe,{color:d.startsWith("Failed")?"red":"green",children:d}),Ce(oe,{dimColor:!0,children:"Press Esc to cancel"})]}):me(Je,{flexDirection:"column",children:[me(oe,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Ce(oe,{dimColor:!0,children:"No goals found. Press c to create one."}):Ce(Je,{marginTop:1,flexDirection:"column",children:t.map(s=>{let g=s.targetValue>0?s.currentValue/s.targetValue:0,_=Cn[s.status]??"white";return me(Je,{marginBottom:1,flexDirection:"column",children:[me(Je,{children:[Ce(oe,{bold:!0,color:_,children:s.name}),me(oe,{dimColor:!0,children:[" (",s.role,")"]}),Ce(oe,{dimColor:!0,children:" \u2014 "}),Ce(oe,{color:_,children:s.status})]}),me(Je,{children:[me(oe,{dimColor:!0,children:[" ",wn(g)," "]}),me(oe,{color:g>=1?"green":"white",children:[Math.round(g*100),"%"]}),me(oe,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),me(Je,{children:[me(oe,{dimColor:!0,children:[" \u23F0 ",Bn(s.deadline)," left"]}),me(oe,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),me(oe,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),Ce(oe,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as yt,Text as Ae,useInput as En}from"ink";import{useEffect as In,useState as sr}from"react";import{jsx as et,jsxs as Ze}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(()=>{v("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>u(l.message))},[]),c)return Ze(yt,{flexDirection:"column",children:[Ze(Ae,{color:"red",children:["Failed to load strategies: ",c]}),et(Ae,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Ze(yt,{flexDirection:"column",children:[et(Ae,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),et(Ae,{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 Ze(yt,{flexDirection:"column",children:[et(Ae,{bold:!0,children:"Strategy Lab"}),et(Ae,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),et(yt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([l,i])=>Ze(yt,{marginBottom:1,flexDirection:"column",children:[et(Ae,{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 Ze(yt,{children:[et(Ae,{dimColor:!0,children:" "}),Ze(Ae,{children:[kn(n.alpha,n.beta)," "]}),Ze(Ae,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),Ze(Ae,{dimColor:!0,children:[" ",n.name," (\u03B1=",n.alpha.toFixed(1)," \u03B2=",n.beta.toFixed(1)," trials=",n.totalTrials,")"]})]},n.id)})]},l))}),et(Ae,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as Ee,Text as Z,useInput as Mn}from"ink";import To from"ink-text-input";import{useEffect as Nn,useState as tt,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 ee,jsxs as xe}from"react/jsx-runtime";var ho=["manual","cron","event"],Zt={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]=tt([]),[c,u]=tt(!0),[m,l]=tt(0),[i,n]=tt("list"),[r,a]=tt({...Zt}),[d,b]=tt("name"),[p,y]=tt(null),{message:s,setMessage:g,clearMessage:_}=ct(),[M,Y]=tt(!1),[H,O]=tt(!1),X=bt(()=>{u(!0),v("/task-templates").then(({templates:C})=>{o(C),u(!1)}).catch(()=>u(!1))},[]);Nn(()=>{X()},[X]);let I=i==="create"||i==="edit",P=bt(async()=>{let C=t[m];if(!(!C||M)){Y(!0),g(`Triggering ${C.name}...`,"loading");try{let E=await v(`/task-templates/${C.id}/run`,{method:"POST"});g(`Triggered: ${C.name} (${E.executionId})`,"success")}catch(E){g(`Trigger failed: ${E instanceof Error?E.message:String(E)}`,"error")}finally{Y(!1)}}},[t,m,M,g]),S=bt(async()=>{let C=t[m];if(!C||H)return;if(C.trigger?.type!=="cron"&&C.trigger?.type!=="event"){g("Toggle not applicable for manual triggers","error");return}let E=!C.enabled;O(!0),g(`${C.name} \u2192 ${E?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${C.id}`,{method:"PATCH",body:{enabled:E}}),o(R=>R.map(pe=>pe.id===C.id?{...pe,enabled:E}:pe)),g(`${C.name} ${E?"enabled":"disabled"}`,"success")}catch(R){g(`Toggle failed: ${R instanceof Error?R.message:String(R)}`,"error")}finally{O(!1)}},[t,m,H,g]),j=bt(async()=>{let C=t[m];if(C)try{await v(`/task-templates/${C.id}`,{method:"DELETE"}),g(`Deleted: ${C.name}`,"success"),X(),l(E=>Math.max(0,Math.min(E,t.length-2)))}catch(E){g(`Delete failed: ${E instanceof Error?E.message:String(E)}`,"error")}},[t,m,X]),J=bt(()=>{let C=t[m];C&&(y(C.id),a({name:C.name,triggerType:C.trigger?.type??"manual",cron:C.trigger?.cron??"",stepPrompt:C.steps?.[0]?.prompt??""}),b("name"),n("edit"))},[t,m]),Re=bt(async()=>{let C={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 v("/task-templates",{method:"POST",body:C}),g(`Created: ${r.name}`,"success")):i==="edit"&&p&&(await v(`/task-templates/${p}`,{method:"PATCH",body:C}),g(`Updated: ${r.name}`,"success"))}catch(E){g(`Save failed: ${E instanceof Error?E.message:String(E)}`,"error")}n("list"),a({...Zt}),y(null),X()},[r,i,p,X]);return Mn((C,E)=>{if(I){if(E.escape){n("list"),a({...Zt}),y(null);return}if(E.return){let R=["name","triggerType","cron","stepPrompt"],pe=R.indexOf(d);if(pe<R.length-1){let ce=pe+1;if(R[ce]==="cron"&&r.triggerType!=="cron"&&ce++,ce<R.length){b(R[ce]);return}}Re();return}if(E.tab&&d==="triggerType"){a(R=>{let pe=ho.indexOf(R.triggerType);return{...R,triggerType:ho[(pe+1)%ho.length]}});return}return}if(E.escape||C==="q"){e();return}if(E.upArrow){l(R=>Math.max(0,R-1));return}if(E.downArrow){l(R=>Math.min(t.length-1,R+1));return}if(C==="t"){P();return}if(C==="d"){j();return}if(C==="e"){J();return}if(C==="c"){a({...Zt}),b("name"),n("create");return}if(C==="s"||C===" "){S();return}C==="r"&&(X(),_())}),c?ee(Z,{dimColor:!0,children:"Loading templates..."}):I?xe(Ee,{flexDirection:"column",children:[xe(Z,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),xe(Ee,{marginTop:1,flexDirection:"column",children:[xe(Ee,{children:[xe(Z,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?ee(To,{value:r.name,onChange:C=>a(E=>({...E,name:C})),placeholder:"template name"}):ee(Z,{children:r.name||"(empty)"})]}),xe(Ee,{children:[xe(Z,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),ee(Z,{children:r.triggerType}),d==="triggerType"&&ee(Z,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&xe(Ee,{children:[xe(Z,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?ee(To,{value:r.cron,onChange:C=>a(E=>({...E,cron:C})),placeholder:"*/5 * * * *"}):ee(Z,{children:r.cron||"(empty)"})]}),xe(Ee,{children:[xe(Z,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?ee(To,{value:r.stepPrompt,onChange:C=>a(E=>({...E,stepPrompt:C})),placeholder:"What should this template do?"}):ee(Z,{children:r.stepPrompt||"(empty)"})]})]}),ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):xe(Ee,{flexDirection:"column",children:[xe(Z,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&ee(Ee,{marginTop:1,children:xe(Z,{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?ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"No templates found. Press c to create one."})}):ee(Ee,{marginTop:1,flexDirection:"column",children:t.map((C,E)=>{let R=E===m,pe=C.trigger?.type==="cron"&&C.trigger?.cron?_n(C.trigger.cron):"";return xe(Ee,{children:[ee(Z,{color:R?"cyan":void 0,bold:R,children:R?"> ":" "}),ee(Z,{color:R?"cyan":void 0,bold:R,children:eo(C.name,24)}),ee(Z,{dimColor:!0,children:eo(C.trigger?.type,10)}),C.trigger?.type!=="cron"&&C.trigger?.type!=="event"?ee(Z,{dimColor:!0,children:eo("\u2014",6)}):ee(Z,{color:C.enabled?"green":"gray",children:eo(C.enabled?"on":"off",6)}),pe&&xe(Z,{dimColor:!0,children:["next: ",pe]})]},C.id)})}),ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function eo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as dt,Text as Ie,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 ye,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,b]=St(null),p=lr(()=>{l(!0),v("/webhooks").then(({webhooks:s,auth:g})=>{o(s),u(g),l(!1)}).catch(()=>l(!1))},[]);On(()=>{p()},[p]);let y=lr(async s=>{if(s.trim())try{let g=await v(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});b(`Triggered: ${g.executionId}`)}catch(g){b(`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){y(r),n(!1),a("");return}return}if(g.escape||s==="q"){e();return}if(s==="t"){n(!0),a(""),b(null);return}s==="r"&&(p(),b(null))}),m?ye(Ie,{dimColor:!0,children:"Loading webhooks..."}):gt(dt,{flexDirection:"column",children:[gt(Ie,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),gt(Ie,{dimColor:!0,children:["Auth: ",c]}),d&&ye(dt,{marginTop:1,children:ye(Ie,{color:"yellow",children:d})}),i&>(dt,{marginTop:1,children:[ye(Ie,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ye($n,{value:r,onChange:a,placeholder:"webhook name or ID"}),ye(Ie,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ye(dt,{marginTop:1,children:ye(Ie,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):gt(dt,{marginTop:1,flexDirection:"column",children:[ye(dt,{children:gt(Ie,{bold:!0,children:[Ct("NAME",24),Ct("DESCRIPTION",36),Ct("TRIGGER",28),"TAGS"]})}),t.map(s=>gt(dt,{children:[ye(Ie,{children:Ct(s.displayName,24)}),ye(Ie,{dimColor:!0,children:Ct(qn(s.description??"",34),36)}),ye(Ie,{dimColor:!0,children:Ct(s.trigger,28)}),ye(Ie,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),ye(dt,{marginTop:1,children:ye(Ie,{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 Ke,Text as ae,useInput as Fn}from"ink";import Un from"ink-text-input";import{useEffect as dr,useState as ot,useCallback as vo}from"react";import{jsx as le,jsxs as qe}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,b]=ot(""),[p,y]=ot("all"),[s,g]=ot(null),[_,M]=ot(!1),Y=vo(()=>{v("/agents").then(({agents:S})=>{o(S),n(!1)}).catch(()=>n(!1))},[]);dr(()=>{Y()},[Y]);let H=t[c],O=vo(()=>{H&&(M(!1),v(`/memories/${H.id}`).then(({memories:S})=>{l(S),g(null)}).catch(S=>g(`Failed: ${S instanceof Error?S.message:String(S)}`)))},[H]);dr(()=>{H&&O()},[H,O]);let X=vo(async S=>{if(!(!H||!S.trim()))try{let j=await v("/memories/query",{method:"POST",body:{agentId:H.id,prompt:S.trim()}});l(j.memories),M(!0),g(`Search: ${j.count} results`)}catch(j){g(`Search failed: ${j instanceof Error?j.message:String(j)}`)}},[H]),I=r,P=m.filter(S=>p==="all"?!0:p==="high"?S.importance>3:p==="medium"?S.importance===3:S.importance<3);return Fn((S,j)=>{if(I){if(j.escape){a(!1),b("");return}if(j.return){X(d),a(!1),b("");return}return}if(j.escape||S==="q"){e();return}if(S==="a"){u(J=>(J+1)%Math.max(1,t.length));return}if(j.leftArrow){u(J=>(J-1+t.length)%Math.max(1,t.length));return}if(j.rightArrow){u(J=>(J+1)%Math.max(1,t.length));return}if(S==="s"){a(!0),b(""),g(null);return}if(S==="h"){y(J=>J==="high"?"all":"high");return}if(S==="m"){y(J=>J==="medium"?"all":"medium");return}if(S==="l"){y(J=>J==="low"?"all":"low");return}S==="r"&&O()}),i?le(ae,{dimColor:!0,children:"Loading agents..."}):t.length===0?qe(Ke,{flexDirection:"column",children:[le(ae,{dimColor:!0,children:"No agents found"}),le(ae,{dimColor:!0,children:"Press Esc to go back"})]}):qe(Ke,{flexDirection:"column",children:[le(ae,{bold:!0,children:"Memories (Esc to go back)"}),qe(Ke,{marginTop:1,children:[le(ae,{children:"Agent: "}),le(ae,{bold:!0,color:"cyan",children:H?.name??"?"}),qe(ae,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),le(Ke,{children:qe(ae,{dimColor:!0,children:["Filter: ",p==="all"?"all":p," | ",_?"search results":"all memories"," (",P.length,")"]})}),s&&le(Ke,{children:le(ae,{color:"yellow",children:s})}),r&&qe(Ke,{marginTop:1,children:[le(ae,{bold:!0,color:"cyan",children:"Search: "}),le(Un,{value:d,onChange:b,placeholder:"search query..."}),le(ae,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),P.length===0?le(Ke,{marginTop:1,children:qe(ae,{dimColor:!0,children:["No memories",p!=="all"?` matching filter '${p}'`:""]})}):le(Ke,{marginTop:1,flexDirection:"column",children:P.map(S=>qe(Ke,{marginBottom:0,children:[qe(ae,{color:Wn(S.importance),bold:!0,children:[Gn(S.importance)," "]}),le(ae,{dimColor:!0,children:ur(S.type??"?",12)}),le(ae,{dimColor:!0,children:ur(`\xD7${S.retrievedCount??0}`,5)}),qe(ae,{children:[Kn(S.content,55)," "]}),le(ae,{dimColor:!0,children:Hn(S.createdAt)}),S.score!==void 0&&qe(ae,{dimColor:!0,children:[" (",S.score.toFixed(2),")"]})]},S.id))}),le(Ke,{marginTop:1,children:le(ae,{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 Kn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Fe,Text as re,useInput as jn}from"ink";import oo from"ink-text-input";import{useState as we,useEffect as gr,useCallback as yo}from"react";import{jsx as ge,jsxs as ue}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"]},Qn={"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"};function pr({onBack:e}){let{state:t}=st(),[o,c]=we({}),[u,m]=we([]),[l,i]=we(null),[n,r]=we("view"),[a,d]=we(0),[b,p]=we(""),[y,s]=we(null),[g,_]=we(!1),[M,Y]=we([]),[H,O]=we({}),[X,I]=we(0),[P,S]=we(""),[j,J]=we(""),[Re,C]=we(""),E=Object.values(fr).flat(),R=yo(()=>{v("/config").then(D=>{c(D.config),m(D.mutable)}).catch(D=>i(D.message)),v("/config/env-diff").then(D=>{Y(D.diffs)}).catch(()=>{}),v("/config/env").then(D=>O(D.env??{})).catch(()=>{})},[]);gr(()=>{R()},[R]),gr(()=>{t.configVersion>0&&R()},[t.configVersion,R]);let pe=yo(async()=>{let D=E[a];if(D){_(!0),s(null);try{let $=b,q=o[D];if(q&&typeof q.value=="number"&&($=Number(b),isNaN($))){s("Invalid number"),_(!1);return}let ne=await v("/config",{method:"PATCH",body:{[D]:$}});ne.updated.length>0&&(s(`Updated: ${D}`),R()),ne.errors.length>0&&s(ne.errors[0]),r("view")}catch($){s(`Failed: ${$ instanceof Error?$.message:String($)}`)}finally{_(!1)}}},[E,a,b,o,R]),ce=Object.keys(H),je=yo(async D=>{try{await v("/config/env",{method:"PUT",body:D}),s("Env vars saved"),R()}catch($){s(`Failed: ${$ instanceof Error?$.message:String($)}`)}},[R]);if(jn((D,$)=>{if(n==="edit"){if($.escape){r("view");return}return}if(n==="env-list"){if($.escape){r("view");return}if($.upArrow&&X>0&&I(q=>q-1),$.downArrow&&X<ce.length-1&&I(q=>q+1),D==="a"){S(""),r("env-add-key");return}if(D==="d"&&ce.length>0){let q=ce[X],ne={...H};delete ne[q],je(ne),X>=ce.length-1&&X>0&&I(Qe=>Qe-1);return}if($.return&&ce.length>0){C(H[ce[X]]??""),r("env-edit-value");return}return}if(n==="env-add-key"){if($.escape){r("env-list");return}return}if(n==="env-add-value"){if($.escape){r("env-list");return}return}if(n==="env-edit-value"){if($.escape){r("env-list");return}return}if($.escape||D==="q"){e();return}if($.upArrow&&a>0&&d(q=>q-1),$.downArrow&&a<E.length-1&&d(q=>q+1),$.return||D==="e"){let q=E[a],ne=o[q];ne&&ne.mutable?(p(String(ne.value??"")),r("edit"),s(null)):ne&&!ne.mutable&&s("This setting requires a restart to change")}D==="v"&&(I(0),r("env-list"),s(null)),D==="r"&&(R(),s("Refreshed")),D==="s"&&M.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),Y([]),R()}),D==="l"&&M.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),R()})}),l)return ue(Fe,{flexDirection:"column",children:[ue(re,{color:"red",children:["Failed to load config: ",l]}),ge(re,{dimColor:!0,children:"Press Esc or q to return"})]});let pt=0;return ue(Fe,{flexDirection:"column",children:[ge(re,{bold:!0,children:"Settings"}),y&&ge(re,{color:y.startsWith("Failed")||y.startsWith("This setting")?"yellow":"green",children:y}),M&&M.length>0&&ue(Fe,{flexDirection:"column",marginBottom:1,children:[ue(re,{color:"yellow",children:[".env differs from DB (",M.length," key(s)): ",M.map(D=>D.envKey).join(", ")]}),ge(re,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ge(Fe,{marginTop:1,flexDirection:"column",children:Object.entries(fr).map(([D,$])=>ue(Fe,{marginBottom:1,flexDirection:"column",children:[ge(re,{bold:!0,color:"cyan",children:D}),$.map(q=>{let ne=o[q],xt=pt++===a,Tt=u.includes(q),Ft=Qn[q]??q,Xe=ne?String(ne.value??""):"...";return n==="edit"&&xt?ue(Fe,{children:[ue(re,{color:"cyan",children:["> ",Ft,": "]}),ge(oo,{value:b,onChange:p,onSubmit:()=>{pe()}}),g&&ge(re,{color:"yellow",children:" saving..."})]},q):ue(Fe,{children:[ue(re,{color:xt?"cyan":"white",children:[xt?"> ":" ",Tt?" ":"\u{1F512} ",Ft,": "," "]}),ge(re,{color:Tt?"white":"gray",children:Xe}),!Tt&&ge(re,{dimColor:!0,children:" (restart required)"})]},q)})]},D))}),ge(re,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),n.startsWith("env")&&ue(Fe,{flexDirection:"column",marginTop:1,children:[ue(re,{bold:!0,color:"cyan",children:["Environment Variables (",ce.length,")"]}),ce.length===0&&n==="env-list"&&ge(re,{dimColor:!0,children:" No env vars. Press a to add."}),ce.map((D,$)=>{let q=$===X;return n==="env-edit-value"&&q?ue(Fe,{children:[ue(re,{color:"cyan",children:["> ",D," = "]}),ge(oo,{value:Re,onChange:C,onSubmit:()=>{je({...H,[D]:Re}),r("env-list")}})]},D):ue(re,{color:q&&n==="env-list"?"cyan":"white",children:[q&&n==="env-list"?"> ":" ",D," = ",H[D]]},D)}),n==="env-add-key"&&ue(Fe,{children:[ge(re,{color:"green",children:" New key: "}),ge(oo,{value:P,onChange:S,onSubmit:()=>{P.trim()&&(J(""),r("env-add-value"))}})]}),n==="env-add-value"&&ue(Fe,{children:[ue(re,{color:"green",children:[" ",P," = "]}),ge(oo,{value:j,onChange:J,onSubmit:()=>{je({...H,[P.trim()]:j}),r("env-list")}})]}),ge(re,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as ft,Text as be,useInput as Xn}from"ink";import{useEffect as zn,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),v("/plugins").then(({plugins:d})=>{o(d),u(!1)}).catch(()=>u(!1))},[]);return zn(()=>{a()},[a]),Xn((d,b)=>{if(b.escape||d==="q"){e();return}if(b.upArrow){l(p=>Math.max(0,p-1));return}if(b.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,b)=>{let p=b===m,y=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(y,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(zt,{onBack:e}),t==="automations"&&Et(to,{onBack:e}),t==="goals"&&Et(Jt,{onBack:e})]})}import{Box as z,Text as W,useInput as ts}from"ink";import{useEffect as os,useState as $t}from"react";import{jsx as N,jsxs as fe}from"react/jsx-runtime";var vr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function yr({onBack:e}){let[t,o]=$t([]),[c,u]=$t(!0),[m,l]=$t(0),[i,n]=$t(null),[r,a]=$t("");os(()=>{d()},[]);async function d(){try{let y=await v("/channels");o(y.channels)}catch{}u(!1)}async function b(y){if(t.find(g=>g.id===y)?.platform==="wechat")try{a("Starting WeChat QR login...");let g=await v(`/channels/${y}/wechat/qr-start`,{method:"POST"});if(g.qrcodeUrl){a(`Scan QR: ${g.qrcodeUrl}
|
|
6
|
+
Waiting for scan...`);let _=await v(`/channels/${y}/wechat/qr-wait`,{method:"POST",body:{sessionKey:g.sessionKey,timeoutMs:12e4}});a(_.message)}else a(g.message);d()}catch{a("WeChat connect failed")}else try{await v(`/channels/${y}/connect`,{method:"POST"}),a("Connecting..."),d()}catch{a("Connect failed")}}async function p(y){try{await v(`/channels/${y}/disconnect`,{method:"POST"}),a("Disconnected"),d()}catch{a("Disconnect failed")}}return ts((y,s)=>{if(i){if(s.escape||y==="q"){n(null);return}if(y==="c"){b(i.id);return}if(y==="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?N(z,{flexDirection:"column",children:N(W,{dimColor:!0,children:"Loading channels..."})}):i?fe(z,{flexDirection:"column",children:[fe(z,{marginBottom:1,children:[fe(W,{bold:!0,children:["Channel: ",i.name]}),N(W,{dimColor:!0,children:" (Esc to go back)"})]}),fe(z,{flexDirection:"column",gap:0,children:[fe(W,{children:["ID: ",i.id]}),fe(W,{children:["Platform: ",i.platform]}),fe(W,{children:["Status: ",N(W,{color:vr[i.status]??"white",children:i.status})]}),fe(W,{children:["Enabled: ",i.enabled?"yes":"no"]}),fe(W,{children:["Messages: ",i.messageCount]}),fe(W,{children:["Config: ",JSON.stringify(i.config)]})]}),N(z,{marginTop:1,children:N(W,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&N(W,{color:"yellow",children:r})]}):fe(z,{flexDirection:"column",children:[fe(z,{marginBottom:1,children:[N(W,{bold:!0,children:"Channels"}),fe(W,{dimColor:!0,children:[" (",t.length," total) "]}),N(W,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?N(W,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):fe(z,{flexDirection:"column",children:[fe(z,{children:[N(z,{width:3,children:N(W,{dimColor:!0,children:" "})}),N(z,{width:12,children:N(W,{bold:!0,dimColor:!0,children:"ID"})}),N(z,{width:16,children:N(W,{bold:!0,dimColor:!0,children:"Name"})}),N(z,{width:12,children:N(W,{bold:!0,dimColor:!0,children:"Platform"})}),N(z,{width:14,children:N(W,{bold:!0,dimColor:!0,children:"Status"})}),N(z,{width:10,children:N(W,{bold:!0,dimColor:!0,children:"Enabled"})}),N(z,{width:10,children:N(W,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((y,s)=>fe(z,{children:[N(z,{width:3,children:N(W,{children:s===m?">":" "})}),N(z,{width:12,children:N(W,{inverse:s===m,children:y.id.slice(0,8)})}),N(z,{width:16,children:N(W,{children:y.name})}),N(z,{width:12,children:N(W,{children:y.platform})}),N(z,{width:14,children:fe(W,{color:vr[y.status]??"white",children:[y.status==="connected"?"\u25CF":y.status==="error"?"\u2717":"\u25CB"," ",y.status]})}),N(z,{width:10,children:N(W,{color:y.enabled?"green":"gray",children:y.enabled?"yes":"no"})}),N(z,{width:10,children:N(W,{children:y.messageCount})})]},y.id))]})]})}import{Box as kt,Text as nt,useInput as ns}from"ink";import{useEffect as ss,useState as Ot,useCallback as is}from"react";import{Box as A,Text as T,useInput as rs}from"ink";import rt from"ink-text-input";import{useEffect as br,useState as Q,useCallback as It}from"react";Do();import{Fragment as Sr,jsx as h,jsxs as B}from"react/jsx-runtime";function Cr({roleId:e,onBack:t}){let[o,c]=Q(null),[u,m]=Q([]),[l,i]=Q(!0),[n,r]=Q("view"),[a,d]=Q(""),[b,p]=Q(0),[y,s]=Q(""),[g,_]=Q([]),[M,Y]=Q(0),[H,O]=Q(new Set),[X,I]=Q("inline"),[P,S]=Q(""),[j,J]=Q(""),[Re,C]=Q([]),[E,R]=Q(new Set),[pe,ce]=Q(0),[je,pt]=Q("default"),[D,$]=Q(""),[q,ne]=Q(""),[Qe,xt]=Q("mode"),[Tt,Ft]=Q([]),[Xe,Ut]=Q(0),[Wt,Bo]=Q(""),[Eo,Io]=Q(""),[ko,Po]=Q(""),{message:V,setMessage:F}=ct(),se=It(()=>{i(!0),v(`/roles/${e}`).then(({role:f,boundPlugins:w})=>{c(f),m(w??[]),d(f.cagPrompt??""),O(new Set(f.allowedTools??[])),I(f.executionMode??"inline"),S(f.model??""),J(f.maxBudgetUsd!=null?String(f.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);br(()=>{se(),v("/config").then(f=>{let w=f["defaults.deniedReadPaths"]?.value;Array.isArray(w)&&Ft(w)}).catch(()=>{})},[se]),br(()=>{I(o?.executionMode??"inline"),S(o?.model??""),J(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),pt(o?.permissionMode??"default"),$((o?.allowedBashPatterns??[]).join(", ")),ne((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 v(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:a}}),F("CAG prompt saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,a,se,F]),Er=It(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Me}}),F("Directories saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,se,F]),Ir=It(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),F("Tool permissions saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,H,se,F]),kr=It(async()=>{if(!o)return;let f={executionMode:X};P!==void 0&&(f.model=P);let w=parseFloat(j);isNaN(w)||(f.maxBudgetUsd=w);try{await v(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Execution config saved","success"),r("view"),se()}catch(x){F(`Save failed: ${x instanceof Error?x.message:String(x)}`,"error")}},[o,X,P,j,se,F]),Pr=It(async()=>{if(!o)return;let f={permissionMode:je},w=D.split(",").map(k=>k.trim()).filter(Boolean),x=q.split(",").map(k=>k.trim()).filter(Boolean);f.allowedBashPatterns=w.length>0?w:[],f.deniedBashPatterns=x.length>0?x:[];try{await v(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Permission config saved","success"),r("view"),se()}catch(k){F(`Save failed: ${k instanceof Error?k.message:String(k)}`,"error")}},[o,je,D,q,se,F]),Me=o?.additionalDirectories??[];if(rs((f,w)=>{if(w.escape){r("view");return}if(f==="r"){se();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"){v("/channels?enabled=true").then(({channels:x})=>{C(x.map(k=>({name:k.name,id:k.id}))),R(new Set(o?.allowedChannels??[])),ce(0),r("edit-channels")}).catch(()=>F("Failed to load channels","error"));return}if(f==="p"){pt(o?.permissionMode??"default"),$((o?.allowedBashPatterns??[]).join(", ")),ne((o?.deniedBashPatterns??[]).join(", ")),xt("mode"),r("edit-permissions");return}if(f==="v"){Ut(0),r("edit-env");return}if(f==="i"){if(!o)return;let x=!o.inheritUserSettings;v(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:x}}).then(()=>{F(`Inherit user settings: ${x?"ON":"OFF"}`,"success"),se()}).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"&&Me.length>0){let x=Me[b];if(x){c(de=>de&&{...de,additionalDirectories:de.additionalDirectories?.map((ke,Ar)=>Ar===b?{...typeof ke=="string"?{path:ke}:ke,mode:ke.mode==="ro"?"rw":"ro"}:ke)});let k=x.mode==="ro"?"rw":"ro";F(`Mode set to ${k.toUpperCase()}`,"success")}return}if(f==="x"&&Me.length>0){c(x=>x&&{...x,additionalDirectories:Me.filter((k,de)=>de!==b)}),p(x=>Math.max(0,Math.min(x,Me.length-2)));return}if(w.upArrow){p(x=>Math.max(0,x-1));return}if(w.downArrow){p(x=>Math.min(Me.length-1,x+1));return}break}case"edit-dirs-add":{if(w.escape){r("edit-dirs"),s(""),_([]);return}if(w.return&&g.length>0){let x=g[M];x&&(s(x.endsWith("/")?x:x+"/"),_([]));return}if(w.return){let x=y.trim();x&&x.startsWith("/")?(c(k=>k&&{...k,additionalDirectories:[...k.additionalDirectories??[],{path:x,mode:"rw"}]}),s(""),_([]),r("edit-dirs")):F("Path must be absolute (must start with /)","error");return}if(w.tab){let x=y.trim();if(!x||!x.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(x)}`).then(({suggestions:k})=>{k.length===1?(s(k[0]+"/"),_([])):k.length>1&&(_(k),Y(0))}).catch(()=>{_([])});return}if(w.upArrow&&g.length>0){Y(x=>Math.max(0,x-1));return}if(w.downArrow&&g.length>0){Y(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<Gt.length){let k=Gt[x];O(de=>{let ke=new Set(de);return ke.has(k)?ke.delete(k):ke.add(k),ke});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"],k=x.indexOf(je);w.upArrow&&pt(x[Math.max(0,k-1)]),w.downArrow&&pt(x[Math.min(x.length-1,k+1)]);return}break}case"edit-channels":{if(f==="s"){if(!o)return;let x=E.size>0?Array.from(E):[];v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:x}}).then(()=>{F("Channels saved","success"),r("view"),se()}).catch(()=>F("Save failed","error"));return}if(f==="u"){if(!o)return;v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{F("Channels: unrestricted","success"),r("view"),se()}).catch(()=>F("Save failed","error"));return}if(f===" "){let x=Re[pe];x&&R(k=>{let de=new Set(k);return de.has(x.name)?de.delete(x.name):de.add(x.name),de});return}if(w.upArrow){ce(x=>Math.max(0,x-1));return}if(w.downArrow){ce(x=>Math.min(Re.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 k=x[Xe],de={...o?.envVars??{}};delete de[k],v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:de}}).then(()=>{F("Deleted","success"),se()}).catch(()=>F("Delete failed","error")),Xe>=x.length-1&&Xe>0&&Ut(ke=>ke-1);return}if(w.return&&x.length>0){Po((o?.envVars??{})[x[Xe]]??""),r("edit-env-edit-value");return}w.upArrow&&Xe>0&&Ut(k=>k-1),w.downArrow&&Xe<x.length-1&&Ut(k=>k+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),l)return h(T,{dimColor:!0,children:"Loading role..."});if(!o)return h(T,{dimColor:!0,children:"Role not found."});if(n==="edit-cag")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(rt,{value:a,onChange:d,placeholder:"Character And Guidance prompt..."}),V&&h(A,{marginTop:1,children:h(T,{color:V.type==="error"?"red":"green",children:V.text})})]});if(n==="edit-dirs-add")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(rt,{value:y,onChange:f=>{s(f),_([])},placeholder:"/absolute/path/to/directory"}),g.length>0&&B(A,{flexDirection:"column",marginTop:1,children:[g.map((f,w)=>B(T,{color:w===M?"cyan":void 0,dimColor:w!==M,children:[w===M?"> ":" ",f,"/"]},f)),h(T,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),V&&h(A,{marginTop:1,children:h(T,{color:V.type==="error"?"red":"green",children:V.text})})]});if(n==="edit-dirs")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),Me.length===0?h(T,{dimColor:!0,children:"No directories. Press a to add one."}):Me.map((f,w)=>{let x=typeof f=="string"?{path:f,mode:"rw"}:f,k=x.mode!=="ro";return B(A,{children:[h(T,{color:w===b?"cyan":void 0,bold:w===b,children:w===b?"> ":" "}),B(T,{color:k?"green":"yellow",children:["[",k?"RW":"RO","]"," "]}),h(T,{color:w===b?"cyan":void 0,children:x.path})]},x.path)})]});if(n==="edit-tools")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),Gt.map((f,w)=>{let x=H.has(f);return B(A,{children:[B(T,{dimColor:!0,children:[w+1,". "]}),h(T,{color:x?"green":"red",children:x?"[ON] ":"[OFF] "}),h(T,{children:f})]},f)})]});if(n==="edit-exec")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(A,{children:[h(T,{bold:!0,children:" Mode: "}),h(T,{color:"cyan",children:X}),h(T,{dimColor:!0,children:" (Tab to toggle)"})]}),B(A,{children:[h(T,{bold:!0,children:" Model: "}),h(rt,{value:P,onChange:S,placeholder:"sonnet, opus, haiku, or blank"})]}),B(A,{children:[h(T,{bold:!0,children:" Max Budget (USD): "}),h(rt,{value:j,onChange:J,placeholder:"0 = unlimited"})]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n==="edit-permissions")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(A,{children:[h(T,{bold:!0,color:Qe==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(w=>B(T,{color:w===je?"green":"gray",children:[w===je?`[${w}]`:` ${w} `," "]},w))]}),B(A,{children:[h(T,{bold:!0,color:Qe==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),Qe==="allowed"?h(rt,{value:D,onChange:$,placeholder:"git add *, pnpm test*"}):h(T,{children:D||"(none)"})]}),B(A,{children:[h(T,{bold:!0,color:Qe==="denied"?"cyan":void 0,children:" Denied Bash: "}),Qe==="denied"?h(rt,{value:q,onChange:ne,placeholder:"rm -rf *, ssh *"}):h(T,{children:q||"(none)"})]}),h(T,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n==="edit-channels")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Re.length===0?h(T,{dimColor:!0,children:"No channels available"}):Re.map((f,w)=>B(A,{children:[B(T,{children:[w===pe?">":" "," "]}),B(T,{color:E.has(f.name)?"green":"gray",children:["[",E.has(f.name)?"x":" ","] ",f.name]})]},f.id)),B(T,{dimColor:!0,children:["Selected: ",E.size>0?Array.from(E).join(", "):"none (= block all)"]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n.startsWith("edit-env")){let f=Object.keys(o.envVars??{});return B(A,{flexDirection:"column",children:[B(T,{bold:!0,children:["Environment Variables (",f.length,")"]}),f.length===0&&n==="edit-env"&&h(T,{dimColor:!0,children:" No env vars. Press a to add."}),f.map((w,x)=>{let k=x===Xe;return n==="edit-env-edit-value"&&k?B(A,{children:[B(T,{color:"cyan",children:["> ",w," = "]}),h(rt,{value:ko,onChange:Po,onSubmit:()=>{let de={...o.envVars??{},[w]:ko};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:de}}).then(()=>{F("Saved","success"),se(),r("edit-env")}).catch(()=>F("Save failed","error"))}})]},w):B(T,{color:k&&n==="edit-env"?"cyan":"white",children:[k&&n==="edit-env"?"> ":" ",w," = ",(o.envVars??{})[w]]},w)}),n==="edit-env-add-key"&&B(A,{children:[h(T,{color:"green",children:" New key: "}),h(rt,{value:Wt,onChange:Bo,onSubmit:()=>{Wt.trim()&&(Io(""),r("edit-env-add-value"))}})]}),n==="edit-env-add-value"&&B(A,{children:[B(T,{color:"green",children:[" ",Wt," = "]}),h(rt,{value:Eo,onChange:Io,onSubmit:()=>{let w={...o.envVars??{},[Wt.trim()]:Eo};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:w}}).then(()=>{F("Added","success"),se(),r("edit-env")}).catch(()=>F("Add failed","error"))}})]}),h(T,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),V&&h(T,{color:V.type==="error"?"red":"green",children:V.text})]})}return B(A,{flexDirection:"column",children:[B(T,{bold:!0,children:["Role: ",o.name]}),B(A,{children:[h(T,{dimColor:!0,children:"ID: "}),h(T,{children:o.id})]}),B(A,{children:[h(T,{dimColor:!0,children:"Status: "}),h(T,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&B(A,{children:[h(T,{dimColor:!0,children:"Score: "}),B(T,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(A,{children:[h(T,{dimColor:!0,children:"Created: "}),h(T,{children:new Date(o.createdAt).toLocaleString()})]}),B(A,{children:[h(T,{dimColor:!0,children:"Execution: "}),B(T,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),Me.length>0&&B(Sr,{children:[h(T,{bold:!0,children:"Additional Directories:"}),Me.map(f=>B(T,{dimColor:!0,children:[" ",f.path]},f.path))]}),B(A,{children:[h(T,{dimColor:!0,children:"Permission: "}),h(T,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(A,{children:[h(T,{dimColor:!0,children:" Bash Allow: "}),h(T,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(A,{children:[h(T,{dimColor:!0,children:" Bash Deny: "}),h(T,{children:o.deniedBashPatterns.join(", ")})]}),Tt.length>0&&B(A,{flexDirection:"column",children:[h(T,{dimColor:!0,children:"Denied Read Paths (global):"}),Tt.map(f=>B(T,{dimColor:!0,children:[" ",f]},f)),B(T,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(A,{children:[h(T,{dimColor:!0,children:"Channels: "}),h(T,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(A,{children:[h(T,{dimColor:!0,children:"Inherit User Settings: "}),h(T,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&B(Sr,{children:[h(T,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(f=>B(T,{dimColor:!0,children:[" - ",f]},f))]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),h(A,{marginTop:1,children:h(T,{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 De,jsxs as no}from"react/jsx-runtime";function wr({onBack:e}){let[t,o]=Ot([]),[c,u]=Ot(!0),[m,l]=Ot(0),[i,n]=Ot("list"),[r,a]=Ot(null),{message:d,setMessage:b,clearMessage:p}=ct(),y=is(()=>{u(!0),v("/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(()=>{y()},[y]),ns((s,g)=>{if(g.escape||s==="q"){e();return}if(g.upArrow){l(_=>Math.max(0,_-1));return}if(g.downArrow){l(_=>Math.min(t.length-1,_+1));return}if(s==="r"&&(y(),p()),s===`
|
|
7
|
+
`||s==="o"||s==="e"){t.length>0&&(a(t[m].id),n("detail"));return}}),c?De(nt,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?De(Cr,{roleId:r,onBack:()=>n("list")}):no(kt,{flexDirection:"column",children:[no(nt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&De(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?De(kt,{marginTop:1,children:De(nt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):De(kt,{marginTop:1,flexDirection:"column",children:t.map((s,g)=>{let _=g===m,M=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014";return no(kt,{children:[De(nt,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),De(nt,{color:_?"cyan":void 0,bold:_,children:Co(s.name,24)}),De(nt,{color:as(s.status),children:Co(s.status,12)}),De(nt,{dimColor:!0,children:Co(M,8)})]},s.id)})}),De(kt,{marginTop:1,children:De(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 G,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(M=>[...M,{role:"assistant",content:n.content}]))},[n]);let{events:a,isStreaming:d,clearEvents:b}=Oo(e.activeTaskId),p=a[a.length-1],y=p?.type==="complete"&&!d,s=wo(null),g=wo("");so(()=>{g.current=a.filter(M=>M.type==="reasoning").map(M=>M.content).join("")},[a]),so(()=>{if(y&&e.activeTaskId!==s.current){s.current=e.activeTaskId;let M=p?.content||g.current;M&&i(Y=>[...Y,{role:"assistant",content:M}])}},[y,p,e.activeTaskId]);let _=async M=>{let Y=M.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(Y)&&process.exit(0),M.startsWith("/")){let O=M.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"}[O];if(I){t({type:"SET_VIEW",view:I});return}if(O==="new"){if(await m()){let S=await u();i([]),b(),S&&i([{role:"assistant",content:`Session archived. New session started: ${S.id.slice(0,8)}`}])}return}if(O==="session"){let P=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:P}]);return}}if(i(O=>[...O,{role:"user",content:M}]),b(),!await c(M)){i(O=>[...O,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}};return At(qt,{flexDirection:"column",paddingX:1,children:[G(Wo,{}),At(qt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&At(gs,{children:[G(Xo,{messages:l}),G(Ko,{events:a,isStreaming:d}),!e.connected&&!e.serverUnreachable&&G(qt,{children:G(Pt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&At(qt,{flexDirection:"column",children:[G(Pt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),G(Pt,{dimColor:!0,children:"Check: adam server logs"}),G(Pt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&G(hr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&G(zt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&G(or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&G(nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&G(Jt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&G(ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&G(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&G(cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&G(mr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&G(xr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&G(wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&G(pr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&G(yr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?G(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?G(zo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):G(Ho,{onSubmit:_}),e.planTimeoutNotice&&G(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(qt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[At(Pt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),G(Pt,{dimColor:!0,children:" [d] Dismiss"})]})}function ms(){return G(No,{children:G(ds,{})})}export{ms as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as a,o as b}from"./chunk-UW3OJG7U.js";import"./chunk-5V36ACKZ.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-6YURWVQG.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-MPRAVJUO.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KLQOILIJ.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-2HN2TSP6.js";import"./chunk-EGS6U3V5.js";import"./chunk-SWPXG2CY.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as a,j as b,k as c,l as d,m as e}from"./chunk-U5NRQNBB.js";import"./chunk-QN6BEJF5.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-3RAFA6QK.js";import"./chunk-BIIP363C.js";import"./chunk-KLQOILIJ.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-Q4YE5BU7.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-L7JP7DUO.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c}from"./chunk-IHP7JV6J.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f}from"./chunk-SWPXG2CY.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as S,h as x}from"./chunk-INNDBLZE.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{b as f}from"./chunk-EGS6U3V5.js";import{b as m}from"./chunk-SWPXG2CY.js";import{c as h,h as v}from"./chunk-INNDBLZE.js";v();var p=h("channels"),u=new Map,I=3e5,A=new Set(["telegram"]);function w(i){let e=i.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,o=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:o?"allow":"deny"}}function $(i){let n=m(i);return n?A.has(n.platform):!1}var T={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},P={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function k(i){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of i.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let o=e.description.indexOf(": "),r=o>0?e.description.slice(0,o):"Operation";if(n.push(`\u64CD\u4F5C: ${r}`),r==="Bash"&&o>0)try{let t=JSON.parse(e.description.slice(o+2));if(t.command){let s=String(t.command).trim();n.push(`\u547D\u4EE4: ${s.length>120?s.slice(0,117)+"...":s}`)}}catch{let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}else if(o>0){let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}}let c=T[e.riskLevel]??"\u{1F7E1}",l=P[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
|
|
2
|
+
`).trimEnd()}async function C(i,n,e,c,l,o=I){let r=e,t=r.slice(0,8);u.set(t,{planId:e,taskId:c,channelId:i,chatId:n,requestId:r,timestamp:Date.now(),timeoutMs:o});let s=f(),d=$(i);if(d){let a=`${l}
|
|
3
|
+
|
|
4
|
+
`;await s.send({channelId:i,chatId:n,content:a,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${t}`},{text:"\u274C Deny",callbackData:`no ${t}`}]]}})}else{let a=[l,"",`Reply 'yes ${t}' or 'no ${t}'`].join(`
|
|
5
|
+
`);await s.send({channelId:i,chatId:n,content:a,messageType:"approval"})}setTimeout(()=>{let a=u.get(t);if(a&&Date.now()-a.timestamp>=a.timeoutMs){u.delete(t),p.warn({requestId:r,shortId:t,taskId:c},"Approval timed out, auto-denying"),s.send({channelId:a.channelId,chatId:a.chatId,content:`\u23F0 Approval ${t} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(g=>p.error({requestId:r,error:g},"Failed to notify timeout"));let y=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${y}/tasks/${a.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:a.planId,decision:"deny"})}).catch(g=>p.error({requestId:r,error:g},"Failed to auto-deny"))}},o+1e3),p.info({channelId:i,chatId:n,planId:e,shortId:t,interactive:d},"Interactive approval sent to channel")}async function S(i,n,e,c){let o=w(c??e);if(!o)return!1;let{requestId:r,decision:t}=o,s=u.get(r);if(!s)return!1;if(s.channelId!==i||s.chatId!==n)return p.debug({shortId:r,expectedChannel:s.channelId,gotChannel:i},"Approval reply from different channel"),!1;u.delete(r),p.info({shortId:r,requestId:s.requestId,decision:t},"Channel approval reply received");try{let d=process.env.ADAM_PORT??"7100",a=await fetch(`http://localhost:${d}/tasks/${s.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:s.planId,decision:t}),signal:AbortSignal.timeout(1e4)});a.ok||p.error({shortId:r,status:a.status},"Failed to forward approval to API")}catch(d){p.error({shortId:r,error:d},"Error forwarding approval to API")}return!0}function E(){return[...u.keys()]}export{w as a,k as b,C as c,S as d,E as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as u,d as a}from"./chunk-
|
|
1
|
+
import{b as u,d as a}from"./chunk-KVSO3KGZ.js";a();function d(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??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,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0}}function c(e){u().prepare(`
|
|
2
2
|
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
3
|
sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
4
|
created_at, started_at, completed_at,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f,
|
|
1
|
+
import{e as f,k as h}from"./chunk-B4WHT7DX.js";import{b as u,d as E}from"./chunk-KVSO3KGZ.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
|
|
2
2
|
INSERT INTO memories (id, role_id, type, content, embedding, keywords,
|
|
3
3
|
importance, source_type, source_task_id, evidence,
|
|
4
4
|
created_at, last_accessed, retrieved_count, tier, superseded_by)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as n,h as g}from"./chunk-INNDBLZE.js";g();import{query as l}from"@anthropic-ai/claude-agent-sdk";import*as i from"fs/promises";import*as a from"path";import*as m from"os";var v=n("manager"),e=a.join(m.homedir(),".adam","llm-eval");async function w(u,t){await i.mkdir(e,{recursive:!0});let o={cwd:e,maxTurns:3,maxBudgetUsd:.05};t&&(o.systemPrompt=t);let c=l({prompt:u,options:o}),s="";for await(let f of c){let r=f;r.type==="result"&&typeof r.result=="string"&&(s=r.result)}return s}export{w as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as l}from"./chunk-
|
|
1
|
+
import{b as s,d as l}from"./chunk-KVSO3KGZ.js";l();function o(e){let n={type:e.trigger_type,cron:e.trigger_type==="once"?void 0:e.trigger_cron??void 0,event:e.trigger_event??void 0,runAt:e.trigger_type==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:n,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,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,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0}}function u(e){s().prepare(`
|
|
2
2
|
INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
|
|
3
3
|
trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
|
|
4
4
|
source_session_id, deliver_to, report_to, goal_ids)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","server.timezone","anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel","defaults.approvalTimeout","defaults.deniedReadPaths","defaults.approvalRequired"],g=["server.port","server.host","server.apiKey"],p={"anthropic.apiKey":"ANTHROPIC_API_KEY","anthropic.baseUrl":"ANTHROPIC_BASE_URL","anthropic.model":"ANTHROPIC_MODEL","anthropic.defaultOpusModel":"ANTHROPIC_DEFAULT_OPUS_MODEL","anthropic.defaultSonnetModel":"ANTHROPIC_DEFAULT_SONNET_MODEL","anthropic.defaultHaikuModel":"ANTHROPIC_DEFAULT_HAIKU_MODEL","anthropic.smallFastModel":"ANTHROPIC_SMALL_FAST_MODEL"},a=null;function A(t){a=JSON.parse(JSON.stringify(t))}function i(){if(!a)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return a}function _(t){let r=i(),o=t();for(let[n,e]of Object.entries(o))d(r,n,e)}function R(){let t=i(),r={};for(let[o,n]of Object.entries(p)){let e=E(t,o);e&&typeof e=="string"&&e.length>0?r[n]=e:process.env[n]&&(r[n]=process.env[n])}return r}function c(t){let r={};for(let[o,n]of Object.entries(t))o.startsWith("ANTHROPIC_")||(r[o]=n);return r}var l=/key|token|secret|password|credential/i;function k(t){let r={};for(let[o,n]of Object.entries(t))r[o]=l.test(o)&&n.length>4?n.slice(0,4)+"****":l.test(o)&&n.length>0?"****":n;return r}function O(t){let o=i().defaults?.env??{};return{...process.env,...o,...R(),...c(t?.roleEnvVars??{}),...c(t?.taskEnv??{}),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1"}}function S(t,r){let o=i(),n=[],e=[];for(let[s,u]of Object.entries(t)){if(!h(s)){v(s)?e.push(`"${s}" requires restart. Cannot modify at runtime.`):e.push(`"${s}" is not a recognized config path.`);continue}d(o,s,u)&&(n.push(s),r?.(s,u))}return{success:e.length===0,updated:n,errors:e}}function d(t,r,o){let n=r.split("."),e=t;for(let s=0;s<n.length-1;s++)if(e&&typeof e=="object")e=e[n[s]];else return!1;return e&&typeof e=="object"?(e[n[n.length-1]]=o,!0):!1}function E(t,r){let o=r.split("."),n=t;for(let e of o)if(n&&typeof n=="object")n=n[e];else return;return n}function h(t){return f.includes(t)}function v(t){return g.includes(t)}export{f as a,g as b,A as c,i as d,_ as e,R as f,c as g,k as h,O as i,S as j,E as k,h as l,v as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as e,d as t,h as a}from"./chunk-WBAPIPST.js";a();var r={defaults:{timeout:600,maxTurns:100,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"notify",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},sandboxViolation:{enabled:!0,action:"alert"}}},execution:{maxConcurrent:5,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""}};export{r as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as a,d as u}from"./chunk-
|
|
1
|
+
import{b as a,d as u}from"./chunk-KVSO3KGZ.js";u();function l(e){return{id:e.id,eventType:e.event_type,matchCriteria:JSON.parse(e.match_criteria),target:JSON.parse(e.target),formatTemplate:e.format_template??void 0,maxPerMinute:e.max_per_minute,skipOriginChannel:e.skip_origin_channel===1,enabled:e.enabled===1,createdAt:e.created_at,createdBy:e.created_by??void 0}}function d(e){a().prepare(`
|
|
2
2
|
INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
|
|
3
3
|
max_per_minute, skip_origin_channel, enabled, created_at, created_by)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{g as a,h as E}from"./chunk-WBAPIPST.js";E();import{readFileSync as h,writeFileSync as _,existsSync as v}from"fs";var f={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel"},R=Object.fromEntries(Object.entries(f).map(([c,o])=>[o,c]));function m(c){let o={};for(let i of c.split(`
|
|
2
|
+
`)){let r=i.trim();if(!r||r.startsWith("#"))continue;let n=r.startsWith("export ")?r.slice(7).trim():r,s=n.indexOf("=");if(s===-1)continue;let e=n.slice(0,s).trim(),t=n.slice(s+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(l,g,u)=>{let d=g??u;return o[d]??process.env[d]??""}),!t))&&(o[e]=t)}return o}function y(){if(!v(a))return null;let c=m(h(a,"utf-8")),o={};for(let[i,r]of Object.entries(c))i in f&&(o[i]=r);return o}function V(){return v(a)?m(h(a,"utf-8")):null}function P(c){let o=V();if(!o)return[];let i=[];for(let[n,s]of Object.entries(f)){let e=c[s],t=o[n];if(t===void 0)continue;let l=e?String(e):"";l!==t&&i.push({configPath:s,envKey:n,dbValue:l,envValue:t})}let r=c["defaults.env"]??{};for(let[n,s]of Object.entries(o)){if(n in f)continue;let e=r[n]??"";e!==s&&i.push({configPath:`defaults.env.${n}`,envKey:n,dbValue:e,envValue:s})}for(let[n,s]of Object.entries(r))n in o||i.push({configPath:`defaults.env.${n}`,envKey:n,dbValue:s,envValue:""});return i}function S(c){if(!v(a))return 0;let i=h(a,"utf-8").split(`
|
|
3
|
+
`),r=0,n=new Set,s=c["defaults.env"]??{};for(let e=0;e<i.length;e++){let t=i[e].trim();if(!t||t.startsWith("#"))continue;let l=t.startsWith("export ")?t.slice(7).trim():t,g=l.indexOf("=");if(g===-1)continue;let u=l.slice(0,g).trim(),d=t.startsWith("export ")?"export ":"",O=f[u];if(O){let p=c[O];p!=null&&String(p).length>0&&(i[e]=`${d}${u}=${String(p)}`,n.add(u),r++);continue}u in s&&(i[e]=`${d}${u}=${s[u]}`,n.add(u),r++)}for(let[e,t]of Object.entries(f)){if(n.has(e))continue;let l=c[t];l&&String(l).length>0&&(i.push(`${e}=${String(l)}`),r++)}for(let[e,t]of Object.entries(s))n.has(e)||t&&t.length>0&&(i.push(`${e}=${t}`),r++);return r>0&&_(a,i.join(`
|
|
4
|
+
`)),r}export{R as a,y as b,V as c,P as d,S as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as r,d as s}from"./chunk-KVSO3KGZ.js";import{c as i}from"./chunk-FCV2DPZQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
|
|
2
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-KVSO3KGZ.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
|
|
2
2
|
INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
|
|
3
3
|
title, created_at, last_active_at, archived_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as n,d as o}from"./chunk-
|
|
1
|
+
import{b as n,d as o}from"./chunk-KVSO3KGZ.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
|
|
2
2
|
INSERT INTO chat_messages (id, session_id, role, content, source_type, task_id,
|
|
3
3
|
channel_message_id, metadata, created_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{a as u,g as O}from"./chunk-7LBDLAUQ.js";import{b as l,d as R}from"./chunk-KVSO3KGZ.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{f as s,j as w}from"./chunk-KLQOILIJ.js";import{d as i,e as f,h as g,k as y}from"./chunk-B4WHT7DX.js";import{c as p,h}from"./chunk-INNDBLZE.js";y();w();h();import{v4 as c}from"uuid";var t=p("store"),a="role-chat-manager",l=[{name:"Engineer",cagPrompt:`Role: General-purpose software engineer.
|
|
2
2
|
Capabilities: Read, write, and edit code; run shell commands; search codebases.
|
|
3
3
|
Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
|
|
4
4
|
Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
|
|
@@ -14,6 +14,6 @@ Constraints: No file write/edit permissions. Cannot modify the codebase \u2014 o
|
|
|
14
14
|
Capabilities: Create and edit text files, read reference material, search for context.
|
|
15
15
|
Approach: Understand the target audience and format \u2192 draft \u2192 refine. Match the project's existing tone and terminology.
|
|
16
16
|
Best for: Documentation, reports, emails, translations, summaries, changelog entries.
|
|
17
|
-
Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}];function
|
|
17
|
+
Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}];function M(){R();let r=g(void 0,1e3,0),o=new Set(l.map(e=>e.name)),d=r.filter(e=>o.has(e.name));if(d.length>0)return t.info({count:d.length},"Default roles already exist, skipping"),r;t.info({count:l.length},"Creating default roles");let u=[];for(let e of l){let m=`role-${c().slice(0,8)}`,n={id:m,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,evaluationCriteria:e.evaluationCriteria,executionMode:e.executionMode};i(n),u.push(n),s(n),t.info({roleId:m,name:e.name},"Created default role")}return u}function R(){if(f(a)){t.debug({roleId:a},"ChatManager system role already exists");return}let o={id:a,name:"Chat Manager",cagPrompt:`You are the Chat Manager \u2014 orchestrating conversations and managing agent interactions.
|
|
18
18
|
You coordinate between user requests and agent execution, maintaining conversation context
|
|
19
|
-
and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,
|
|
19
|
+
and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,M as b};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as l}from"./chunk-
|
|
1
|
+
import{b as i,d as l}from"./chunk-KVSO3KGZ.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
2
|
INSERT INTO goals (id, name, description, role, metric_type, target_value,
|
|
3
3
|
current_value, deadline, budget_usd, status, created_at, updated_at,
|
|
4
4
|
source_session_id, deliver_to, report_to)
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as C}from"./chunk-SWPXG2CY.js";import{b as D,c as f,d as w}from"./chunk-OFOVSC72.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
|
+
|
|
3
|
+
`).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-WMCY4QC3.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as t,d}from"./chunk-
|
|
1
|
+
import{b as t,d}from"./chunk-KVSO3KGZ.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
|
|
2
2
|
INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
|
|
3
3
|
deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as e,d as p}from"./chunk-
|
|
1
|
+
import{b as e,d as p}from"./chunk-KVSO3KGZ.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
|
|
2
2
|
INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
|
|
3
3
|
tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as l}from"./chunk-
|
|
1
|
+
import{a as l}from"./chunk-2CMR5AG7.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-4TCP2AT7.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
|
|
2
2
|
|
|
3
3
|
[User Request]
|
|
4
4
|
`);for(let c of o){let r=m(`- [${c.tier??"episodic"}] ${c.content}
|