adam-agent-server 1.2.2 → 1.3.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.
Files changed (101) hide show
  1. package/dist/App-3OBJDI2C.js +9 -0
  2. package/dist/adam-tools-4LZYFB6J.js +1 -0
  3. package/dist/{approval-handler-JYIS2PKQ.js → approval-handler-RIJO3OBO.js} +1 -1
  4. package/dist/audit-manager-6FFPXID3.js +1 -0
  5. package/dist/bree-engine-2NOTIBAZ.js +1 -0
  6. package/dist/{channels-WZOYE4O4.js → channels-LUJ7GTSP.js} +1 -1
  7. package/dist/channels-TSZLEU3L.js +1 -0
  8. package/dist/{chunk-PMHNW5IL.js → chunk-4LSIHSCO.js} +1 -1
  9. package/dist/{chunk-KVSO3KGZ.js → chunk-4MJF77RD.js} +54 -5
  10. package/dist/{chunk-BIIP363C.js → chunk-4NW2DNDZ.js} +1 -1
  11. package/dist/{chunk-OEKM2W3K.js → chunk-6NUHSHS5.js} +1 -1
  12. package/dist/{chunk-IHP7JV6J.js → chunk-72VLUJ2S.js} +1 -1
  13. package/dist/chunk-7CJGPCSJ.js +49 -0
  14. package/dist/{chunk-KLQOILIJ.js → chunk-7IXLL673.js} +1 -1
  15. package/dist/{chunk-SBX3HMDA.js → chunk-7K4AQBDD.js} +1 -1
  16. package/dist/{chunk-GMCIKDTC.js → chunk-AKPLOO2V.js} +1 -1
  17. package/dist/{chunk-AJVN3KPM.js → chunk-AZBNUSM2.js} +1 -1
  18. package/dist/{chunk-SWPXG2CY.js → chunk-CLHSPXZ6.js} +1 -1
  19. package/dist/{chunk-KKLZIXBN.js → chunk-DBUEHITK.js} +2 -2
  20. package/dist/chunk-GSMC3VUM.js +1 -0
  21. package/dist/{chunk-EJVUUIAV.js → chunk-HFN7Y3IM.js} +1 -1
  22. package/dist/{chunk-6DXNXLYG.js → chunk-IKUBP3SY.js} +1 -1
  23. package/dist/{chunk-4TCP2AT7.js → chunk-IZGTTLTG.js} +1 -1
  24. package/dist/chunk-JZNBFZ7W.js +7 -0
  25. package/dist/{chunk-6YURWVQG.js → chunk-NDP6LWXX.js} +1 -1
  26. package/dist/{chunk-CDVIT7L5.js → chunk-NLD7WK3R.js} +1 -1
  27. package/dist/{chunk-OFOVSC72.js → chunk-NUTUI5KM.js} +1 -1
  28. package/dist/{chunk-B4WHT7DX.js → chunk-OTH4M5L3.js} +1 -1
  29. package/dist/{chunk-GUQAIWCQ.js → chunk-P6KWAGAY.js} +1 -1
  30. package/dist/chunk-PVYEGQEG.js +83 -0
  31. package/dist/{chunk-Z5ET7WW2.js → chunk-T33BLZV2.js} +1 -1
  32. package/dist/{chunk-2HN2TSP6.js → chunk-TCHBOWQ5.js} +1 -1
  33. package/dist/{chunk-RPTHFQX7.js → chunk-TKDT7EQO.js} +1 -1
  34. package/dist/{chunk-ZM6YED5F.js → chunk-UQJZU3R5.js} +1 -1
  35. package/dist/{chunk-7LBDLAUQ.js → chunk-WKS7QVIX.js} +1 -1
  36. package/dist/{chunk-EGS6U3V5.js → chunk-WTRM5VO7.js} +2 -2
  37. package/dist/chunk-XTHP5JMO.js +10 -0
  38. package/dist/chunk-YHVFZB6Q.js +1 -0
  39. package/dist/{chunk-QN6BEJF5.js → chunk-YPOTHL7X.js} +1 -1
  40. package/dist/chunk-ZKMDHQJY.js +104 -0
  41. package/dist/{chunk-AR2IZMM2.js → chunk-ZQYKT5UY.js} +1 -1
  42. package/dist/cli.js +2 -2
  43. package/dist/{config-EI3SCA4W.js → config-HR4MBTIS.js} +1 -1
  44. package/dist/config-XMQS2NPT.js +1 -0
  45. package/dist/{db-4NY7ZOS2.js → db-6KUGCGVR.js} +1 -1
  46. package/dist/{delivery-log-SC2ULFCK.js → delivery-log-7DJJTPXL.js} +1 -1
  47. package/dist/engine-HJUE6I4I.js +1 -0
  48. package/dist/{evolution-audit-KUBXFUHI.js → evolution-audit-I2ITWAEC.js} +1 -1
  49. package/dist/{external-api-A4JXX4ZE.js → external-api-7XV2PXPC.js} +1 -1
  50. package/dist/index.js +12 -11
  51. package/dist/{learner-B6XVQKBF.js → learner-CBPQZ3HL.js} +1 -1
  52. package/dist/{memories-FQCRKMK6.js → memories-HBBW44MG.js} +1 -1
  53. package/dist/{memory-extractor-FUOJ5D77.js → memory-extractor-XO2HJ22Y.js} +2 -2
  54. package/dist/memory-service-HIFTKEW2.js +1 -0
  55. package/dist/outbound-gateway-GGFMU5JW.js +1 -0
  56. package/dist/role-presets-W452Y3RV.js +1 -0
  57. package/dist/{roles-3UTFKSHI.js → roles-NYGWZMQI.js} +1 -1
  58. package/dist/{runtime-B2DP3JNB.js → runtime-VDBZZ4KG.js} +1 -1
  59. package/dist/{session-manager-Z6MIYRD3.js → session-manager-JICVE4CO.js} +1 -1
  60. package/dist/{task-templates-PSP7GOJJ.js → task-templates-NC7XIZIC.js} +1 -1
  61. package/dist/workflow-executor-QN4KP7B4.js +1 -0
  62. package/package.json +1 -1
  63. package/web/dist/assets/{ChannelDetail-eWtIGhAd.js → ChannelDetail-DX4QnE8j.js} +1 -1
  64. package/web/dist/assets/{Channels-2veauYsm.js → Channels-EXkNOQpB.js} +1 -1
  65. package/web/dist/assets/{Chat-Bha4vXwT.js → Chat-Da-mCR0c.js} +1 -1
  66. package/web/dist/assets/{Dashboard-cDHpOWnY.js → Dashboard-Bq6sEDdP.js} +1 -1
  67. package/web/dist/assets/{EnvVarEditor-CaCpNT3y.js → EnvVarEditor-CNxXpVbD.js} +1 -1
  68. package/web/dist/assets/{Evolution-Ao-gdHbS.js → Evolution-DPdmbooj.js} +1 -1
  69. package/web/dist/assets/{GoalDetail-CX2i9A5a.js → GoalDetail-BamCfVzS.js} +1 -1
  70. package/web/dist/assets/{Goals-DdM0tFus.js → Goals-CHPEg0RK.js} +1 -1
  71. package/web/dist/assets/{Logs-DJhpDtCA.js → Logs-BHkBvH0T.js} +1 -1
  72. package/web/dist/assets/{Memories-CYN99g2T.js → Memories-BY2pJhVd.js} +1 -1
  73. package/web/dist/assets/{Plugins-gcMpBdyq.js → Plugins-C5xLM0BU.js} +1 -1
  74. package/web/dist/assets/{RoleDetail-s7u-Shk3.js → RoleDetail-Dnp-W14x.js} +1 -1
  75. package/web/dist/assets/{Roles-CCy1H7PY.js → Roles-BVOVoHvc.js} +1 -1
  76. package/web/dist/assets/Settings-eBHvn6s_.js +1 -0
  77. package/web/dist/assets/{Strategies-CO4LwZjS.js → Strategies-BbFbLKBJ.js} +1 -1
  78. package/web/dist/assets/{Switch-CTAIxUd_.js → Switch-Q-inggPs.js} +1 -1
  79. package/web/dist/assets/{TaskDetail-DEg_oUwx.js → TaskDetail-BEjZ1gco.js} +1 -1
  80. package/web/dist/assets/Work-CF2iLs8i.js +1 -0
  81. package/web/dist/assets/{index-rvaixveh.js → index-CaHdOfAc.js} +2 -2
  82. package/web/dist/assets/index-D0SvKqKc.css +2 -0
  83. package/web/dist/index.html +2 -2
  84. package/dist/App-RIYRYLKD.js +0 -9
  85. package/dist/adam-tools-V22LRDCP.js +0 -1
  86. package/dist/audit-manager-QDFDBK4E.js +0 -1
  87. package/dist/bree-engine-EKZFCS4Q.js +0 -1
  88. package/dist/channels-WMCY4QC3.js +0 -1
  89. package/dist/chunk-6HD6NYIB.js +0 -1
  90. package/dist/chunk-ITUBFUJQ.js +0 -67
  91. package/dist/chunk-IZWULGUS.js +0 -83
  92. package/dist/chunk-JNRCXAW3.js +0 -49
  93. package/dist/chunk-W3554FQ7.js +0 -7
  94. package/dist/config-7HYICF5P.js +0 -1
  95. package/dist/engine-5RJ7NJSM.js +0 -1
  96. package/dist/memory-service-ANR67OPY.js +0 -1
  97. package/dist/outbound-gateway-6FQRWYFF.js +0 -1
  98. package/dist/role-presets-LRP6P5O2.js +0 -1
  99. package/web/dist/assets/Settings-JbgBxBeo.js +0 -1
  100. package/web/dist/assets/Work-BpKK_uXA.js +0 -1
  101. package/web/dist/assets/index-CaocwyO8.css +0 -2
@@ -0,0 +1,9 @@
1
+ import{b as T,d as jt,e as Ro}from"./chunk-VRP4LTHY.js";import{a as Ht,f as Ao,h as Do}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as Ft,Text as Pt,useInput as ls}from"ink";import{useState as cs,useEffect as so,useRef as wo}from"react";import{createContext as Dr,useContext as Rr,useReducer as Mr}from"react";import{jsx as _r}from"react/jsx-runtime";var Nr={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null,version:null};function Lr(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};case"SET_VERSION":return{...e,version:t.version};default:return e}}var Mo=Dr(null);function No({children:e}){let[t,o]=Mr(Lr,Nr);return _r(Mo.Provider,{value:{state:t,dispatch:o},children:e})}function st(){let e=Rr(Mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Lo,useRef as _o}from"react";var Vr=15e3;function Vo(){let{state:e,dispatch:t}=st(),o=_o(null),c=_o(null);Lo(()=>{c.current=e.session?.id??null},[e.session?.id]),Lo(()=>{let u=!0,m=null,l=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{l(),o.current=setTimeout(()=>{u&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Vr)};return(()=>{try{m=new jt("/events"),m.on("task_status_change",()=>{}),m.on("approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:a.taskId,approvalId:a.approvalId,toolName:a.toolName,toolInput:a.toolInput,matchedPattern:a.matchedPattern}})}),m.on("plan_approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:a.taskId,planId:a.planId,roleId:a.roleId,plan:a.plan}})}),m.on("plan_approval_decision",()=>{u&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),m.on("config_changed",()=>{u&&t({type:"CONFIG_CHANGED"})}),m.on("execution_task_start",r=>{if(!u)return;let a=r,d=c.current;d&&(async()=>{try{let C=await T(`/tasks/${a.taskId}`);u&&C.sourceSessionId===d&&t({type:"SET_ACTIVE_TASK",taskId:a.taskId})}catch{}})()}),m.on("stats_update",r=>{if(!u)return;let a=r;t({type:"UPDATE_STATS",activeTasks:a.activeTasks,queuedTasks:a.queuedTasks,costToday:a.totalCostToday})}),m.connect().then(async()=>{if(u){l(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await T("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{u&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{u&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{u=!1,l(),m?.close()}},[t])}import{useEffect as $r,useRef as Or,useState as $o,useCallback as qr}from"react";function Oo(e){let[t,o]=$o([]),[c,u]=$o(!1),m=Or(null),l=qr(()=>{o([]),u(!1)},[]);return $r(()=>{if(!e)return;let i=!0;o([]),u(!0);try{let n=new Ro(e);return m.current=n,n.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(C=>{let p=C[C.length-1];if(p?.type==="reasoning"){let b=[...C];return b[b.length-1]={...p,content:p.content+d},b}return[...C,{type:"reasoning",content:d,timestamp:Date.now()}]})}),n.on("tool_call",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_call",content:a.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:a.toolName}}])}),n.on("tool_result",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_result",content:a.content??"",timestamp:Date.now()}])}),n.on("error",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"error",content:a.error??"unknown error",timestamp:Date.now()}])}),n.on("complete",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"complete",content:a.result??"",timestamp:Date.now(),metadata:{cost:a.costUsd,turns:a.numTurns,duration:a.totalDurationMs}}]),u(!1)}),n.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),u(!1))}),()=>{i=!1,n.close()}}catch{u(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as io,useEffect as Fr,useCallback as Dt}from"react";function ao(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function qo(){let[e,t]=io(null),[o,c]=io(!0),[u,m]=io(null),l=Dt(async()=>{try{let C=(await T("/chat/sessions?status=active")).sessions.find(p=>p.source.type==="tui");return C?ao(C):null}catch{return null}},[]),i=Dt(async()=>{try{let d=await T("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),C=ao(d.session);return t(C),C}catch{return m("Failed to create session"),null}},[]),n=Dt(async d=>{try{let C=await T("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(p=>p&&{...p,messageCount:p.messageCount+1,lastActiveAt:Date.now()}),C}catch{return null}},[]),r=Dt(async()=>{if(!e)return!1;try{return await T(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),a=Dt(async()=>{if(e)try{let d=await T(`/chat/sessions/${e.id}`);t(ao(d.session))}catch{t(null)}},[e]);return Fr(()=>{let d=!1;async function C(){c(!0);let p=await l();d||(p?t(p):await i(),d||c(!1))}return C(),()=>{d=!0}},[]),{session:e,loading:o,error:u,sendMessage:n,createNewSession:i,archiveCurrentSession:r,refreshSession:a,setSession:t}}import{useEffect as Fo,useRef as Ur,useState as Wr}from"react";function Uo(e){let[t,o]=Wr(null),c=Ur(new Set);return Fo(()=>{if(!e)return;let u=!0,m=null;try{m=new jt("/chat/stream"),m.on("chat_message",l=>{if(!u)return;let n=l.message;n&&n.sessionId===e&&n.role==="assistant"&&(c.current.has(n.id)||(c.current.add(n.id),o(n)))}),m.connect().catch(()=>{})}catch{}return()=>{u=!1,m?.close()}},[e]),Fo(()=>{c.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as co,Text as _e}from"ink";import Le from"chalk";var lo={connected:Le.green,disconnected:Le.red,warning:Le.yellow,reasoning:Le.gray,toolCall:Le.blue,toolResult:Le.green,error:Le.red,dim:Le.dim,bold:Le.bold,statusUp:Le.green("\u25CF"),statusDown:Le.red("\u25CF")};import{Fragment as Gr,jsx as ut,jsxs as it}from"react/jsx-runtime";function Wo(){let{state:e}=st(),t=e.connected?`${lo.statusUp} Server: up`:`${lo.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,m=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return it(co,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[it(co,{children:[ut(_e,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ut(_e,{children:" \u2502 "}),ut(_e,{children:t}),ut(_e,{children:" \u2502 "}),it(_e,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&it(Gr,{children:[ut(_e,{children:" \u2502 "}),it(_e,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),m&&ut(_e,{color:"yellow",children:" timeout soon"})]})]}),it(co,{children:[it(_e,{children:["Tasks: ",o]}),ut(_e,{children:" \u2502 "}),it(_e,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Kt,Text as zt,useInput as jr}from"ink";import{useState as mo,useMemo as Kr}from"react";import zr from"ink-text-input";var Hr=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function uo(e){let t=e.toLowerCase();return Hr.filter(o=>o.name.startsWith(t))}function Go(e){let t=uo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Qt,jsxs as Rt}from"react/jsx-runtime";function Ho({onSubmit:e}){let[t,o]=mo(""),[c,u]=mo(0),[m,l]=mo(!1),i=t.startsWith("/")&&t.length>=1,n=t.slice(1),r=Kr(()=>i?uo(n):[],[i,n]),a=p=>{o(p),p.startsWith("/")?(l(!0),u(0)):l(!1)},d=()=>{let p=t.trim();if(p){if(p.startsWith("/")){let b=p.slice(1),s=Go(b);e(s?`/${s.name}`:p)}else e(p);o(""),l(!1)}},C=p=>{e(`/${p.name}`),o(""),l(!1)};return jr((p,b)=>{if(!(!m||!i||r.length===0)){if(b.upArrow){u(s=>s<=0?r.length-1:s-1);return}if(b.downArrow){u(s=>s>=r.length-1?0:s+1);return}if(b.tab){let s=r[c];s&&C(s);return}if(b.escape){l(!1),o("");return}}},{isActive:m&&i&&r.length>0}),Rt(Kt,{flexDirection:"column",children:[m&&i&&r.length>0&&Qt(Kt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((p,b)=>{let s=b===c;return Rt(Kt,{children:[Qt(zt,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),Rt(zt,{color:s?"cyan":"white",bold:s,children:["/",p.name]}),Rt(zt,{dimColor:!0,children:[" \u2014 ",p.description]})]},p.name)})}),Rt(Kt,{borderStyle:"round",borderDimColor:!0,children:[Qt(zt,{bold:!0,children:"\u25B8 "}),Qt(zr,{value:t,onChange:a,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as ht,Text as Ce}from"ink";import{useState as Qr}from"react";import{jsx as Ae,jsxs as We}from"react/jsx-runtime";function Xr({content:e}){let[t,o]=Qr(!1),c=e.split(`
2
+ `);return c.length<=5?Ae(Ce,{color:"green",children:e}):t?Ae(Ce,{color:"green",children:e}):We(Ce,{color:"green",children:[c.slice(0,3).join(`
3
+ `),`
4
+ `,We(Ce,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function Yr({event:e}){switch(e.type){case"reasoning":return Ae(ht,{children:Ae(Ce,{color:"gray",children:e.content})});case"tool_call":return Ae(ht,{children:We(Ce,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return We(ht,{flexDirection:"column",children:[Ae(Ce,{color:"blue",dimColor:!0,children:"[result]"}),Ae(Xr,{content:e.content})]});case"error":return Ae(ht,{children:We(Ce,{color:"red",children:["[error] ",e.content]})});case"complete":return We(ht,{flexDirection:"column",marginTop:1,children:[e.content&&Ae(Ce,{children:e.content}),Ae(Ce,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&We(Ce,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&We(Ce,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&We(Ce,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function jo({events:e,isStreaming:t}){return e.length===0&&!t?null:We(ht,{flexDirection:"column",children:[t&&e.length===0&&Ae(Ce,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>Ae(Yr,{event:o},c))]})}import{Box as Ko,Text as zo}from"ink";import{jsx as go,jsxs as Jr}from"react/jsx-runtime";function Qo({messages:e}){return e.length===0?null:go(Ko,{flexDirection:"column",children:e.map((t,o)=>Jr(Ko,{flexDirection:"column",marginBottom:1,children:[go(zo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),go(zo,{children:t.content})]},o))})}import{Box as Mt,Text as Ge,useInput as Zr}from"ink";import{jsx as He,jsxs as Nt}from"react/jsx-runtime";function Xo({approval:e,onResolved:t}){return Zr(o=>{o==="a"?T(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&T(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Nt(Mt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[He(Ge,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Nt(Mt,{marginTop:1,children:[He(Ge,{children:"Tool: "}),He(Ge,{bold:!0,children:e.toolName})]}),Nt(Mt,{children:[He(Ge,{children:"Input: "}),He(Ge,{children:JSON.stringify(e.toolInput)})]}),Nt(Mt,{children:[He(Ge,{children:"Pattern: "}),He(Ge,{dimColor:!0,children:e.matchedPattern})]}),Nt(Mt,{marginTop:1,children:[He(Ge,{color:"green",children:"[a] Approve"}),He(Ge,{children:" "}),He(Ge,{color:"red",children:"[r] Reject"})]})]})}import{Box as Lt,Text as he,useInput as en}from"ink";import{useState as tn,useEffect as on}from"react";import{jsx as Ye,jsxs as Ve}from"react/jsx-runtime";var rn=300;function Yo({approval:e,onResolved:t,onTimeout:o}){let[c,u]=tn(rn);on(()=>{let l=setInterval(()=>{u(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),en(l=>{l==="a"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let m=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ve(Lt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Ye(he,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ve(he,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ve(he,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ve(Lt,{marginTop:1,children:[Ye(he,{children:"Overall Risk: "}),Ye(he,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),Ve(he,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return Ve(Lt,{paddingLeft:2,children:[Ve(he,{children:["[",l.index,"] "]}),Ye(he,{children:l.description}),Ve(he,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ve(he,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ve(Lt,{marginTop:1,children:[Ye(he,{dimColor:!0,children:"Permissions: "}),Ye(he,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ve(Lt,{marginTop:1,children:[Ye(he,{color:"green",children:"[a] Allow once "}),Ye(he,{color:"green",children:"[p] Allow permanent "}),Ye(he,{color:"red",children:"[r] Deny"})]})]})}import{Box as mt,Text as ae,useInput as an}from"ink";import{useEffect as ln,useState as Je,useCallback as Zo}from"react";import{Box as oe,Text as _,useInput as nn}from"ink";import{useState as fo,useEffect as sn}from"react";import{jsx as U,jsxs as K}from"react/jsx-runtime";function Jo({taskId:e,onBack:t}){let[o,c]=fo(null),[u,m]=fo([]),[l,i]=fo(null);if(sn(()=>{T(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),T(`/tasks/${e}/plan`).then(r=>m(r.plans)).catch(()=>m([]))},[e]),nn((r,a)=>{(r==="b"||a.escape)&&t()}),l)return K(oe,{flexDirection:"column",children:[K(_,{color:"red",children:["Error: ",l]}),U(_,{dimColor:!0,children:"[b] Back"})]});if(!o)return K(_,{dimColor:!0,children:["Loading task ",e,"..."]});let n=u[0];return K(oe,{flexDirection:"column",children:[U(_,{bold:!0,color:"cyan",children:"Task Detail"}),K(oe,{marginTop:1,flexDirection:"column",children:[K(oe,{children:[U(_,{children:"ID: "}),U(_,{dimColor:!0,children:String(o.id)})]}),K(oe,{children:[U(_,{children:"Status: "}),U(_,{bold:!0,children:String(o.status)})]}),K(oe,{children:[U(_,{children:"Prompt: "}),U(_,{children:String(o.prompt)})]}),o.result?K(oe,{children:[U(_,{children:"Result: "}),U(_,{children:String(o.result).slice(0,200)})]}):null,o.error?K(oe,{children:[U(_,{color:"red",children:"Error: "}),U(_,{children:String(o.error)})]}):null,o.deliverTo?.length?K(oe,{children:[U(_,{children:"DeliverTo: "}),U(_,{dimColor:!0,children:o.deliverTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null,o.reportTo?.length?K(oe,{children:[U(_,{children:"ReportTo: "}),U(_,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),n&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"cyan",children:"Execution Plan"}),K(oe,{children:[U(_,{children:"Plan ID: "}),U(_,{dimColor:!0,children:n.id})]}),K(oe,{children:[U(_,{children:"Status: "}),U(_,{children:n.status})]}),n.plan.overallRisk&&K(oe,{children:[U(_,{children:"Overall Risk: "}),U(_,{bold:!0,color:n.plan.overallRisk==="high"?"red":n.plan.overallRisk==="medium"?"yellow":"green",children:n.plan.overallRisk.toUpperCase()})]}),K(_,{bold:!0,children:["Steps (",n.plan.steps.length,"):"]}),n.plan.steps.map(r=>{let a=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return K(oe,{paddingLeft:2,children:[K(_,{children:["[",r.index,"] ",r.description]}),K(_,{color:a,children:[" [",r.riskLevel,"]"]})]},r.index)}),n.deviationReport&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"yellow",children:"Deviation Report"}),K(_,{children:["Planned: ",n.deviationReport.stepsPlanned," | Executed: ",n.deviationReport.stepsExecuted," | Accuracy: ",(n.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),n.deviationReport.deviations.map((r,a)=>K(oe,{paddingLeft:2,children:[K(_,{color:"yellow",children:["[",r.deviationType,"] "]}),K(_,{children:["Step ",r.stepIndex,": ",r.actual]})]},a))]}),n.learnedRules&&n.learnedRules.length>0&&K(oe,{marginTop:1,flexDirection:"column",children:[U(_,{bold:!0,color:"blue",children:"Learned Rules"}),n.learnedRules.map((r,a)=>U(oe,{paddingLeft:2,children:K(_,{children:["* ",r]})},a))]})]}),!n&&u.length===0&&U(oe,{marginTop:1,children:U(_,{dimColor:!0,children:"No execution plan for this task."})}),U(oe,{marginTop:1,children:U(_,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as un,jsx as ye,jsxs as Ie}from"react/jsx-runtime";var cn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Xt=["all","pending","queued","running","completed","failed","cancelled"],po=15;function Yt({onBack:e}){let[t,o]=Je([]),[c,u]=Je(!0),[m,l]=Je("list"),[i,n]=Je(0),[r,a]=Je("all"),[d,C]=Je(0),[p,b]=Je(0),[s,g]=Je(null),[V,N]=Je([]),Z=Zo(async()=>{u(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let k=await T(`/tasks?${I}`);o(k.tasks)}catch{o([])}finally{u(!1)}},[r]);ln(()=>{Z()},[Z]);let j=Math.max(1,Math.ceil(t.length/po)),q=t.slice(p*po,(p+1)*po),de=Zo(async()=>{let I=q[i];if(I)try{await T(`/tasks/${I.id}/cancel`,{method:"POST"}),g(`Cancelled: ${I.id.slice(0,8)}`),l("list"),Z()}catch(k){g(`Failed: ${k instanceof Error?k.message:String(k)}`),l("list")}},[q,i,Z]);return an((I,k)=>{if(m==="detail"){(k.escape||k.return||I==="q")&&l("list");return}if(m==="cancelling"){I==="y"?de():l("list");return}if(m==="filter"){if(k.escape){l("list");return}k.upArrow&&d>0&&C(S=>S-1),k.downArrow&&d<Xt.length-1&&C(S=>S+1),k.return&&(a(Xt[d]),b(0),n(0),l("list"));return}if(k.escape||I==="q"){e();return}if(k.upArrow&&i>0&&n(S=>S-1),k.downArrow&&i<q.length-1&&n(S=>S+1),k.return){let S=q[i];S&&(N([]),l("detail"),T(`/tasks/${S.id}/logs?limit=20`).then(({logs:Q})=>N(Q)).catch(()=>N([])))}if(I==="x"&&q[i]){let S=q[i];["running","pending","queued","paused"].includes(S.status)?(l("cancelling"),g(null)):g(`Cannot cancel task in status: ${S.status}`)}I==="f"&&(C(Xt.indexOf(r)),l("filter")),I==="r"&&Z(),(k.pageDown||I==="n")&&p<j-1&&(b(S=>S+1),n(0)),(k.pageUp||I==="p")&&p>0&&(b(S=>S-1),n(0))}),c?ye(ae,{dimColor:!0,children:"Loading tasks..."}):m==="filter"?Ie(mt,{flexDirection:"column",children:[ye(ae,{bold:!0,children:"Filter by status:"}),Xt.map((I,k)=>ye(mt,{children:Ie(ae,{color:k===d?"cyan":"white",children:[k===d?"> ":" ",I,I===r?" (current)":""]})},I)),ye(ae,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):m==="detail"&&q[i]?ye(Jo,{taskId:q[i].id,onBack:()=>l("list")}):m==="cancelling"&&q[i]?Ie(mt,{flexDirection:"column",children:[Ie(ae,{color:"red",children:['Cancel task "',q[i].id.slice(0,8),'"? (y/n)']}),s&&ye(ae,{color:"red",children:s})]}):Ie(mt,{flexDirection:"column",children:[Ie(mt,{children:[Ie(ae,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&Ie(ae,{dimColor:!0,children:[" [filter: ",r,"]"]}),Ie(ae,{dimColor:!0,children:[" \u2014 Page ",p+1,"/",j]})]}),s&&ye(ae,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?Ie(ae,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):Ie(un,{children:[ye(mt,{marginTop:1,children:Ie(ae,{bold:!0,children:[" ",at("ID",10),at("STATUS",12),at("PROMPT",40),at("DURATION",10),"COST"]})}),q.map((I,k)=>{let S=k===i,Q=I.totalDurationMs?`${(I.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",ee=I.costUsd!==void 0?`$${I.costUsd.toFixed(4)}`:"\u2014",Me=cn[I.status]??"white";return Ie(mt,{children:[ye(ae,{color:S?"cyan":"white",children:S?"> ":" "}),ye(ae,{dimColor:!0,children:at(I.id.slice(0,8),10)}),ye(ae,{color:Me,children:at(I.status,12)}),ye(ae,{children:at(dn(I.prompt,38),40)}),ye(ae,{dimColor:!0,children:at(Q,10)}),ye(ae,{dimColor:!0,children:ee})]},I.id)})]}),ye(ae,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function at(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function dn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}Do();import{Box as _t,Text as $e,useInput as mn}from"ink";import{useEffect as gn,useState as er}from"react";import{readFileSync as fn,existsSync as pn}from"fs";import{parse as xn}from"yaml";import{Fragment as Tn,jsx as Oe,jsxs as lt}from"react/jsx-runtime";function or({onBack:e}){let[t,o]=er(null),[c,u]=er(null);return mn((m,l)=>{(l.escape||m==="q")&&e()}),gn(()=>{try{let m=Ao;if(!pn(m)){u(`Config file not found: ${m}`);return}let l=fn(m,"utf-8");o(xn(l))}catch(m){u(m.message)}},[]),c?lt(_t,{flexDirection:"column",children:[Oe($e,{color:"red",children:c}),Oe($e,{dimColor:!0,children:"Press Esc to go back"})]}):t?lt(_t,{flexDirection:"column",children:[Oe($e,{bold:!0,children:"Configuration (Esc to go back)"}),Oe(_t,{marginTop:1,flexDirection:"column",children:Oe(rr,{obj:t,indent:0})})]}):Oe($e,{dimColor:!0,children:"Loading config..."})}function rr({obj:e,indent:t}){let o=" ".repeat(t);return Oe(Tn,{children:Object.entries(e).map(([c,u])=>u&&typeof u=="object"&&!Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),":"]}),Oe(rr,{obj:u,indent:t+1})]},c):Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),":"]}),u.map((m,l)=>lt($e,{children:[o," - ",tr(c,String(m))]},l))]},c):lt($e,{children:[o,Oe($e,{color:"cyan",children:c}),": ",tr(c,String(u))]},c))})}function tr(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as Jt,Text as qe,useInput as hn}from"ink";import{useEffect as yn,useState as xo}from"react";import{jsx as Vt,jsxs as je}from"react/jsx-runtime";function nr({onBack:e}){let[t,o]=xo([]),[c,u]=xo(!0),[m,l]=xo(null);return hn((i,n)=>{(n.escape||i==="q")&&e()}),yn(()=>{T("/evolution-audit?limit=20").then(i=>{o(i),u(!1)}).catch(i=>{l(i.message),u(!1)})},[]),c?Vt(qe,{dimColor:!0,children:"Loading evolution log..."}):m?je(Jt,{flexDirection:"column",children:[Vt(qe,{color:"red",children:m}),Vt(qe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?je(Jt,{flexDirection:"column",children:[Vt(qe,{dimColor:!0,children:"No evolution records yet"}),Vt(qe,{dimColor:!0,children:"Press Esc to go back"})]}):je(Jt,{flexDirection:"column",children:[je(qe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>je(Jt,{flexDirection:"column",marginTop:1,children:[je(qe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&je(qe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
5
+ `).map((n,r)=>n.startsWith("+")?je(qe,{color:"green",children:[" ",n]},r):n.startsWith("-")?je(qe,{color:"red",children:[" ",n]},r):je(qe,{dimColor:!0,children:[" ",n]},r))]},i.id))]})}import{Box as Ze,Text as re,useInput as vn}from"ink";import bn from"ink-text-input";import{useEffect as Sn,useState as yt}from"react";import{jsx as we,jsxs as ge}from"react/jsx-runtime";var Cn={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function wn(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Bn(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Zt({onBack:e}){let[t,o]=yt([]),[c,u]=yt(null),[m,l]=yt("list"),[i,n]=yt(""),[r,a]=yt(!1),[d,C]=yt(null);vn((s,g)=>{if(m==="create"){g.escape&&(l("list"),n(""),C(null));return}(g.escape||s==="q")&&e(),s==="c"&&(l("create"),C(null)),s==="r"&&p()});let p=()=>{T("/goals?limit=20").then(({goals:s})=>o(s)).catch(s=>u(s.message))};Sn(()=>{p()},[]);let b=async s=>{if(s.trim()){a(!0),C(null);try{let g=await T("/goals",{method:"POST",body:{input:s.trim()}});C(`Goal created: ${g.goal.name}`),n(""),l("list"),p()}catch(g){C(`Failed: ${g instanceof Error?g.message:String(g)}`)}finally{a(!1)}}};return c?ge(Ze,{flexDirection:"column",children:[ge(re,{color:"red",children:["Failed to load goals: ",c]}),we(re,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?ge(Ze,{flexDirection:"column",children:[we(re,{bold:!0,children:"Create Goal"}),we(re,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),ge(Ze,{marginTop:1,children:[we(re,{color:"cyan",children:"> "}),we(bn,{value:i,onChange:n,onSubmit:b})]}),r&&we(re,{color:"yellow",children:"Creating goal..."}),d&&we(re,{color:d.startsWith("Failed")?"red":"green",children:d}),we(re,{dimColor:!0,children:"Press Esc to cancel"})]}):ge(Ze,{flexDirection:"column",children:[ge(re,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?we(re,{dimColor:!0,children:"No goals found. Press c to create one."}):we(Ze,{marginTop:1,flexDirection:"column",children:t.map(s=>{let g=s.targetValue>0?s.currentValue/s.targetValue:0,V=Cn[s.status]??"white";return ge(Ze,{marginBottom:1,flexDirection:"column",children:[ge(Ze,{children:[we(re,{bold:!0,color:V,children:s.name}),ge(re,{dimColor:!0,children:[" (",s.role,")"]}),we(re,{dimColor:!0,children:" \u2014 "}),we(re,{color:V,children:s.status})]}),ge(Ze,{children:[ge(re,{dimColor:!0,children:[" ",wn(g)," "]}),ge(re,{color:g>=1?"green":"white",children:[Math.round(g*100),"%"]}),ge(re,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),ge(Ze,{children:[ge(re,{dimColor:!0,children:[" \u23F0 ",Bn(s.deadline)," left"]}),ge(re,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),ge(re,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),we(re,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as vt,Text as De,useInput as En}from"ink";import{useEffect as In,useState as sr}from"react";import{jsx as tt,jsxs as et}from"react/jsx-runtime";function kn(e,t,o=15){let c=e/(e+t),u=Math.round(c*o);return"\u2593".repeat(u)+"\u2591".repeat(o-u)}function ir({onBack:e}){let[t,o]=sr([]),[c,u]=sr(null);if(En((l,i)=>{(i.escape||l==="q")&&e()}),In(()=>{T("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>u(l.message))},[]),c)return et(vt,{flexDirection:"column",children:[et(De,{color:"red",children:["Failed to load strategies: ",c]}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return et(vt,{flexDirection:"column",children:[tt(De,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]});let m=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,n=m.get(i)??[];n.push(l),m.set(i,n)}return et(vt,{flexDirection:"column",children:[tt(De,{bold:!0,children:"Strategy Lab"}),tt(De,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),tt(vt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([l,i])=>et(vt,{marginBottom:1,flexDirection:"column",children:[tt(De,{bold:!0,color:"cyan",children:l}),i.sort((n,r)=>{let a=n.alpha/(n.alpha+n.beta);return r.alpha/(r.alpha+r.beta)-a}).map(n=>{let r=n.alpha/(n.alpha+n.beta);return et(vt,{children:[tt(De,{dimColor:!0,children:" "}),et(De,{children:[kn(n.alpha,n.beta)," "]}),et(De,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),et(De,{dimColor:!0,children:[" ",n.name," (\u03B1=",n.alpha.toFixed(1)," \u03B2=",n.beta.toFixed(1)," trials=",n.totalTrials,")"]})]},n.id)})]},l))}),tt(De,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as xe,Text as G,useInput as Mn}from"ink";import To from"ink-text-input";import{useEffect as Nn,useState as Ke,useCallback as bt}from"react";import{CronExpressionParser as Ln}from"cron-parser";import{useState as Pn,useEffect as An,useCallback as ar,useRef as Dn}from"react";var Rn=3e3;function ct(){let[e,t]=Pn(null),o=Dn(null),c=ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),u=ar((m,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:m,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},Rn))},[]);return An(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:u,clearMessage:c}}import{jsx as X,jsxs as te}from"react/jsx-runtime";var ho=["manual","cron","event"],eo={name:"",triggerType:"manual",cron:"",stepPrompt:""};function _n(e){try{return Ln.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function to({onBack:e}){let[t,o]=Ke([]),[c,u]=Ke(!0),[m,l]=Ke(0),[i,n]=Ke("list"),[r,a]=Ke({...eo}),[d,C]=Ke("name"),[p,b]=Ke(null),{message:s,setMessage:g,clearMessage:V}=ct(),[N,Z]=Ke(!1),[j,q]=Ke(!1),[de,I]=Ke({}),k=bt(()=>{u(!0),T("/task-templates").then(({templates:v})=>{o(v),new Set(v.flatMap(A=>A.steps?.map(z=>z.roleId).filter(Boolean)??[])).size>0?T("/roles").then(({roles:A})=>{if(!Array.isArray(A)){I({});return}I(Object.fromEntries(A.map(z=>[z.id,z.name])))}).catch(()=>I({})):I({}),u(!1)}).catch(()=>u(!1))},[]);Nn(()=>{k()},[k]);let S=i==="create"||i==="edit",Q=bt(async()=>{let v=t[m];if(!(!v||N)){Z(!0),g(`Triggering ${v.name}...`,"loading");try{let M=await T(`/task-templates/${v.id}/run`,{method:"POST"});g(`Triggered: ${v.name} (${M.executionId})`,"success")}catch(M){g(`Trigger failed: ${M instanceof Error?M.message:String(M)}`,"error")}finally{Z(!1)}}},[t,m,N,g]),ee=bt(async()=>{let v=t[m];if(!v||j)return;if(v.trigger?.type!=="cron"&&v.trigger?.type!=="event"){g("Toggle not applicable for manual triggers","error");return}let M=!v.enabled;q(!0),g(`${v.name} \u2192 ${M?"enabling":"disabling"}...`,"loading");try{await T(`/task-templates/${v.id}`,{method:"PATCH",body:{enabled:M}}),o(A=>A.map(z=>z.id===v.id?{...z,enabled:M}:z)),g(`${v.name} ${M?"enabled":"disabled"}`,"success")}catch(A){g(`Toggle failed: ${A instanceof Error?A.message:String(A)}`,"error")}finally{q(!1)}},[t,m,j,g]),Me=bt(async()=>{let v=t[m];if(v)try{await T(`/task-templates/${v.id}`,{method:"DELETE"}),g(`Deleted: ${v.name}`,"success"),k(),l(M=>Math.max(0,Math.min(M,t.length-2)))}catch(M){g(`Delete failed: ${M instanceof Error?M.message:String(M)}`,"error")}},[t,m,k]),pt=bt(()=>{let v=t[m];v&&(b(v.id),a({name:v.name,triggerType:v.trigger?.type??"manual",cron:v.trigger?.cron??"",stepPrompt:v.steps?.[0]?.prompt??""}),C("name"),n("edit"))},[t,m]),Ee=bt(async()=>{let v={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await T("/task-templates",{method:"POST",body:v}),g(`Created: ${r.name}`,"success")):i==="edit"&&p&&(await T(`/task-templates/${p}`,{method:"PATCH",body:v}),g(`Updated: ${r.name}`,"success"))}catch(M){g(`Save failed: ${M instanceof Error?M.message:String(M)}`,"error")}n("list"),a({...eo}),b(null),k()},[r,i,p,k]);return Mn((v,M)=>{if(S){if(M.escape){n("list"),a({...eo}),b(null);return}if(M.return){let A=["name","triggerType","cron","stepPrompt"],z=A.indexOf(d);if(z<A.length-1){let Se=z+1;if(A[Se]==="cron"&&r.triggerType!=="cron"&&Se++,Se<A.length){C(A[Se]);return}}Ee();return}if(M.tab&&d==="triggerType"){a(A=>{let z=ho.indexOf(A.triggerType);return{...A,triggerType:ho[(z+1)%ho.length]}});return}return}if(M.escape||v==="q"){e();return}if(M.upArrow){l(A=>Math.max(0,A-1));return}if(M.downArrow){l(A=>Math.min(t.length-1,A+1));return}if(v==="t"){Q();return}if(v==="d"){Me();return}if(v==="e"){pt();return}if(v==="c"){a({...eo}),C("name"),n("create");return}if(v==="s"||v===" "){ee();return}v==="r"&&(k(),V())}),c?X(G,{dimColor:!0,children:"Loading templates..."}):S?te(xe,{flexDirection:"column",children:[te(G,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),te(xe,{marginTop:1,flexDirection:"column",children:[te(xe,{children:[te(G,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?X(To,{value:r.name,onChange:v=>a(M=>({...M,name:v})),placeholder:"template name"}):X(G,{children:r.name||"(empty)"})]}),te(xe,{children:[te(G,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),X(G,{children:r.triggerType}),d==="triggerType"&&X(G,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&te(xe,{children:[te(G,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?X(To,{value:r.cron,onChange:v=>a(M=>({...M,cron:v})),placeholder:"*/5 * * * *"}):X(G,{children:r.cron||"(empty)"})]}),te(xe,{children:[te(G,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?X(To,{value:r.stepPrompt,onChange:v=>a(M=>({...M,stepPrompt:v})),placeholder:"What should this template do?"}):X(G,{children:r.stepPrompt||"(empty)"})]})]}),X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):te(xe,{flexDirection:"column",children:[te(G,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&X(xe,{marginTop:1,children:te(G,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"No templates found. Press c to create one."})}):X(xe,{marginTop:1,flexDirection:"column",children:t.map((v,M)=>{let A=M===m,z=v.trigger?.type==="cron"&&v.trigger?.cron?_n(v.trigger.cron):"",Se=new Set(v.steps?.filter(E=>E.roleId).map(E=>E.roleId)),D=v.steps?.length>1?`${v.steps.length} steps${Se.size>0?` / ${Se.size} roles`:""}`:`${v.steps?.length??0} step`;return te(xe,{flexDirection:"column",children:[te(xe,{children:[X(G,{color:A?"cyan":void 0,bold:A,children:A?"> ":" "}),X(G,{color:A?"cyan":void 0,bold:A,children:$t(v.name,24)}),X(G,{dimColor:!0,children:$t(v.trigger?.type,10)}),v.trigger?.type!=="cron"&&v.trigger?.type!=="event"?X(G,{dimColor:!0,children:$t("\u2014",6)}):X(G,{color:v.enabled?"green":"gray",children:$t(v.enabled?"on":"off",6)}),X(G,{dimColor:!0,children:$t(D,18)}),z&&te(G,{dimColor:!0,children:["next: ",z]})]}),A&&v.steps?.length>1&&X(xe,{flexDirection:"column",marginLeft:4,marginTop:0,children:v.steps.map((E,O)=>te(xe,{children:[te(G,{dimColor:!0,children:[" ",O+1,". "]}),X(G,{dimColor:!0,children:E.id}),E.roleId&&te(G,{color:"yellow",children:[" @",de[E.roleId]??E.roleId]}),E.dependsOn&&E.dependsOn.length>0&&te(G,{dimColor:!0,children:[" (after: ",E.dependsOn.join(", "),")"]}),E.config&&te(G,{dimColor:!0,children:[" ","[",[E.config.timeout!==void 0?`timeout:${E.config.timeout}s`:"",E.config.maxTurns!==void 0?`turns:${E.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},E.id))})]},v.id)})}),X(xe,{marginTop:1,children:X(G,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function $t(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as dt,Text as ke,useInput as Vn}from"ink";import $n from"ink-text-input";import{useEffect as On,useState as St,useCallback as lr}from"react";import{jsx as ve,jsxs as gt}from"react/jsx-runtime";function cr({onBack:e}){let[t,o]=St([]),[c,u]=St(""),[m,l]=St(!0),[i,n]=St(!1),[r,a]=St(""),[d,C]=St(null),p=lr(()=>{l(!0),T("/webhooks").then(({webhooks:s,auth:g})=>{o(s),u(g),l(!1)}).catch(()=>l(!1))},[]);On(()=>{p()},[p]);let b=lr(async s=>{if(s.trim())try{let g=await T(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});C(`Triggered: ${g.executionId}`)}catch(g){C(`Trigger failed: ${g instanceof Error?g.message:String(g)}`)}},[]);return Vn((s,g)=>{if(i){if(g.escape){n(!1),a("");return}if(g.return){b(r),n(!1),a("");return}return}if(g.escape||s==="q"){e();return}if(s==="t"){n(!0),a(""),C(null);return}s==="r"&&(p(),C(null))}),m?ve(ke,{dimColor:!0,children:"Loading webhooks..."}):gt(dt,{flexDirection:"column",children:[gt(ke,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),gt(ke,{dimColor:!0,children:["Auth: ",c]}),d&&ve(dt,{marginTop:1,children:ve(ke,{color:"yellow",children:d})}),i&&gt(dt,{marginTop:1,children:[ve(ke,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ve($n,{value:r,onChange:a,placeholder:"webhook name or ID"}),ve(ke,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ve(dt,{marginTop:1,children:ve(ke,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):gt(dt,{marginTop:1,flexDirection:"column",children:[ve(dt,{children:gt(ke,{bold:!0,children:[Ct("NAME",24),Ct("DESCRIPTION",36),Ct("TRIGGER",28),"TAGS"]})}),t.map(s=>gt(dt,{children:[ve(ke,{children:Ct(s.displayName,24)}),ve(ke,{dimColor:!0,children:Ct(qn(s.description??"",34),36)}),ve(ke,{dimColor:!0,children:Ct(s.trigger,28)}),ve(ke,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),ve(dt,{marginTop:1,children:ve(ke,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function Ct(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function qn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as ze,Text as le,useInput as Fn}from"ink";import Un from"ink-text-input";import{useEffect as dr,useState as ot,useCallback as yo}from"react";import{jsx as ce,jsxs as Fe}from"react/jsx-runtime";function Wn(e){return e>=4?"red":e===3?"yellow":"gray"}function Gn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Hn(e){return new Date(e).toLocaleDateString()}function mr({onBack:e}){let[t,o]=ot([]),[c,u]=ot(0),[m,l]=ot([]),[i,n]=ot(!0),[r,a]=ot(!1),[d,C]=ot(""),[p,b]=ot("all"),[s,g]=ot(null),[V,N]=ot(!1),Z=yo(()=>{T("/agents").then(({agents:S})=>{o(S),n(!1)}).catch(()=>n(!1))},[]);dr(()=>{Z()},[Z]);let j=t[c],q=yo(()=>{j&&(N(!1),T(`/memories/${j.id}`).then(({memories:S})=>{l(S),g(null)}).catch(S=>g(`Failed: ${S instanceof Error?S.message:String(S)}`)))},[j]);dr(()=>{j&&q()},[j,q]);let de=yo(async S=>{if(!(!j||!S.trim()))try{let Q=await T("/memories/query",{method:"POST",body:{agentId:j.id,prompt:S.trim()}});l(Q.memories),N(!0),g(`Search: ${Q.count} results`)}catch(Q){g(`Search failed: ${Q instanceof Error?Q.message:String(Q)}`)}},[j]),I=r,k=m.filter(S=>p==="all"?!0:p==="high"?S.importance>3:p==="medium"?S.importance===3:S.importance<3);return Fn((S,Q)=>{if(I){if(Q.escape){a(!1),C("");return}if(Q.return){de(d),a(!1),C("");return}return}if(Q.escape||S==="q"){e();return}if(S==="a"){u(ee=>(ee+1)%Math.max(1,t.length));return}if(Q.leftArrow){u(ee=>(ee-1+t.length)%Math.max(1,t.length));return}if(Q.rightArrow){u(ee=>(ee+1)%Math.max(1,t.length));return}if(S==="s"){a(!0),C(""),g(null);return}if(S==="h"){b(ee=>ee==="high"?"all":"high");return}if(S==="m"){b(ee=>ee==="medium"?"all":"medium");return}if(S==="l"){b(ee=>ee==="low"?"all":"low");return}S==="r"&&q()}),i?ce(le,{dimColor:!0,children:"Loading agents..."}):t.length===0?Fe(ze,{flexDirection:"column",children:[ce(le,{dimColor:!0,children:"No agents found"}),ce(le,{dimColor:!0,children:"Press Esc to go back"})]}):Fe(ze,{flexDirection:"column",children:[ce(le,{bold:!0,children:"Memories (Esc to go back)"}),Fe(ze,{marginTop:1,children:[ce(le,{children:"Agent: "}),ce(le,{bold:!0,color:"cyan",children:j?.name??"?"}),Fe(le,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),ce(ze,{children:Fe(le,{dimColor:!0,children:["Filter: ",p==="all"?"all":p," | ",V?"search results":"all memories"," (",k.length,")"]})}),s&&ce(ze,{children:ce(le,{color:"yellow",children:s})}),r&&Fe(ze,{marginTop:1,children:[ce(le,{bold:!0,color:"cyan",children:"Search: "}),ce(Un,{value:d,onChange:C,placeholder:"search query..."}),ce(le,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),k.length===0?ce(ze,{marginTop:1,children:Fe(le,{dimColor:!0,children:["No memories",p!=="all"?` matching filter '${p}'`:""]})}):ce(ze,{marginTop:1,flexDirection:"column",children:k.map(S=>Fe(ze,{marginBottom:0,children:[Fe(le,{color:Wn(S.importance),bold:!0,children:[Gn(S.importance)," "]}),ce(le,{dimColor:!0,children:ur(S.type??"?",12)}),ce(le,{dimColor:!0,children:ur(`\xD7${S.retrievedCount??0}`,5)}),Fe(le,{children:[jn(S.content,55)," "]}),ce(le,{dimColor:!0,children:Hn(S.createdAt)}),S.score!==void 0&&Fe(le,{dimColor:!0,children:[" (",S.score.toFixed(2),")"]})]},S.id))}),ce(ze,{marginTop:1,children:ce(le,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function ur(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function jn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ue,Text as ne,useInput as Kn}from"ink";import oo from"ink-text-input";import{useState as Be,useEffect as gr,useCallback as vo}from"react";import{jsx as fe,jsxs as me}from"react/jsx-runtime";var fr={Anthropic:["anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel"],Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","defaults.approvalTimeout"],Server:["server.port","server.host","server.apiKey","server.timezone"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"],Workflow:["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},zn={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","defaults.approvalTimeout":"Approval Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold","watchdog.rules.artifactCleanup.enabled":"Artifact Cleanup Enabled","watchdog.rules.artifactCleanup.ttlDays":"Artifact Retention (days)","watchdog.rules.artifactCleanup.orphanGcMinAgeHours":"Orphan GC Min Age (hours)"};function pr({onBack:e}){let{state:t}=st(),[o,c]=Be({}),[u,m]=Be([]),[l,i]=Be(null),[n,r]=Be("view"),[a,d]=Be(0),[C,p]=Be(""),[b,s]=Be(null),[g,V]=Be(!1),[N,Z]=Be([]),[j,q]=Be({}),[de,I]=Be(0),[k,S]=Be(""),[Q,ee]=Be(""),[Me,pt]=Be(""),Ee=Object.values(fr).flat(),v=vo(()=>{T("/config").then(D=>{c(D.config),m(D.mutable)}).catch(D=>i(D.message)),T("/config/env-diff").then(D=>{Z(D.diffs)}).catch(()=>{}),T("/config/env").then(D=>q(D.env??{})).catch(()=>{})},[]);gr(()=>{v()},[v]),gr(()=>{t.configVersion>0&&v()},[t.configVersion,v]);let M=vo(async()=>{let D=Ee[a];if(D){V(!0),s(null);try{let E=C,O=o[D];if(O&&typeof O.value=="number"&&(E=Number(C),isNaN(E))){s("Invalid number"),V(!1);return}let se=await T("/config",{method:"PATCH",body:{[D]:E}});se.updated.length>0&&(s(`Updated: ${D}`),v()),se.errors.length>0&&s(se.errors[0]),r("view")}catch(E){s(`Failed: ${E instanceof Error?E.message:String(E)}`)}finally{V(!1)}}},[Ee,a,C,o,v]),A=Object.keys(j),z=vo(async D=>{try{await T("/config/env",{method:"PUT",body:D}),s("Env vars saved"),v()}catch(E){s(`Failed: ${E instanceof Error?E.message:String(E)}`)}},[v]);if(Kn((D,E)=>{if(n==="edit"){if(E.escape){r("view");return}return}if(n==="env-list"){if(E.escape){r("view");return}if(E.upArrow&&de>0&&I(O=>O-1),E.downArrow&&de<A.length-1&&I(O=>O+1),D==="a"){S(""),r("env-add-key");return}if(D==="d"&&A.length>0){let O=A[de],se={...j};delete se[O],z(se),de>=A.length-1&&de>0&&I(Qe=>Qe-1);return}if(E.return&&A.length>0){pt(j[A[de]]??""),r("env-edit-value");return}return}if(n==="env-add-key"){if(E.escape){r("env-list");return}return}if(n==="env-add-value"){if(E.escape){r("env-list");return}return}if(n==="env-edit-value"){if(E.escape){r("env-list");return}return}if(E.escape||D==="q"){e();return}if(E.upArrow&&a>0&&d(O=>O-1),E.downArrow&&a<Ee.length-1&&d(O=>O+1),E.return||D==="e"){let O=Ee[a],se=o[O];se&&se.mutable?(p(String(se.value??"")),r("edit"),s(null)):se&&!se.mutable&&s("This setting requires a restart to change")}D==="v"&&(I(0),r("env-list"),s(null)),D==="r"&&(v(),s("Refreshed")),D==="s"&&N.length>0&&T("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),Z([]),v()}),D==="l"&&N.length>0&&T("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),v()})}),l)return me(Ue,{flexDirection:"column",children:[me(ne,{color:"red",children:["Failed to load config: ",l]}),fe(ne,{dimColor:!0,children:"Press Esc or q to return"})]});let Se=0;return me(Ue,{flexDirection:"column",children:[fe(ne,{bold:!0,children:"Settings"}),b&&fe(ne,{color:b.startsWith("Failed")||b.startsWith("This setting")?"yellow":"green",children:b}),N&&N.length>0&&me(Ue,{flexDirection:"column",marginBottom:1,children:[me(ne,{color:"yellow",children:[".env differs from DB (",N.length," key(s)): ",N.map(D=>D.envKey).join(", ")]}),fe(ne,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),fe(Ue,{marginTop:1,flexDirection:"column",children:Object.entries(fr).map(([D,E])=>me(Ue,{marginBottom:1,flexDirection:"column",children:[fe(ne,{bold:!0,color:"cyan",children:D}),E.map(O=>{let se=o[O],xt=Se++===a,Tt=u.includes(O),Ut=zn[O]??O,Xe=se?String(se.value??""):"...";return n==="edit"&&xt?me(Ue,{children:[me(ne,{color:"cyan",children:["> ",Ut,": "]}),fe(oo,{value:C,onChange:p,onSubmit:()=>{M()}}),g&&fe(ne,{color:"yellow",children:" saving..."})]},O):me(Ue,{children:[me(ne,{color:xt?"cyan":"white",children:[xt?"> ":" ",Tt?" ":"\u{1F512} ",Ut,": "," "]}),fe(ne,{color:Tt?"white":"gray",children:Xe}),!Tt&&fe(ne,{dimColor:!0,children:" (restart required)"})]},O)})]},D))}),fe(ne,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),n.startsWith("env")&&me(Ue,{flexDirection:"column",marginTop:1,children:[me(ne,{bold:!0,color:"cyan",children:["Environment Variables (",A.length,")"]}),A.length===0&&n==="env-list"&&fe(ne,{dimColor:!0,children:" No env vars. Press a to add."}),A.map((D,E)=>{let O=E===de;return n==="env-edit-value"&&O?me(Ue,{children:[me(ne,{color:"cyan",children:["> ",D," = "]}),fe(oo,{value:Me,onChange:pt,onSubmit:()=>{z({...j,[D]:Me}),r("env-list")}})]},D):me(ne,{color:O&&n==="env-list"?"cyan":"white",children:[O&&n==="env-list"?"> ":" ",D," = ",j[D]]},D)}),n==="env-add-key"&&me(Ue,{children:[fe(ne,{color:"green",children:" New key: "}),fe(oo,{value:k,onChange:S,onSubmit:()=>{k.trim()&&(ee(""),r("env-add-value"))}})]}),n==="env-add-value"&&me(Ue,{children:[me(ne,{color:"green",children:[" ",k," = "]}),fe(oo,{value:Q,onChange:ee,onSubmit:()=>{z({...j,[k.trim()]:Q}),r("env-list")}})]}),fe(ne,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as ft,Text as be,useInput as Qn}from"ink";import{useEffect as Xn,useState as bo,useCallback as Yn}from"react";import{jsx as Te,jsxs as Bt}from"react/jsx-runtime";function xr({onBack:e}){let[t,o]=bo([]),[c,u]=bo(!0),[m,l]=bo(0),{message:i,setMessage:n,clearMessage:r}=ct(),a=Yn(()=>{u(!0),T("/plugins").then(({plugins:d})=>{o(d),u(!1)}).catch(()=>u(!1))},[]);return Xn(()=>{a()},[a]),Qn((d,C)=>{if(C.escape||d==="q"){e();return}if(C.upArrow){l(p=>Math.max(0,p-1));return}if(C.downArrow){l(p=>Math.min(t.length-1,p+1));return}d==="r"&&(a(),r())}),c?Te(be,{dimColor:!0,children:"Loading plugins..."}):Bt(ft,{flexDirection:"column",children:[Bt(be,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Te(ft,{marginTop:1,children:Bt(be,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"No plugins installed."})}):Bt(ft,{marginTop:1,flexDirection:"column",children:[Bt(ft,{children:[Te(be,{dimColor:!0,children:" "}),Te(be,{dimColor:!0,children:wt("Name",24)}),Te(be,{dimColor:!0,children:wt("Scope",8)}),Te(be,{dimColor:!0,children:wt("User",6)}),Te(be,{dimColor:!0,children:"Path"})]}),t.map((d,C)=>{let p=C===m,b=d.id.split("@")[0];return Bt(ft,{children:[Te(be,{color:p?"cyan":void 0,bold:p,children:p?"> ":" "}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(b,24)}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(d.scope,8)}),Te(be,{color:d.globalEnabled?"green":"gray",children:wt(d.globalEnabled?"on":"off",6)}),Te(be,{dimColor:!0,children:d.installPath})]},d.id)})]}),Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"r:refresh"})})]})}function wt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ro,Text as Tr,useInput as Jn}from"ink";import{useState as Zn}from"react";import{jsx as Et,jsxs as So}from"react/jsx-runtime";var es=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function hr({onBack:e}){let[t,o]=Zn("tasks");return Jn((c,u)=>{if(u.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),So(ro,{flexDirection:"column",children:[So(ro,{gap:1,marginBottom:1,children:[es.map(c=>{let u=t===c.id;return Et(ro,{children:So(Tr,{color:u?"cyan":"gray",bold:u,underline:u,children:["[",c.key,":",c.label,"]"]})},c.id)}),Et(ro,{flexGrow:1}),Et(Tr,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&Et(Yt,{onBack:e}),t==="automations"&&Et(to,{onBack:e}),t==="goals"&&Et(Zt,{onBack:e})]})}import{Box as J,Text as W,useInput as ts}from"ink";import{useEffect as os,useState as Ot}from"react";import{jsx as L,jsxs as pe}from"react/jsx-runtime";var yr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function vr({onBack:e}){let[t,o]=Ot([]),[c,u]=Ot(!0),[m,l]=Ot(0),[i,n]=Ot(null),[r,a]=Ot("");os(()=>{d()},[]);async function d(){try{let b=await T("/channels");o(b.channels)}catch{}u(!1)}async function C(b){if(t.find(g=>g.id===b)?.platform==="wechat")try{a("Starting WeChat QR login...");let g=await T(`/channels/${b}/wechat/qr-start`,{method:"POST"});if(g.qrcodeUrl){a(`Scan QR: ${g.qrcodeUrl}
6
+ Waiting for scan...`);let V=await T(`/channels/${b}/wechat/qr-wait`,{method:"POST",body:{sessionKey:g.sessionKey,timeoutMs:12e4}});a(V.message)}else a(g.message);d()}catch{a("WeChat connect failed")}else try{await T(`/channels/${b}/connect`,{method:"POST"}),a("Connecting..."),d()}catch{a("Connect failed")}}async function p(b){try{await T(`/channels/${b}/disconnect`,{method:"POST"}),a("Disconnected"),d()}catch{a("Disconnect failed")}}return ts((b,s)=>{if(i){if(s.escape||b==="q"){n(null);return}if(b==="c"){C(i.id);return}if(b==="d"){p(i.id);return}return}if(s.escape){e();return}if(s.upArrow){l(g=>Math.max(0,g-1));return}if(s.downArrow){l(g=>Math.min(t.length-1,g+1));return}if(s.return&&t[m]){n(t[m]),a("");return}}),c?L(J,{flexDirection:"column",children:L(W,{dimColor:!0,children:"Loading channels..."})}):i?pe(J,{flexDirection:"column",children:[pe(J,{marginBottom:1,children:[pe(W,{bold:!0,children:["Channel: ",i.name]}),L(W,{dimColor:!0,children:" (Esc to go back)"})]}),pe(J,{flexDirection:"column",gap:0,children:[pe(W,{children:["ID: ",i.id]}),pe(W,{children:["Platform: ",i.platform]}),pe(W,{children:["Status: ",L(W,{color:yr[i.status]??"white",children:i.status})]}),pe(W,{children:["Enabled: ",i.enabled?"yes":"no"]}),pe(W,{children:["Messages: ",i.messageCount]}),pe(W,{children:["Config: ",JSON.stringify(i.config)]})]}),L(J,{marginTop:1,children:L(W,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&L(W,{color:"yellow",children:r})]}):pe(J,{flexDirection:"column",children:[pe(J,{marginBottom:1,children:[L(W,{bold:!0,children:"Channels"}),pe(W,{dimColor:!0,children:[" (",t.length," total) "]}),L(W,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?L(W,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):pe(J,{flexDirection:"column",children:[pe(J,{children:[L(J,{width:3,children:L(W,{dimColor:!0,children:" "})}),L(J,{width:12,children:L(W,{bold:!0,dimColor:!0,children:"ID"})}),L(J,{width:16,children:L(W,{bold:!0,dimColor:!0,children:"Name"})}),L(J,{width:12,children:L(W,{bold:!0,dimColor:!0,children:"Platform"})}),L(J,{width:14,children:L(W,{bold:!0,dimColor:!0,children:"Status"})}),L(J,{width:10,children:L(W,{bold:!0,dimColor:!0,children:"Enabled"})}),L(J,{width:10,children:L(W,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((b,s)=>pe(J,{children:[L(J,{width:3,children:L(W,{children:s===m?">":" "})}),L(J,{width:12,children:L(W,{inverse:s===m,children:b.id.slice(0,8)})}),L(J,{width:16,children:L(W,{children:b.name})}),L(J,{width:12,children:L(W,{children:b.platform})}),L(J,{width:14,children:pe(W,{color:yr[b.status]??"white",children:[b.status==="connected"?"\u25CF":b.status==="error"?"\u2717":"\u25CB"," ",b.status]})}),L(J,{width:10,children:L(W,{color:b.enabled?"green":"gray",children:b.enabled?"yes":"no"})}),L(J,{width:10,children:L(W,{children:b.messageCount})})]},b.id))]})]})}import{Box as kt,Text as nt,useInput as ns}from"ink";import{useEffect as ss,useState as qt,useCallback as is}from"react";import{Box as R,Text as h,useInput as rs}from"ink";import rt from"ink-text-input";import{useEffect as br,useState as Y,useCallback as It}from"react";Do();import{Fragment as Sr,jsx as y,jsxs as B}from"react/jsx-runtime";function Cr({roleId:e,onBack:t}){let[o,c]=Y(null),[u,m]=Y([]),[l,i]=Y(!0),[n,r]=Y("view"),[a,d]=Y(""),[C,p]=Y(0),[b,s]=Y(""),[g,V]=Y([]),[N,Z]=Y(0),[j,q]=Y(new Set),[de,I]=Y("inline"),[k,S]=Y(""),[Q,ee]=Y(""),[Me,pt]=Y([]),[Ee,v]=Y(new Set),[M,A]=Y(0),[z,Se]=Y("default"),[D,E]=Y(""),[O,se]=Y(""),[Qe,xt]=Y("mode"),[Tt,Ut]=Y([]),[Xe,Wt]=Y(0),[Gt,Bo]=Y(""),[Eo,Io]=Y(""),[ko,Po]=Y(""),{message:$,setMessage:F}=ct(),ie=It(()=>{i(!0),T(`/roles/${e}`).then(({role:f,boundPlugins:w})=>{c(f),m(w??[]),d(f.cagPrompt??""),q(new Set(f.allowedTools??[])),I(f.executionMode??"inline"),S(f.model??""),ee(f.maxBudgetUsd!=null?String(f.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);br(()=>{ie(),T("/config").then(f=>{let w=f["defaults.deniedReadPaths"]?.value;Array.isArray(w)&&Ut(w)}).catch(()=>{})},[ie]),br(()=>{I(o?.executionMode??"inline"),S(o?.model??""),ee(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Se(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),se((o?.deniedBashPatterns??[]).join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns]);let Br=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:a}}),F("CAG prompt saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,a,ie,F]),Er=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Ne}}),F("Directories saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,ie,F]),Ir=It(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(j)}}),F("Tool permissions saved","success"),r("view"),ie()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,j,ie,F]),kr=It(async()=>{if(!o)return;let f={executionMode:de};k!==void 0&&(f.model=k);let w=parseFloat(Q);isNaN(w)||(f.maxBudgetUsd=w);try{await T(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Execution config saved","success"),r("view"),ie()}catch(x){F(`Save failed: ${x instanceof Error?x.message:String(x)}`,"error")}},[o,de,k,Q,ie,F]),Pr=It(async()=>{if(!o)return;let f={permissionMode:z},w=D.split(",").map(P=>P.trim()).filter(Boolean),x=O.split(",").map(P=>P.trim()).filter(Boolean);f.allowedBashPatterns=w.length>0?w:[],f.deniedBashPatterns=x.length>0?x:[];try{await T(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Permission config saved","success"),r("view"),ie()}catch(P){F(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[o,z,D,O,ie,F]),Ne=o?.additionalDirectories??[];if(rs((f,w)=>{if(w.escape){r("view");return}if(f==="r"){ie();return}switch(n){case"view":{if(f==="c"){r("edit-cag");return}if(f==="d"){r("edit-dirs"),p(0),s("");return}if(f==="t"){r("edit-tools");return}if(f==="x"){r("edit-exec");return}if(f==="h"){T("/channels?enabled=true").then(({channels:x})=>{pt(x.map(P=>({name:P.name,id:P.id}))),v(new Set(o?.allowedChannels??[])),A(0),r("edit-channels")}).catch(()=>F("Failed to load channels","error"));return}if(f==="p"){Se(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),se((o?.deniedBashPatterns??[]).join(", ")),xt("mode"),r("edit-permissions");return}if(f==="v"){Wt(0),r("edit-env");return}if(f==="i"){if(!o)return;let x=!o.inheritUserSettings;T(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:x}}).then(()=>{F(`Inherit user settings: ${x?"ON":"OFF"}`,"success"),ie()}).catch(()=>F("Failed to toggle","error"));return}break}case"edit-cag":{if(w.ctrl&&f==="s"){Br();return}break}case"edit-dirs":{if(f==="s"){Er();return}if(f==="a"){r("edit-dirs-add");return}if(f==="m"&&Ne.length>0){let x=Ne[C];if(x){c(ue=>ue&&{...ue,additionalDirectories:ue.additionalDirectories?.map((Pe,Ar)=>Ar===C?{...typeof Pe=="string"?{path:Pe}:Pe,mode:Pe.mode==="ro"?"rw":"ro"}:Pe)});let P=x.mode==="ro"?"rw":"ro";F(`Mode set to ${P.toUpperCase()}`,"success")}return}if(f==="x"&&Ne.length>0){c(x=>x&&{...x,additionalDirectories:Ne.filter((P,ue)=>ue!==C)}),p(x=>Math.max(0,Math.min(x,Ne.length-2)));return}if(w.upArrow){p(x=>Math.max(0,x-1));return}if(w.downArrow){p(x=>Math.min(Ne.length-1,x+1));return}break}case"edit-dirs-add":{if(w.escape){r("edit-dirs"),s(""),V([]);return}if(w.return&&g.length>0){let x=g[N];x&&(s(x.endsWith("/")?x:x+"/"),V([]));return}if(w.return){let x=b.trim();x&&x.startsWith("/")?(c(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:x,mode:"rw"}]}),s(""),V([]),r("edit-dirs")):F("Path must be absolute (must start with /)","error");return}if(w.tab){let x=b.trim();if(!x||!x.startsWith("/"))return;T(`/fs/suggest-dirs?prefix=${encodeURIComponent(x)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),V([])):P.length>1&&(V(P),Z(0))}).catch(()=>{V([])});return}if(w.upArrow&&g.length>0){Z(x=>Math.max(0,x-1));return}if(w.downArrow&&g.length>0){Z(x=>Math.min(g.length-1,x+1));return}break}case"edit-tools":{if(f==="s"){Ir();return}let x=parseInt(f,10)-1;if(!isNaN(x)&&x>=0&&x<Ht.length){let P=Ht[x];q(ue=>{let Pe=new Set(ue);return Pe.has(P)?Pe.delete(P):Pe.add(P),Pe});return}break}case"edit-exec":{if(f==="s"){kr();return}if(w.tab){I(x=>x==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(f==="s"){Pr();return}if(w.tab){xt(x=>x==="mode"?"allowed":x==="allowed"?"denied":"mode");return}if(Qe==="mode"&&(w.upArrow||w.downArrow)){let x=["default","acceptEdits","dontAsk","bypassPermissions"],P=x.indexOf(z);w.upArrow&&Se(x[Math.max(0,P-1)]),w.downArrow&&Se(x[Math.min(x.length-1,P+1)]);return}break}case"edit-channels":{if(f==="s"){if(!o)return;let x=Ee.size>0?Array.from(Ee):[];T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:x}}).then(()=>{F("Channels saved","success"),r("view"),ie()}).catch(()=>F("Save failed","error"));return}if(f==="u"){if(!o)return;T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{F("Channels: unrestricted","success"),r("view"),ie()}).catch(()=>F("Save failed","error"));return}if(f===" "){let x=Me[M];x&&v(P=>{let ue=new Set(P);return ue.has(x.name)?ue.delete(x.name):ue.add(x.name),ue});return}if(w.upArrow){A(x=>Math.max(0,x-1));return}if(w.downArrow){A(x=>Math.min(Me.length-1,x+1));return}break}case"edit-env":{let x=Object.keys(o?.envVars??{});if(f==="a"){Bo(""),r("edit-env-add-key");return}if(f==="d"&&x.length>0){let P=x[Xe],ue={...o?.envVars??{}};delete ue[P],T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:ue}}).then(()=>{F("Deleted","success"),ie()}).catch(()=>F("Delete failed","error")),Xe>=x.length-1&&Xe>0&&Wt(Pe=>Pe-1);return}if(w.return&&x.length>0){Po((o?.envVars??{})[x[Xe]]??""),r("edit-env-edit-value");return}w.upArrow&&Xe>0&&Wt(P=>P-1),w.downArrow&&Xe<x.length-1&&Wt(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),l)return y(h,{dimColor:!0,children:"Loading role..."});if(!o)return y(h,{dimColor:!0,children:"Role not found."});if(n==="edit-cag")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),y(rt,{value:a,onChange:d,placeholder:"Character And Guidance prompt..."}),$&&y(R,{marginTop:1,children:y(h,{color:$.type==="error"?"red":"green",children:$.text})})]});if(n==="edit-dirs-add")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),y(rt,{value:b,onChange:f=>{s(f),V([])},placeholder:"/absolute/path/to/directory"}),g.length>0&&B(R,{flexDirection:"column",marginTop:1,children:[g.map((f,w)=>B(h,{color:w===N?"cyan":void 0,dimColor:w!==N,children:[w===N?"> ":" ",f,"/"]},f)),y(h,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),$&&y(R,{marginTop:1,children:y(h,{color:$.type==="error"?"red":"green",children:$.text})})]});if(n==="edit-dirs")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),Ne.length===0?y(h,{dimColor:!0,children:"No directories. Press a to add one."}):Ne.map((f,w)=>{let x=typeof f=="string"?{path:f,mode:"rw"}:f,P=x.mode!=="ro";return B(R,{children:[y(h,{color:w===C?"cyan":void 0,bold:w===C,children:w===C?"> ":" "}),B(h,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),y(h,{color:w===C?"cyan":void 0,children:x.path})]},x.path)})]});if(n==="edit-tools")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),Ht.map((f,w)=>{let x=j.has(f);return B(R,{children:[B(h,{dimColor:!0,children:[w+1,". "]}),y(h,{color:x?"green":"red",children:x?"[ON] ":"[OFF] "}),y(h,{children:f})]},f)})]});if(n==="edit-exec")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(R,{children:[y(h,{bold:!0,children:" Mode: "}),y(h,{color:"cyan",children:de}),y(h,{dimColor:!0,children:" (Tab to toggle)"})]}),B(R,{children:[y(h,{bold:!0,children:" Model: "}),y(rt,{value:k,onChange:S,placeholder:"sonnet, opus, haiku, or blank"})]}),B(R,{children:[y(h,{bold:!0,children:" Max Budget (USD): "}),y(rt,{value:Q,onChange:ee,placeholder:"0 = unlimited"})]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n==="edit-permissions")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(R,{children:[y(h,{bold:!0,color:Qe==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(w=>B(h,{color:w===z?"green":"gray",children:[w===z?`[${w}]`:` ${w} `," "]},w))]}),B(R,{children:[y(h,{bold:!0,color:Qe==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),Qe==="allowed"?y(rt,{value:D,onChange:E,placeholder:"git add *, pnpm test*"}):y(h,{children:D||"(none)"})]}),B(R,{children:[y(h,{bold:!0,color:Qe==="denied"?"cyan":void 0,children:" Denied Bash: "}),Qe==="denied"?y(rt,{value:O,onChange:se,placeholder:"rm -rf *, ssh *"}):y(h,{children:O||"(none)"})]}),y(h,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n==="edit-channels")return B(R,{flexDirection:"column",children:[y(h,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Me.length===0?y(h,{dimColor:!0,children:"No channels available"}):Me.map((f,w)=>B(R,{children:[B(h,{children:[w===M?">":" "," "]}),B(h,{color:Ee.has(f.name)?"green":"gray",children:["[",Ee.has(f.name)?"x":" ","] ",f.name]})]},f.id)),B(h,{dimColor:!0,children:["Selected: ",Ee.size>0?Array.from(Ee).join(", "):"none (= block all)"]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(n.startsWith("edit-env")){let f=Object.keys(o.envVars??{});return B(R,{flexDirection:"column",children:[B(h,{bold:!0,children:["Environment Variables (",f.length,")"]}),f.length===0&&n==="edit-env"&&y(h,{dimColor:!0,children:" No env vars. Press a to add."}),f.map((w,x)=>{let P=x===Xe;return n==="edit-env-edit-value"&&P?B(R,{children:[B(h,{color:"cyan",children:["> ",w," = "]}),y(rt,{value:ko,onChange:Po,onSubmit:()=>{let ue={...o.envVars??{},[w]:ko};T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:ue}}).then(()=>{F("Saved","success"),ie(),r("edit-env")}).catch(()=>F("Save failed","error"))}})]},w):B(h,{color:P&&n==="edit-env"?"cyan":"white",children:[P&&n==="edit-env"?"> ":" ",w," = ",(o.envVars??{})[w]]},w)}),n==="edit-env-add-key"&&B(R,{children:[y(h,{color:"green",children:" New key: "}),y(rt,{value:Gt,onChange:Bo,onSubmit:()=>{Gt.trim()&&(Io(""),r("edit-env-add-value"))}})]}),n==="edit-env-add-value"&&B(R,{children:[B(h,{color:"green",children:[" ",Gt," = "]}),y(rt,{value:Eo,onChange:Io,onSubmit:()=>{let w={...o.envVars??{},[Gt.trim()]:Eo};T(`/roles/${o.id}`,{method:"PATCH",body:{envVars:w}}).then(()=>{F("Added","success"),ie(),r("edit-env")}).catch(()=>F("Add failed","error"))}})]}),y(h,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),$&&y(h,{color:$.type==="error"?"red":"green",children:$.text})]})}return B(R,{flexDirection:"column",children:[B(h,{bold:!0,children:["Role: ",o.name]}),B(R,{children:[y(h,{dimColor:!0,children:"ID: "}),y(h,{children:o.id})]}),B(R,{children:[y(h,{dimColor:!0,children:"Status: "}),y(h,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&B(R,{children:[y(h,{dimColor:!0,children:"Score: "}),B(h,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(R,{children:[y(h,{dimColor:!0,children:"Created: "}),y(h,{children:new Date(o.createdAt).toLocaleString()})]}),B(R,{children:[y(h,{dimColor:!0,children:"Execution: "}),B(h,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),Ne.length>0&&B(Sr,{children:[y(h,{bold:!0,children:"Additional Directories:"}),Ne.map(f=>B(h,{dimColor:!0,children:[" ",f.path]},f.path))]}),B(R,{children:[y(h,{dimColor:!0,children:"Permission: "}),y(h,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(R,{children:[y(h,{dimColor:!0,children:" Bash Allow: "}),y(h,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(R,{children:[y(h,{dimColor:!0,children:" Bash Deny: "}),y(h,{children:o.deniedBashPatterns.join(", ")})]}),Tt.length>0&&B(R,{flexDirection:"column",children:[y(h,{dimColor:!0,children:"Denied Read Paths (global):"}),Tt.map(f=>B(h,{dimColor:!0,children:[" ",f]},f)),B(h,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(R,{children:[y(h,{dimColor:!0,children:"Channels: "}),y(h,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(R,{children:[y(h,{dimColor:!0,children:"Inherit User Settings: "}),y(h,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&B(Sr,{children:[y(h,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(f=>B(h,{dimColor:!0,children:[" - ",f]},f))]}),$&&y(R,{children:y(h,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),y(R,{marginTop:1,children:y(h,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as Re,jsxs as no}from"react/jsx-runtime";function wr({onBack:e}){let[t,o]=qt([]),[c,u]=qt(!0),[m,l]=qt(0),[i,n]=qt("list"),[r,a]=qt(null),{message:d,setMessage:C,clearMessage:p}=ct(),b=is(()=>{u(!0),T("/roles").then(({roles:s})=>{o(s.map(g=>({id:g.id,name:g.name,status:g.status,performanceScore:g.performanceScore,createdAt:g.createdAt}))),u(!1)}).catch(()=>u(!1))},[]);return ss(()=>{b()},[b]),ns((s,g)=>{if(g.escape||s==="q"){e();return}if(g.upArrow){l(V=>Math.max(0,V-1));return}if(g.downArrow){l(V=>Math.min(t.length-1,V+1));return}if(s==="r"&&(b(),p()),s===`
7
+ `||s==="o"||s==="e"){t.length>0&&(a(t[m].id),n("detail"));return}}),c?Re(nt,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Re(Cr,{roleId:r,onBack:()=>n("list")}):no(kt,{flexDirection:"column",children:[no(nt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&Re(kt,{marginTop:1,children:no(nt,{color:d.type==="success"?"green":d.type==="error"?"red":"gray",children:[d.type==="success"?"\u2713 ":d.type==="error"?"\u2717 ":"\u2192 ",d.text]})}),t.length===0?Re(kt,{marginTop:1,children:Re(nt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Re(kt,{marginTop:1,flexDirection:"column",children:t.map((s,g)=>{let V=g===m,N=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014";return no(kt,{children:[Re(nt,{color:V?"cyan":void 0,bold:V,children:V?"> ":" "}),Re(nt,{color:V?"cyan":void 0,bold:V,children:Co(s.name,24)}),Re(nt,{color:as(s.status),children:Co(s.status,12)}),Re(nt,{dimColor:!0,children:Co(N,8)})]},s.id)})}),Re(kt,{marginTop:1,children:Re(nt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function as(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Co(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as gs,jsx as H,jsxs as At}from"react/jsx-runtime";function ds(){let{state:e,dispatch:t}=st(),{session:o,sendMessage:c,createNewSession:u,archiveCurrentSession:m}=qo(),[l,i]=cs([]);so(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Vo();let{latestMessage:n}=Uo(o?.id??null),r=wo(null);so(()=>{n&&n.id!==r.current&&(r.current=n.id,i(N=>[...N,{role:"assistant",content:n.content}]))},[n]);let{events:a,isStreaming:d,clearEvents:C}=Oo(e.activeTaskId),p=a[a.length-1],b=p?.type==="complete"&&!d,s=wo(null),g=wo("");so(()=>{g.current=a.filter(N=>N.type==="reasoning").map(N=>N.content).join("")},[a]),so(()=>{if(b&&e.activeTaskId!==s.current){s.current=e.activeTaskId;let N=p?.content||g.current;N&&i(Z=>[...Z,{role:"assistant",content:N}])}},[b,p,e.activeTaskId]);let V=async N=>{let Z=N.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(Z)&&process.exit(0),N.startsWith("/")){let q=N.slice(1),I={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"}[q];if(I){t({type:"SET_VIEW",view:I});return}if(q==="new"){if(await m()){let S=await u();i([]),C(),S&&i([{role:"assistant",content:`Session archived. New session started: ${S.id.slice(0,8)}`}])}return}if(q==="session"){let k=o?`Session: ${o.id}
8
+ Turns: ${o.messageCount}
9
+ Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(S=>[...S,{role:"assistant",content:k}]);return}}if(i(q=>[...q,{role:"user",content:N}]),C(),!await c(N)){i(q=>[...q,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}};return At(Ft,{flexDirection:"column",paddingX:1,children:[H(Wo,{}),At(Ft,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&At(gs,{children:[H(Qo,{messages:l}),H(jo,{events:a,isStreaming:d}),!e.connected&&!e.serverUnreachable&&H(Ft,{children:H(Pt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&At(Ft,{flexDirection:"column",children:[H(Pt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),H(Pt,{dimColor:!0,children:"Check: adam server logs"}),H(Pt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&H(hr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&H(Yt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&H(or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&H(nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&H(Zt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&H(ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&H(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&H(cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&H(mr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&H(xr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&H(wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&H(pr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&H(vr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?H(Yo,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?H(Xo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):H(Ho,{onSubmit:V}),e.planTimeoutNotice&&H(us,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function us({planId:e,onDismiss:t}){return ls(o=>{o==="d"&&t()}),At(Ft,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[At(Pt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),H(Pt,{dimColor:!0,children:" [d] Dismiss"})]})}function ms(){return H(No,{children:H(ds,{})})}export{ms as default};
@@ -0,0 +1 @@
1
+ import{n as a,o as b}from"./chunk-PVYEGQEG.js";import"./chunk-5V36ACKZ.js";import"./chunk-6NUHSHS5.js";import"./chunk-HFN7Y3IM.js";import"./chunk-AKPLOO2V.js";import"./chunk-NDP6LWXX.js";import"./chunk-NLD7WK3R.js";import"./chunk-JZNBFZ7W.js";import"./chunk-CLHSPXZ6.js";import"./chunk-TKDT7EQO.js";import"./chunk-AZBNUSM2.js";import"./chunk-ZQYKT5UY.js";import"./chunk-7IXLL673.js";import"./chunk-L7JP7DUO.js";import"./chunk-P6KWAGAY.js";import"./chunk-2CMR5AG7.js";import"./chunk-IZGTTLTG.js";import"./chunk-IKUBP3SY.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -1 +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};
1
+ import{a,b,c,d,e}from"./chunk-TCHBOWQ5.js";import"./chunk-WTRM5VO7.js";import"./chunk-CLHSPXZ6.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-4MJF77RD.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{l as a,m as b,n as c,o as d,p as e}from"./chunk-ZKMDHQJY.js";import"./chunk-6NUHSHS5.js";import"./chunk-HFN7Y3IM.js";import"./chunk-AKPLOO2V.js";import"./chunk-YHVFZB6Q.js";import"./chunk-JZNBFZ7W.js";import"./chunk-YPOTHL7X.js";import"./chunk-4NW2DNDZ.js";import"./chunk-7IXLL673.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-P6KWAGAY.js";import"./chunk-2CMR5AG7.js";import"./chunk-IZGTTLTG.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-7CJGPCSJ.js";import"./chunk-NLD7WK3R.js";import"./chunk-XTHP5JMO.js";import"./chunk-YHVFZB6Q.js";import"./chunk-JZNBFZ7W.js";import"./chunk-WTRM5VO7.js";import"./chunk-CLHSPXZ6.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-IZGTTLTG.js";import"./chunk-IKUBP3SY.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-OTH4M5L3.js";import"./chunk-WKS7QVIX.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -1 +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};
1
+ import{a,b,c,d,e,f}from"./chunk-CLHSPXZ6.js";import"./chunk-4MJF77RD.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 a,d as b,e as c}from"./chunk-72VLUJ2S.js";import"./chunk-CLHSPXZ6.js";import"./chunk-ZQYKT5UY.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1,4 +1,4 @@
1
- import{a as c,b as m}from"./chunk-6DXNXLYG.js";import{b as a,d as _}from"./chunk-KVSO3KGZ.js";import{c as s,h as f}from"./chunk-INNDBLZE.js";import{readFileSync as p,existsSync as g}from"fs";import{fileURLToPath as A}from"url";import{dirname as I,join as o}from"path";var O=A(import.meta.url),l=I(O),r,n;function u(){let e=o(l,"..","package.json");if(g(e))return e;let i=o(l,"..","..","package.json");return g(i)?i:o(process.cwd(),"package.json")}function P(){if(r===void 0){let e=u();r=JSON.parse(p(e,"utf-8")).version}return r}function b(){if(n===void 0){let e=u();n=JSON.parse(p(e,"utf-8")).name}return n}_();f();import{dirname as h,join as T}from"path";import{fileURLToPath as y}from"url";var k=h(y(import.meta.url)),d=T(k,"..");var x=d,U=s("cli:register-ai-digest"),t="ai-hourly-digest";function R(){try{if(m(t)){console.log(`[INFO] AI Digest template already exists (${t})`);return}}catch{}let e={id:t,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
1
+ import{a as c,b as m}from"./chunk-IKUBP3SY.js";import{b as a,d as _}from"./chunk-4MJF77RD.js";import{c as s,h as f}from"./chunk-INNDBLZE.js";import{readFileSync as p,existsSync as g}from"fs";import{fileURLToPath as A}from"url";import{dirname as I,join as o}from"path";var O=A(import.meta.url),l=I(O),r,n;function u(){let e=o(l,"..","package.json");if(g(e))return e;let i=o(l,"..","..","package.json");return g(i)?i:o(process.cwd(),"package.json")}function P(){if(r===void 0){let e=u();r=JSON.parse(p(e,"utf-8")).version}return r}function b(){if(n===void 0){let e=u();n=JSON.parse(p(e,"utf-8")).name}return n}_();f();import{dirname as h,join as T}from"path";import{fileURLToPath as y}from"url";var k=h(y(import.meta.url)),d=T(k,"..");var x=d,U=s("cli:register-ai-digest"),t="ai-hourly-digest";function R(){try{if(m(t)){console.log(`[INFO] AI Digest template already exists (${t})`);return}}catch{}let e={id:t,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
2
2
 
3
3
  \u641C\u7D22\u6765\u6E90:
4
4
  1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
@@ -1,4 +1,4 @@
1
- import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk-INNDBLZE.js";import{c as m}from"./chunk-FCV2DPZQ.js";import p from"better-sqlite3";import{existsSync as S,mkdirSync as g}from"fs";import{dirname as u}from"path";function D(e){e.exec(`
1
+ import{e as A,h as X}from"./chunk-WBAPIPST.js";import{c as R,h as O}from"./chunk-INNDBLZE.js";import{c as m}from"./chunk-FCV2DPZQ.js";import p from"better-sqlite3";import{existsSync as S,mkdirSync as u}from"fs";import{dirname as g}from"path";function C(e){e.exec(`
2
2
  CREATE TABLE IF NOT EXISTS server_state (
3
3
  id INTEGER PRIMARY KEY CHECK(id = 1),
4
4
  sdk_session_id TEXT,
@@ -8,7 +8,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
8
8
  created_at INTEGER NOT NULL DEFAULT (unixepoch('now') * 1000),
9
9
  last_active_at INTEGER
10
10
  );
11
- `),e.prepare("PRAGMA table_info(server_state)").all().some(E=>E.name==="schema_version")||e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 0");let o=e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0;if(o<2){let E=["delivery_log","delivery_rules","manager_decisions","skill_scores","approval_rules","task_plans","calibration_history","task_plugins","marketplaces","plugins","trials","strategies","metric_tree","goals","chat_messages","chat_sessions","channels","evolution_audit","step_logs","task_templates","memories","tasks","config","memories_fts","memories_fts_config","memories_fts_data","memories_fts_docsize","memories_fts_idx"];for(let s of E)try{e.exec(`DROP TABLE IF EXISTS ${s}`)}catch{}for(let s of["memories_fts_insert","memories_fts_delete","memories_fts_update"])try{e.exec(`DROP TRIGGER IF EXISTS ${s}`)}catch{}}if(e.exec(`
11
+ `),e.prepare("PRAGMA table_info(server_state)").all().some(E=>E.name==="schema_version")||e.exec("ALTER TABLE server_state ADD COLUMN schema_version INTEGER DEFAULT 0");let _=e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0;if(_<2){let E=["delivery_log","delivery_rules","manager_decisions","skill_scores","approval_rules","task_plans","calibration_history","task_plugins","marketplaces","plugins","trials","strategies","metric_tree","goals","chat_messages","chat_sessions","channels","evolution_audit","step_logs","task_templates","memories","tasks","config","memories_fts","memories_fts_config","memories_fts_data","memories_fts_docsize","memories_fts_idx"];for(let s of E)try{e.exec(`DROP TABLE IF EXISTS ${s}`)}catch{}for(let s of["memories_fts_insert","memories_fts_delete","memories_fts_update"])try{e.exec(`DROP TRIGGER IF EXISTS ${s}`)}catch{}}if(e.exec(`
12
12
  CREATE TABLE IF NOT EXISTS tasks (
13
13
  id TEXT PRIMARY KEY,
14
14
  parent_id TEXT,
@@ -368,7 +368,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
368
368
 
369
369
  CREATE INDEX IF NOT EXISTS idx_calibration_goal ON calibration_history(goal_id);
370
370
  CREATE INDEX IF NOT EXISTS idx_calibration_computed ON calibration_history(computed_at);
371
- `),o<2&&e.exec("UPDATE server_state SET schema_version = 2 WHERE id = 1"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<4&&(e.exec(`
371
+ `),_<2&&e.exec("UPDATE server_state SET schema_version = 2 WHERE id = 1"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<4&&(e.exec(`
372
372
  CREATE TABLE IF NOT EXISTS roles (
373
373
  id TEXT PRIMARY KEY,
374
374
  name TEXT NOT NULL UNIQUE,
@@ -566,7 +566,7 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
566
566
  bound_at INTEGER NOT NULL,
567
567
  PRIMARY KEY (role_id, plugin_id)
568
568
  );
569
- `),e.exec("UPDATE server_state SET schema_version = 10 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<11){try{e.exec("ALTER TABLE task_templates RENAME COLUMN skill_preference TO role_preference")}catch(E){let s=e.prepare("PRAGMA table_info(task_templates)").all(),T=s.some(i=>i.name==="role_preference"),t=s.some(i=>i.name==="skill_preference");if(!T&&t)throw E}e.exec("UPDATE server_state SET schema_version = 11 WHERE id = 1")}if(o<12&&(e.prepare("PRAGMA table_info(server_state)").all().some(s=>s.name==="tools_fingerprint")||e.exec("ALTER TABLE server_state ADD COLUMN tools_fingerprint TEXT"),e.exec("UPDATE server_state SET schema_version = 12 WHERE id = 1")),o<13&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="additional_directories")||e.exec("ALTER TABLE roles ADD COLUMN additional_directories TEXT"),e.exec("UPDATE server_state SET schema_version = 13 WHERE id = 1")),o<14){let E=e.prepare("PRAGMA table_info(roles)").all();E.some(t=>t.name==="allowed_channels")||e.exec("ALTER TABLE roles ADD COLUMN allowed_channels TEXT"),E.some(t=>t.name==="mcp_servers")||e.exec("ALTER TABLE roles ADD COLUMN mcp_servers TEXT");let s=e.prepare("PRAGMA table_info(tasks)").all();s.some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),s.some(t=>t.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(goals)").all().some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE goals ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 14 WHERE id = 1")}if(o<15&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="inherit_user_settings")||e.exec("ALTER TABLE roles ADD COLUMN inherit_user_settings INTEGER DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 15 WHERE id = 1")),o<16&&(e.prepare("PRAGMA table_info(task_templates)").all().some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE task_templates ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 16 WHERE id = 1")),o<17){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS plugins"),e.exec("DROP TABLE IF EXISTS role_plugins"),e.exec("DROP TABLE IF EXISTS marketplaces"),e.exec("DROP INDEX IF EXISTS idx_plugins_source"),e.exec("DROP INDEX IF EXISTS idx_plugins_enabled");try{let T=e.prepare("SELECT id, additional_directories FROM roles WHERE additional_directories IS NOT NULL").all();for(let t of T)try{let i=JSON.parse(t.additional_directories);if(i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"path"in i[0])continue;let N=i.map(n=>typeof n=="string"?{path:n}:n);e.prepare("UPDATE roles SET additional_directories = ? WHERE id = ?").run(JSON.stringify(N),t.id)}catch{}}catch{}let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 17 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(o<18){let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 18 WHERE id = 1")}e.prepare("PRAGMA table_info(delivery_log)").all().some(E=>E.name==="source")||(e.exec(`
569
+ `),e.exec("UPDATE server_state SET schema_version = 10 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(_<11){try{e.exec("ALTER TABLE task_templates RENAME COLUMN skill_preference TO role_preference")}catch(E){let s=e.prepare("PRAGMA table_info(task_templates)").all(),T=s.some(i=>i.name==="role_preference"),t=s.some(i=>i.name==="skill_preference");if(!T&&t)throw E}e.exec("UPDATE server_state SET schema_version = 11 WHERE id = 1")}if(_<12&&(e.prepare("PRAGMA table_info(server_state)").all().some(s=>s.name==="tools_fingerprint")||e.exec("ALTER TABLE server_state ADD COLUMN tools_fingerprint TEXT"),e.exec("UPDATE server_state SET schema_version = 12 WHERE id = 1")),_<13&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="additional_directories")||e.exec("ALTER TABLE roles ADD COLUMN additional_directories TEXT"),e.exec("UPDATE server_state SET schema_version = 13 WHERE id = 1")),_<14){let E=e.prepare("PRAGMA table_info(roles)").all();E.some(t=>t.name==="allowed_channels")||e.exec("ALTER TABLE roles ADD COLUMN allowed_channels TEXT"),E.some(t=>t.name==="mcp_servers")||e.exec("ALTER TABLE roles ADD COLUMN mcp_servers TEXT");let s=e.prepare("PRAGMA table_info(tasks)").all();s.some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),s.some(t=>t.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(goals)").all().some(t=>t.name==="deliver_to")||e.exec("ALTER TABLE goals ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 14 WHERE id = 1")}if(_<15&&(e.prepare("PRAGMA table_info(roles)").all().some(s=>s.name==="inherit_user_settings")||e.exec("ALTER TABLE roles ADD COLUMN inherit_user_settings INTEGER DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 15 WHERE id = 1")),_<16&&(e.prepare("PRAGMA table_info(task_templates)").all().some(s=>s.name==="deliver_to")||e.exec("ALTER TABLE task_templates ADD COLUMN deliver_to TEXT"),e.exec("UPDATE server_state SET schema_version = 16 WHERE id = 1")),_<17){e.exec("PRAGMA foreign_keys = OFF"),e.exec("DROP TABLE IF EXISTS plugins"),e.exec("DROP TABLE IF EXISTS role_plugins"),e.exec("DROP TABLE IF EXISTS marketplaces"),e.exec("DROP INDEX IF EXISTS idx_plugins_source"),e.exec("DROP INDEX IF EXISTS idx_plugins_enabled");try{let T=e.prepare("SELECT id, additional_directories FROM roles WHERE additional_directories IS NOT NULL").all();for(let t of T)try{let i=JSON.parse(t.additional_directories);if(i.length>0&&typeof i[0]=="object"&&i[0]!==null&&"path"in i[0])continue;let N=i.map(n=>typeof n=="string"?{path:n}:n);e.prepare("UPDATE roles SET additional_directories = ? WHERE id = ?").run(JSON.stringify(N),t.id)}catch{}}catch{}let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 17 WHERE id = 1"),e.exec("PRAGMA foreign_keys = ON")}if(_<18){let E=e.prepare("PRAGMA table_info(tasks)").all();E.some(T=>T.name==="deliver_to")||e.exec("ALTER TABLE tasks ADD COLUMN deliver_to TEXT"),E.some(T=>T.name==="report_to")||e.exec("ALTER TABLE tasks ADD COLUMN report_to TEXT");let s=e.prepare("PRAGMA table_info(strategies)").all();s.some(T=>T.name==="role")&&!s.some(T=>T.name==="role_id")&&(e.exec("ALTER TABLE strategies RENAME COLUMN role TO role_id"),e.exec("DROP INDEX IF EXISTS idx_strategies_role_task_type"),e.exec("DROP INDEX IF EXISTS idx_strategies_role"),e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_strategies_role_task_type ON strategies(role_id, task_type, name)"),e.exec("CREATE INDEX IF NOT EXISTS idx_strategies_role ON strategies(role_id)")),e.exec("UPDATE server_state SET schema_version = 18 WHERE id = 1")}e.prepare("PRAGMA table_info(delivery_log)").all().some(E=>E.name==="source")||(e.exec(`
570
570
  CREATE TABLE IF NOT EXISTS delivery_log_new (
571
571
  id TEXT PRIMARY KEY,
572
572
  rule_id TEXT REFERENCES delivery_rules(id),
@@ -583,4 +583,53 @@ import{e as A,h as O}from"./chunk-WBAPIPST.js";import{c as R,h as X}from"./chunk
583
583
  message_type TEXT
584
584
  )
585
585
  `),e.exec(`INSERT INTO delivery_log_new (id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at)
586
- SELECT id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at FROM delivery_log`),e.exec("DROP TABLE delivery_log"),e.exec("ALTER TABLE delivery_log_new RENAME TO delivery_log"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_rule ON delivery_log(rule_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_task ON delivery_log(task_id)")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<20&&(e.prepare("PRAGMA table_info(goals)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE goals ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(task_templates)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE task_templates ADD COLUMN report_to TEXT"),e.exec("UPDATE goals SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE task_templates SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE server_state SET schema_version = 20 WHERE id = 1")),e.prepare("PRAGMA table_info(config)").all().some(E=>E.name==="updated_at")||(e.exec("ALTER TABLE config ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 21 WHERE id = 1"));let c=e.prepare("PRAGMA table_info(memories)").all();c.some(E=>E.name==="tier")||(e.exec("ALTER TABLE memories ADD COLUMN tier TEXT NOT NULL DEFAULT 'episodic'"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)")),c.some(E=>E.name==="superseded_by")||(e.exec("ALTER TABLE memories ADD COLUMN superseded_by TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_superseded ON memories(superseded_by)"));let L=e.prepare("PRAGMA table_info(memories)").all();L.some(E=>E.name==="tier")&&L.some(E=>E.name==="superseded_by")&&(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<22&&e.exec("UPDATE server_state SET schema_version = 22 WHERE id = 1");{let E=e.prepare("PRAGMA table_info(roles)").all();E.some(T=>T.name==="permission_mode")||e.exec("ALTER TABLE roles ADD COLUMN permission_mode TEXT DEFAULT NULL"),E.some(T=>T.name==="allowed_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN allowed_bash_patterns TEXT DEFAULT NULL"),E.some(T=>T.name==="denied_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN denied_bash_patterns TEXT DEFAULT NULL"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<23&&e.exec("UPDATE server_state SET schema_version = 23 WHERE id = 1")}e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="env_vars")||e.prepare("ALTER TABLE roles ADD COLUMN env_vars TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<24&&e.prepare("UPDATE server_state SET schema_version = 24 WHERE id = 1").run();{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let n of t){let a=!1;for(let[d,r]of E)if(d.test(n)){i.push(...r),a=!0,I.info({from:n,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}a||(/[.+?^${}()|[\]\\]/.test(n)&&I.warn({pattern:n},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(n))}let N=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(N),Date.now(),T.key)}catch{}}}function K(){if(_)return _;let e=process.env.ADAM_DB_PATH||A,l=u(e);return S(l)||g(l,{recursive:!0}),_=new p(e),_.pragma("journal_mode = WAL"),_.pragma("foreign_keys = ON"),_.pragma("trusted_schema = ON"),D(_),_}function W(){_&&(_.close(),_=null)}var I,_,C=m(()=>{O();X();I=R("store"),_=null});export{D as a,K as b,W as c,C as d};
586
+ SELECT id, rule_id, task_id, status, target, content, attempts, error, created_at, delivered_at, expires_at FROM delivery_log`),e.exec("DROP TABLE delivery_log"),e.exec("ALTER TABLE delivery_log_new RENAME TO delivery_log"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_rule ON delivery_log(rule_id)"),e.exec("CREATE INDEX IF NOT EXISTS idx_delivery_log_task ON delivery_log(task_id)")),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<20&&(e.prepare("PRAGMA table_info(goals)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE goals ADD COLUMN report_to TEXT"),e.prepare("PRAGMA table_info(task_templates)").all().some(T=>T.name==="report_to")||e.exec("ALTER TABLE task_templates ADD COLUMN report_to TEXT"),e.exec("UPDATE goals SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE task_templates SET report_to = notify_targets WHERE notify_targets IS NOT NULL"),e.exec("UPDATE server_state SET schema_version = 20 WHERE id = 1")),e.prepare("PRAGMA table_info(config)").all().some(E=>E.name==="updated_at")||(e.exec("ALTER TABLE config ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0"),e.exec("UPDATE server_state SET schema_version = 21 WHERE id = 1"));let c=e.prepare("PRAGMA table_info(memories)").all();c.some(E=>E.name==="tier")||(e.exec("ALTER TABLE memories ADD COLUMN tier TEXT NOT NULL DEFAULT 'episodic'"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)")),c.some(E=>E.name==="superseded_by")||(e.exec("ALTER TABLE memories ADD COLUMN superseded_by TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_memories_superseded ON memories(superseded_by)"));let L=e.prepare("PRAGMA table_info(memories)").all();L.some(E=>E.name==="tier")&&L.some(E=>E.name==="superseded_by")&&(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<22&&e.exec("UPDATE server_state SET schema_version = 22 WHERE id = 1");{let E=e.prepare("PRAGMA table_info(roles)").all();E.some(T=>T.name==="permission_mode")||e.exec("ALTER TABLE roles ADD COLUMN permission_mode TEXT DEFAULT NULL"),E.some(T=>T.name==="allowed_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN allowed_bash_patterns TEXT DEFAULT NULL"),E.some(T=>T.name==="denied_bash_patterns")||e.exec("ALTER TABLE roles ADD COLUMN denied_bash_patterns TEXT DEFAULT NULL"),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<23&&e.exec("UPDATE server_state SET schema_version = 23 WHERE id = 1")}if(e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="env_vars")||e.prepare("ALTER TABLE roles ADD COLUMN env_vars TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<24&&e.prepare("UPDATE server_state SET schema_version = 24 WHERE id = 1").run(),_<25&&(e.exec(`
587
+ CREATE TABLE IF NOT EXISTS workflow_executions (
588
+ id TEXT PRIMARY KEY,
589
+ template_id TEXT NOT NULL,
590
+ status TEXT NOT NULL DEFAULT 'running',
591
+ step_statuses TEXT NOT NULL DEFAULT '{}',
592
+ started_at INTEGER NOT NULL,
593
+ completed_at INTEGER,
594
+ error TEXT,
595
+ FOREIGN KEY (template_id) REFERENCES task_templates(id)
596
+ )
597
+ `),e.exec("UPDATE server_state SET schema_version = 25 WHERE id = 1")),_<26){let E=`
598
+ CREATE TABLE IF NOT EXISTS workflow_artifacts (
599
+ id TEXT PRIMARY KEY,
600
+ execution_id TEXT NOT NULL,
601
+ step_id TEXT NOT NULL,
602
+ key TEXT NOT NULL,
603
+ kind TEXT NOT NULL CHECK(kind IN ('json', 'file')),
604
+ value_json TEXT,
605
+ blob_path TEXT,
606
+ mime TEXT,
607
+ size_bytes INTEGER NOT NULL,
608
+ created_at INTEGER NOT NULL,
609
+ UNIQUE(execution_id, step_id, key),
610
+ FOREIGN KEY (execution_id) REFERENCES workflow_executions(id) ON DELETE CASCADE
611
+ );
612
+ CREATE INDEX IF NOT EXISTS idx_workflow_artifacts_execution
613
+ ON workflow_artifacts (execution_id);
614
+ CREATE INDEX IF NOT EXISTS idx_workflow_artifacts_step
615
+ ON workflow_artifacts (execution_id, step_id);
616
+ `,s=`
617
+ CREATE TABLE IF NOT EXISTS artifact_access_log (
618
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
619
+ timestamp INTEGER NOT NULL,
620
+ task_id TEXT,
621
+ role_id TEXT,
622
+ execution_id TEXT NOT NULL,
623
+ step_id TEXT,
624
+ tool TEXT NOT NULL,
625
+ artifact_key TEXT,
626
+ artifact_id TEXT,
627
+ size_bytes INTEGER,
628
+ outcome TEXT NOT NULL CHECK(outcome IN ('success', 'denied', 'error')),
629
+ error_reason TEXT
630
+ );
631
+ CREATE INDEX IF NOT EXISTS idx_artifact_access_log_execution
632
+ ON artifact_access_log (execution_id, timestamp);
633
+ CREATE INDEX IF NOT EXISTS idx_artifact_access_log_role
634
+ ON artifact_access_log (role_id, timestamp);
635
+ `;e.exec(E),e.exec(s),e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="step_id")||e.prepare("ALTER TABLE tasks ADD COLUMN step_id TEXT").run(),e.exec("UPDATE server_state SET schema_version = 26 WHERE id = 1")}{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let n of t){let a=!1;for(let[d,r]of E)if(d.test(n)){i.push(...r),a=!0,I.info({from:n,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}a||(/[.+?^${}()|[\]\\]/.test(n)&&I.warn({pattern:n},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(n))}let N=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(N),Date.now(),T.key)}catch{}}}function K(){if(o)return o;let e=process.env.ADAM_DB_PATH||A,l=g(e);return S(l)||u(l,{recursive:!0}),o=new p(e),o.pragma("journal_mode = WAL"),o.pragma("foreign_keys = ON"),o.pragma("trusted_schema = ON"),C(o),o}function W(){o&&(o.close(),o=null)}var I,o,D=m(()=>{X();O();I=R("store"),o=null});export{C as a,K as b,W as c,D as d};
@@ -1,4 +1,4 @@
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.
1
+ import{f as s,j as w}from"./chunk-7IXLL673.js";import{d as i,e as f,h as g,k as y}from"./chunk-OTH4M5L3.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.
@@ -1,4 +1,4 @@
1
- import{e as I,j as G}from"./chunk-KLQOILIJ.js";import{a as J}from"./chunk-GUQAIWCQ.js";import{a as j}from"./chunk-2CMR5AG7.js";import{a as E,b as S,c as D,j as T}from"./chunk-4TCP2AT7.js";import{b as P,d as B}from"./chunk-KVSO3KGZ.js";import{c as W,e as q}from"./chunk-FCV2DPZQ.js";var Q={};q(Q,{getGlobalEnabledState:()=>w,getInstalledPlugin:()=>z,getPluginManifest:()=>_,listInstalledPlugins:()=>A,listMarketplaceSources:()=>V,resolvePluginPaths:()=>M,scanDirectoryConfig:()=>x});import{existsSync as y,readFileSync as k,readdirSync as C}from"fs";import{join as p}from"path";import L from"os";function h(t){try{if(!y(t))return null;let e=k(t,"utf-8");return JSON.parse(e)}catch{return null}}function w(){return h(Y())?.enabledPlugins??{}}function _(t){let e=t;function s(n,r){let o={};try{if(!y(n))return o;let d=k(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let m of r){let i=new RegExp(`^${m}:\\s*(.+)$`,"m"),a=d.match(i);a&&(o[m]=a[1].trim())}}catch{}return o}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},r=p(e,".claude-plugin","plugin.json");if(y(r))try{let i=JSON.parse(k(r,"utf-8"));n.name=i.name??"",n.version=i.version,n.description=i.description,Array.isArray(i.lspServers)&&(n.lspServers=i.lspServers),Array.isArray(i.mcpServers)&&(n.mcpServers=i.mcpServers),Array.isArray(i.hooks)&&(n.hooks=i.hooks)}catch{}let o=p(e,"skills");if(y(o)){let i=C(o,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()&&!a.isSymbolicLink())continue;let u=p(o,a.name,"SKILL.md"),f=s(u,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let l=p(e,"agents");if(y(l)){let i=C(l,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(".md"))continue;let u=s(p(l,a.name),["name","description"]);u.name&&n.agents.push({name:u.name,description:u.description??""})}}let d=p(e,".mcp.json");if(y(d))try{let i=JSON.parse(k(d,"utf-8"));i.mcpServers&&typeof i.mcpServers=="object"&&(n.mcpServers=Object.keys(i.mcpServers))}catch{}let m=p(e,"hooks","hooks.json");if(y(m))try{let i=JSON.parse(k(m,"utf-8"));Array.isArray(i)&&(n.hooks=i.map(a=>typeof a=="object"&&a!==null&&"event"in a?String(a.event):String(a)))}catch{}return n}catch{return null}}function A(t){let e=h(R());if(!e?.plugins)return[];let s=w(),n=[];for(let[r,o]of Object.entries(e.plugins))if(!(!Array.isArray(o)||o.length===0))for(let l of o){let d=l.scope??"user";t?.scope&&d!==t.scope||t?.projectPath&&l.projectPath!==t.projectPath||n.push({id:r,name:r.split("@")[0],version:l.version??"",scope:d,projectPath:l.projectPath,installPath:l.installPath??p(v(),r),enabled:s[r]??l.enabled??!0,installedAt:l.installedAt??"",lastUpdated:l.lastUpdated??""})}return n}function z(t){let e=h(R());if(!e?.plugins?.[t])return null;let s=e.plugins[t];if(!Array.isArray(s)||s.length===0)return null;let n=s[0],r=w();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??p(v(),t),enabled:r[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function M(t){let e=h(R()),s=new Map;for(let n of t){let r=e?.plugins?.[n];Array.isArray(r)&&r.length>0&&s.set(n,r[0].installPath??p(v(),n))}return s}function V(){return h(H())?.marketplaces??[]}function x(t){let e=p(t,".claude","settings.json"),s=h(e);return{enabledPlugins:s?.enabledPlugins??{},mcpServers:s?.mcpServers??{},allowedTools:s?.allowedTools??[],disallowedTools:s?.disallowedTools??[]}}var v,R,H,Y,O=W(()=>{"use strict";v=()=>p(L.homedir(),".claude","plugins"),R=()=>p(v(),"installed_plugins.json"),H=()=>p(v(),"known_marketplaces.json"),Y=()=>p(L.homedir(),".claude","settings.json")});import{tool as b}from"@anthropic-ai/claude-agent-sdk";import{z as c}from"zod";import{v4 as X}from"uuid";function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Z={query:c.string().describe("Search query for memory retrieval"),roleId:c.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:c.number().optional().describe("Max results to return (default 5)")},ee={query:c.string().describe("Search query for memory retrieval"),topK:c.number().optional().describe("Max results to return (default 5)")},te={id:c.string().optional().describe("Memory ID to update. Omit to create new."),roleId:c.string().describe("Role ID to save memory under"),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ne={id:c.string().optional().describe("Memory ID to update. Omit to create new."),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:c.string().describe("Memory ID to delete")};async function F(t,e){let s=t??e.roleId,n=e.topK??5,r=await J(s,e.query,{topK:n});return g({results:r.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function $(t,e){let s=t??e.roleId;if(!s)return g({error:"roleId is required"});let n,r=!0;try{n=await j(e.content)}catch{r=!1}if(e.id){if(!S(e.id))return g({error:`Memory ${e.id} not found`});let m=D(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return g({id:e.id,action:"updated",success:m,embeddingUpdated:r})}let o=`mem-${X().slice(0,8)}`,l=Date.now();return E({id:o,roleId:s,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:l,lastAccessed:l,retrievedCount:0,tier:e.tier??"episodic"}),g({id:o,action:"created",success:!0,embeddingUpdated:r})}async function K(t,e){if(t){let s=S(e.id);if(!s)return g({error:`Memory ${e.id} not found`});if(s.roleId!==t)return g({error:`Memory ${e.id} does not belong to this role`})}return T(e.id),g({id:e.id,deleted:!0})}function ye(t){return t?[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ee,async e=>F(t,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ne,async e=>$(t,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Z,async e=>F(void 0,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",te,async e=>$(void 0,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}O();G();var re={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ve(t,e){let s=t.allowedTools??[];if(s.length===0)return"No tool permissions";let n=new Map,r=[];for(let i of s){let a=re[i];if(a){let u=n.get(a.category)??[];u.push(a.label),n.set(a.category,u)}else r.push(i)}let o=[];for(let[i,a]of n)o.push(`${i} (${a.join(", ")})`);r.length>0&&o.push(r.join(", "));let l=o.join(" \xB7 "),d=Object.keys(t.mcpServers??{});d.length>0&&(l+=` \xB7 MCP: ${d.join(", ")}`);let m=t.additionalDirectories??[];if(m.length>0&&(l+=` \xB7 Dirs: ${m.map(i=>i.path).join(", ")}`),e&&e.plugins.length>0){let i=e.plugins.map(a=>{let u=[];return a.skills.length>0&&u.push(`skills: ${a.skills.map(f=>f.name).join(", ")}`),a.agents.length>0&&u.push(`agents: ${a.agents.map(f=>f.name).join(", ")}`),u.length>0?`${a.name} (${u.join("; ")})`:a.name});l+=` \xB7 Plugins: ${i.join(", ")}`}return l}function oe(t){let e=[],s=t.additionalDirectories??[];for(let n of s){if(!n.inheritPlugins&&!n.inheritMcp)continue;let r=x(n.path),o=Object.entries(r.enabledPlugins).filter(([,d])=>d).map(([d])=>d),l=M(o);for(let[,d]of l)e.includes(d)||e.push(d)}try{let n=I(t.name),r=A({scope:"project",projectPath:n});for(let o of r)o.installPath&&!e.includes(o.installPath)&&e.push(o.installPath)}catch{}return e}function Pe(t){let e=oe(t),s=[];for(let n of e){let r=_(n);r&&s.push({name:r.name||n.split("/").pop()||"unknown",description:r.description,skills:r.skills,agents:r.agents,mcpServers:r.mcpServers,hooks:r.hooks})}return{plugins:s}}B();function se(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var U={low:1,medium:2,high:3};function we(t){P().prepare(`
1
+ import{e as I,j as G}from"./chunk-7IXLL673.js";import{a as J}from"./chunk-P6KWAGAY.js";import{a as j}from"./chunk-2CMR5AG7.js";import{a as E,b as S,c as D,j as T}from"./chunk-IZGTTLTG.js";import{b as P,d as B}from"./chunk-4MJF77RD.js";import{c as W,e as q}from"./chunk-FCV2DPZQ.js";var Q={};q(Q,{getGlobalEnabledState:()=>w,getInstalledPlugin:()=>z,getPluginManifest:()=>_,listInstalledPlugins:()=>A,listMarketplaceSources:()=>V,resolvePluginPaths:()=>M,scanDirectoryConfig:()=>x});import{existsSync as y,readFileSync as k,readdirSync as C}from"fs";import{join as p}from"path";import L from"os";function h(t){try{if(!y(t))return null;let e=k(t,"utf-8");return JSON.parse(e)}catch{return null}}function w(){return h(Y())?.enabledPlugins??{}}function _(t){let e=t;function s(n,r){let o={};try{if(!y(n))return o;let d=k(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let m of r){let i=new RegExp(`^${m}:\\s*(.+)$`,"m"),a=d.match(i);a&&(o[m]=a[1].trim())}}catch{}return o}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},r=p(e,".claude-plugin","plugin.json");if(y(r))try{let i=JSON.parse(k(r,"utf-8"));n.name=i.name??"",n.version=i.version,n.description=i.description,Array.isArray(i.lspServers)&&(n.lspServers=i.lspServers),Array.isArray(i.mcpServers)&&(n.mcpServers=i.mcpServers),Array.isArray(i.hooks)&&(n.hooks=i.hooks)}catch{}let o=p(e,"skills");if(y(o)){let i=C(o,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()&&!a.isSymbolicLink())continue;let u=p(o,a.name,"SKILL.md"),f=s(u,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let l=p(e,"agents");if(y(l)){let i=C(l,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(".md"))continue;let u=s(p(l,a.name),["name","description"]);u.name&&n.agents.push({name:u.name,description:u.description??""})}}let d=p(e,".mcp.json");if(y(d))try{let i=JSON.parse(k(d,"utf-8"));i.mcpServers&&typeof i.mcpServers=="object"&&(n.mcpServers=Object.keys(i.mcpServers))}catch{}let m=p(e,"hooks","hooks.json");if(y(m))try{let i=JSON.parse(k(m,"utf-8"));Array.isArray(i)&&(n.hooks=i.map(a=>typeof a=="object"&&a!==null&&"event"in a?String(a.event):String(a)))}catch{}return n}catch{return null}}function A(t){let e=h(R());if(!e?.plugins)return[];let s=w(),n=[];for(let[r,o]of Object.entries(e.plugins))if(!(!Array.isArray(o)||o.length===0))for(let l of o){let d=l.scope??"user";t?.scope&&d!==t.scope||t?.projectPath&&l.projectPath!==t.projectPath||n.push({id:r,name:r.split("@")[0],version:l.version??"",scope:d,projectPath:l.projectPath,installPath:l.installPath??p(v(),r),enabled:s[r]??l.enabled??!0,installedAt:l.installedAt??"",lastUpdated:l.lastUpdated??""})}return n}function z(t){let e=h(R());if(!e?.plugins?.[t])return null;let s=e.plugins[t];if(!Array.isArray(s)||s.length===0)return null;let n=s[0],r=w();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??p(v(),t),enabled:r[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function M(t){let e=h(R()),s=new Map;for(let n of t){let r=e?.plugins?.[n];Array.isArray(r)&&r.length>0&&s.set(n,r[0].installPath??p(v(),n))}return s}function V(){return h(H())?.marketplaces??[]}function x(t){let e=p(t,".claude","settings.json"),s=h(e);return{enabledPlugins:s?.enabledPlugins??{},mcpServers:s?.mcpServers??{},allowedTools:s?.allowedTools??[],disallowedTools:s?.disallowedTools??[]}}var v,R,H,Y,O=W(()=>{"use strict";v=()=>p(L.homedir(),".claude","plugins"),R=()=>p(v(),"installed_plugins.json"),H=()=>p(v(),"known_marketplaces.json"),Y=()=>p(L.homedir(),".claude","settings.json")});import{tool as b}from"@anthropic-ai/claude-agent-sdk";import{z as c}from"zod";import{v4 as X}from"uuid";function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Z={query:c.string().describe("Search query for memory retrieval"),roleId:c.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:c.number().optional().describe("Max results to return (default 5)")},ee={query:c.string().describe("Search query for memory retrieval"),topK:c.number().optional().describe("Max results to return (default 5)")},te={id:c.string().optional().describe("Memory ID to update. Omit to create new."),roleId:c.string().describe("Role ID to save memory under"),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ne={id:c.string().optional().describe("Memory ID to update. Omit to create new."),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:c.string().describe("Memory ID to delete")};async function F(t,e){let s=t??e.roleId,n=e.topK??5,r=await J(s,e.query,{topK:n});return g({results:r.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function $(t,e){let s=t??e.roleId;if(!s)return g({error:"roleId is required"});let n,r=!0;try{n=await j(e.content)}catch{r=!1}if(e.id){if(!S(e.id))return g({error:`Memory ${e.id} not found`});let m=D(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return g({id:e.id,action:"updated",success:m,embeddingUpdated:r})}let o=`mem-${X().slice(0,8)}`,l=Date.now();return E({id:o,roleId:s,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:l,lastAccessed:l,retrievedCount:0,tier:e.tier??"episodic"}),g({id:o,action:"created",success:!0,embeddingUpdated:r})}async function K(t,e){if(t){let s=S(e.id);if(!s)return g({error:`Memory ${e.id} not found`});if(s.roleId!==t)return g({error:`Memory ${e.id} does not belong to this role`})}return T(e.id),g({id:e.id,deleted:!0})}function ye(t){return t?[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ee,async e=>F(t,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ne,async e=>$(t,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Z,async e=>F(void 0,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",te,async e=>$(void 0,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}O();G();var re={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ve(t,e){let s=t.allowedTools??[];if(s.length===0)return"No tool permissions";let n=new Map,r=[];for(let i of s){let a=re[i];if(a){let u=n.get(a.category)??[];u.push(a.label),n.set(a.category,u)}else r.push(i)}let o=[];for(let[i,a]of n)o.push(`${i} (${a.join(", ")})`);r.length>0&&o.push(r.join(", "));let l=o.join(" \xB7 "),d=Object.keys(t.mcpServers??{});d.length>0&&(l+=` \xB7 MCP: ${d.join(", ")}`);let m=t.additionalDirectories??[];if(m.length>0&&(l+=` \xB7 Dirs: ${m.map(i=>i.path).join(", ")}`),e&&e.plugins.length>0){let i=e.plugins.map(a=>{let u=[];return a.skills.length>0&&u.push(`skills: ${a.skills.map(f=>f.name).join(", ")}`),a.agents.length>0&&u.push(`agents: ${a.agents.map(f=>f.name).join(", ")}`),u.length>0?`${a.name} (${u.join("; ")})`:a.name});l+=` \xB7 Plugins: ${i.join(", ")}`}return l}function oe(t){let e=[],s=t.additionalDirectories??[];for(let n of s){if(!n.inheritPlugins&&!n.inheritMcp)continue;let r=x(n.path),o=Object.entries(r.enabledPlugins).filter(([,d])=>d).map(([d])=>d),l=M(o);for(let[,d]of l)e.includes(d)||e.push(d)}try{let n=I(t.name),r=A({scope:"project",projectPath:n});for(let o of r)o.installPath&&!e.includes(o.installPath)&&e.push(o.installPath)}catch{}return e}function Pe(t){let e=oe(t),s=[];for(let n of e){let r=_(n);r&&s.push({name:r.name||n.split("/").pop()||"unknown",description:r.description,skills:r.skills,agents:r.agents,mcpServers:r.mcpServers,hooks:r.hooks})}return{plugins:s}}B();function se(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var U={low:1,medium:2,high:3};function we(t){P().prepare(`
2
2
  INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
3
3
  VALUES (?, ?, ?, ?, ?, ?)
4
4
  `).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function _e(t,e,s){let r=P().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let o of r)if(!(o.role_id&&o.role_id!==t)&&!(U[s]>U[o.max_risk_level]))try{if(new RegExp(o.task_pattern,"i").test(e))return se(o)}catch{}}export{we as a,_e as b,w as c,_ as d,A as e,z as f,V as g,x as h,Q as i,O as j,ye as k,ve as l,oe as m,Pe as n};