adam-agent-server 1.4.0 → 1.6.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 (131) hide show
  1. package/dist/App-WJMHK5EO.js +13 -0
  2. package/dist/adam-automator-skills-UFW5TXCC.js +18 -0
  3. package/dist/adam-tools-IAZSLWYB.js +1 -0
  4. package/dist/approval-handler-HQO62WK2.js +1 -0
  5. package/dist/audit-manager-LC5EQXCI.js +1 -0
  6. package/dist/bree-engine-M5CZ6A62.js +1 -0
  7. package/dist/channels-5TFYQN5Z.js +1 -0
  8. package/dist/{channels-PUOPR5Y2.js → channels-J4STJ4X2.js} +1 -1
  9. package/dist/{chunk-L4Y3GR6W.js → chunk-2H7UOW4P.js} +1 -1
  10. package/dist/chunk-3LY6PD6A.js +1 -0
  11. package/dist/{chunk-RUY23IJK.js → chunk-4C5ITATX.js} +1 -1
  12. package/dist/{chunk-NZEDILAK.js → chunk-52PR7XTN.js} +1 -1
  13. package/dist/chunk-5OQZPUBV.js +79 -0
  14. package/dist/{chunk-6THDALGC.js → chunk-7446ZS6D.js} +1 -1
  15. package/dist/{chunk-J3NIPZ73.js → chunk-7ZGSJCX5.js} +2 -2
  16. package/dist/{chunk-24GTCFEV.js → chunk-DBP7GPWG.js} +2 -2
  17. package/dist/chunk-DWRYIN5N.js +12 -0
  18. package/dist/chunk-FIN36WAP.js +99 -0
  19. package/dist/{chunk-GYHOPV4Q.js → chunk-FXQAUQTI.js} +1 -1
  20. package/dist/{chunk-KOWFPY2J.js → chunk-FZCNYKNT.js} +1 -1
  21. package/dist/{chunk-QQWRV23T.js → chunk-G5ESQEXN.js} +1 -1
  22. package/dist/chunk-GGIHDFRW.js +6 -0
  23. package/dist/{chunk-I5IUTZA3.js → chunk-GMMWA5EG.js} +1 -1
  24. package/dist/chunk-HWLSHTVX.js +27 -0
  25. package/dist/{chunk-XAMLLKKA.js → chunk-I7ZZKPHE.js} +1 -1
  26. package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
  27. package/dist/chunk-MDBVKBC7.js +47 -0
  28. package/dist/chunk-MJSSCKMB.js +23 -0
  29. package/dist/{chunk-INNDBLZE.js → chunk-MRTJFYPR.js} +1 -1
  30. package/dist/{chunk-YHVFZB6Q.js → chunk-N4ES7TCL.js} +1 -1
  31. package/dist/{chunk-4VHBKJD5.js → chunk-NCFVJCNQ.js} +26 -7
  32. package/dist/{chunk-3567PCEJ.js → chunk-P5ZXNBNV.js} +2 -2
  33. package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
  34. package/dist/{chunk-EZGMA3VV.js → chunk-RLJYEEQC.js} +1 -1
  35. package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
  36. package/dist/{chunk-YHH3QMLL.js → chunk-TNL2LZB7.js} +1 -1
  37. package/dist/{chunk-HYDCXE5K.js → chunk-TSPQ44HT.js} +1 -1
  38. package/dist/{chunk-JKPSEMUZ.js → chunk-V32YF3J5.js} +1 -1
  39. package/dist/{chunk-CKIVKM5T.js → chunk-VVSZZK5T.js} +2 -2
  40. package/dist/{chunk-XF4IERYF.js → chunk-WAG3MNMC.js} +5 -5
  41. package/dist/{chunk-VRP4LTHY.js → chunk-YDVTWPNA.js} +1 -1
  42. package/dist/{chunk-7BSWC62F.js → chunk-YHVYX3F4.js} +1 -1
  43. package/dist/{chunk-KO5AFX5U.js → chunk-YXYIA24D.js} +1 -1
  44. package/dist/chunk-ZL5JXLAX.js +49 -0
  45. package/dist/cli.js +2 -2
  46. package/dist/{config-CBNOT66B.js → config-KFPS7IEH.js} +1 -1
  47. package/dist/config-ZBNGRASI.js +1 -0
  48. package/dist/db-PZ2V7UCK.js +1 -0
  49. package/dist/delivery-log-ACNJ66RD.js +1 -0
  50. package/dist/engine-5DHYHDAP.js +1 -0
  51. package/dist/{evolution-audit-JZ2U7J4C.js → evolution-audit-OQDGPKYI.js} +1 -1
  52. package/dist/{external-api-7XV2PXPC.js → external-api-V74YTLBY.js} +1 -1
  53. package/dist/index.js +24 -15
  54. package/dist/learner-QCD6BH2J.js +1 -0
  55. package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
  56. package/dist/{memories-EKREXLT6.js → memories-QGMRSBJJ.js} +1 -1
  57. package/dist/{memory-extractor-JO7OHBZP.js → memory-extractor-3MRK43A2.js} +2 -2
  58. package/dist/memory-service-M5ADGITG.js +1 -0
  59. package/dist/outbound-gateway-QRL36F7K.js +1 -0
  60. package/dist/role-presets-DLO3XS54.js +1 -0
  61. package/dist/role-workspace-URSOBCDH.js +1 -0
  62. package/dist/roles-KYXNMO5H.js +1 -0
  63. package/dist/session-manager-LZ77OT7A.js +1 -0
  64. package/dist/task-templates-YPNWJOVV.js +1 -0
  65. package/dist/workflow-executor-3WMS2WV3.js +1 -0
  66. package/package.json +1 -1
  67. package/web/dist/assets/{AlertDialog-r3y6IhpW.js → AlertDialog-CfeiyMrc.js} +1 -1
  68. package/web/dist/assets/{Button-BjXgrQ95.js → Button-DuQctNms.js} +1 -1
  69. package/web/dist/assets/{Card-C153tGfJ.js → Card-rKfViPS2.js} +1 -1
  70. package/web/dist/assets/{ChannelDetail-C2uAZv1u.js → ChannelDetail-DHT8fW0C.js} +1 -1
  71. package/web/dist/assets/{Channels-C62Qrg-n.js → Channels-YHGNXcRu.js} +2 -2
  72. package/web/dist/assets/{Chat-kH2owmB_.js → Chat-Dv_Izjx3.js} +1 -1
  73. package/web/dist/assets/{Dashboard-BhD8SpFb.js → Dashboard-DsHC5W4C.js} +1 -1
  74. package/web/dist/assets/{EmptyState-CXwJFCDQ.js → EmptyState-CIdIlMbn.js} +1 -1
  75. package/web/dist/assets/{EnvVarEditor-GSapLD96.js → EnvVarEditor-Dxy1Kz1Z.js} +1 -1
  76. package/web/dist/assets/EventDefDetail-CwprP2ch.js +1 -0
  77. package/web/dist/assets/Events-B19a8cEG.js +1 -0
  78. package/web/dist/assets/{Evolution-BO5hysLD.js → Evolution-DT6iZvil.js} +1 -1
  79. package/web/dist/assets/{GoalDetail-cxa8OvEi.js → GoalDetail-BALsnPQl.js} +1 -1
  80. package/web/dist/assets/{Goals-Dz3qqp_l.js → Goals-BJIsKgfH.js} +1 -1
  81. package/web/dist/assets/{Logs-Ckp3-hYV.js → Logs-Cv15aV3l.js} +1 -1
  82. package/web/dist/assets/{Memories-DEuSRoP3.js → Memories-CKAXhAso.js} +1 -1
  83. package/web/dist/assets/{NotFound-Bvn39vSk.js → NotFound-DitXhq_y.js} +1 -1
  84. package/web/dist/assets/{PageHeader-BMvN0xiB.js → PageHeader-CHSgtxPw.js} +1 -1
  85. package/web/dist/assets/Plugins-NO0S2spH.js +1 -0
  86. package/web/dist/assets/{RoleDetail-BWMjP9aZ.js → RoleDetail-1FNyCD4u.js} +2 -2
  87. package/web/dist/assets/{Roles-DD7NBDku.js → Roles-grfjw2zy.js} +1 -1
  88. package/web/dist/assets/{SectionHeader-CiCj3Is0.js → SectionHeader-C2WpiwJ5.js} +1 -1
  89. package/web/dist/assets/{Settings-BlU19KuR.js → Settings-9LRLfa_4.js} +1 -1
  90. package/web/dist/assets/{Strategies-CJ_q94-v.js → Strategies-BMyd_7_5.js} +1 -1
  91. package/web/dist/assets/{Switch-CoUUy5jr.js → Switch-CULsD-kC.js} +1 -1
  92. package/web/dist/assets/{Table-CaFJieh_.js → Table-DuOLbyJQ.js} +1 -1
  93. package/web/dist/assets/{TaskDetail-DVrjU-E6.js → TaskDetail-C2yXy8gE.js} +2 -2
  94. package/web/dist/assets/Work-dftf35Me.js +1 -0
  95. package/web/dist/assets/index-D4IubNPI.css +2 -0
  96. package/web/dist/assets/index-qYKJGoIB.js +2 -0
  97. package/web/dist/assets/{useIsMobileLayout-Bwrm84kJ.js → useIsMobileLayout-C6KIQjuh.js} +1 -1
  98. package/web/dist/assets/{vendor-icons-BlMaTTx3.js → vendor-icons-Dk0hMuJz.js} +1 -1
  99. package/web/dist/assets/{vendor-react-7e01TWy7.js → vendor-react-C6faO6LO.js} +1 -1
  100. package/web/dist/assets/{vendor-state-Bj70wnRm.js → vendor-state-DahK0J-G.js} +1 -1
  101. package/web/dist/index.html +7 -7
  102. package/dist/App-JGH6G5US.js +0 -13
  103. package/dist/adam-tools-KTLBI4PA.js +0 -1
  104. package/dist/approval-handler-JZSXM4AD.js +0 -1
  105. package/dist/audit-manager-BPJEAX22.js +0 -1
  106. package/dist/bree-engine-CRK73AI4.js +0 -1
  107. package/dist/channels-WMTZJAO4.js +0 -1
  108. package/dist/chunk-DBI36EGR.js +0 -83
  109. package/dist/chunk-DMZM7RU6.js +0 -19
  110. package/dist/chunk-HQ66TFYI.js +0 -12
  111. package/dist/chunk-I67UMGJM.js +0 -10
  112. package/dist/chunk-NOUSHXGX.js +0 -6
  113. package/dist/chunk-T7GEINGZ.js +0 -6
  114. package/dist/chunk-WRETNOC3.js +0 -99
  115. package/dist/chunk-ZRUVORAJ.js +0 -49
  116. package/dist/config-XMQS2NPT.js +0 -1
  117. package/dist/db-XQUI4IBL.js +0 -1
  118. package/dist/delivery-log-T56ZYDWO.js +0 -1
  119. package/dist/engine-7DFJOADQ.js +0 -1
  120. package/dist/learner-4EO7ZKK4.js +0 -1
  121. package/dist/memory-service-Y3HVQYHM.js +0 -1
  122. package/dist/outbound-gateway-U5LP54JG.js +0 -1
  123. package/dist/role-presets-HWZHXBBA.js +0 -1
  124. package/dist/roles-3AEHVOEW.js +0 -1
  125. package/dist/session-manager-PWJLU6KZ.js +0 -1
  126. package/dist/task-templates-ED2UCUPE.js +0 -1
  127. package/dist/workflow-executor-XFTTJQNE.js +0 -1
  128. package/web/dist/assets/Plugins-CRym22JF.js +0 -1
  129. package/web/dist/assets/Work-BMl61RRi.js +0 -1
  130. package/web/dist/assets/index-DcXMQByM.css +0 -2
  131. package/web/dist/assets/index-pF--tN9F.js +0 -2
@@ -1,13 +0,0 @@
1
- import{b,d as Qt,e as Go}from"./chunk-VRP4LTHY.js";import{a as Xt,f as Uo,h as Wo}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as Ht,Text as Mt,useInput as Hs}from"ink";import{useState as js,useEffect as mo,useRef as No}from"react";import{createContext as on,useContext as rn,useReducer as nn}from"react";import{jsx as ln}from"react/jsx-runtime";var sn={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 an(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 Ho=on(null);function jo({children:e}){let[t,o]=nn(an,sn);return ln(Ho.Provider,{value:{state:t,dispatch:o},children:e})}function He(){let e=rn(Ho);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Ko,useRef as zo}from"react";var cn=15e3;function Xo(){let{state:e,dispatch:t}=He(),o=zo(null),u=zo(null);Ko(()=>{u.current=e.session?.id??null},[e.session?.id]),Ko(()=>{let m=!0,g=null,a=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{a(),o.current=setTimeout(()=>{m&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},cn)};return(()=>{try{g=new Qt("/events"),g.on("task_status_change",()=>{}),g.on("approval_request",r=>{if(!m)return;let d=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:d.taskId,approvalId:d.approvalId,toolName:d.toolName,toolInput:d.toolInput,matchedPattern:d.matchedPattern}})}),g.on("plan_approval_request",r=>{if(!m)return;let d=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:d.taskId,planId:d.planId,roleId:d.roleId,plan:d.plan}})}),g.on("plan_approval_decision",()=>{m&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),g.on("config_changed",()=>{m&&t({type:"CONFIG_CHANGED"})}),g.on("execution_task_start",r=>{if(!m)return;let d=r,f=u.current;f&&(async()=>{try{let S=await b(`/tasks/${d.taskId}`);m&&S.sourceSessionId===f&&t({type:"SET_ACTIVE_TASK",taskId:d.taskId})}catch{}})()}),g.on("stats_update",r=>{if(!m)return;let d=r;t({type:"UPDATE_STATS",activeTasks:d.activeTasks,queuedTasks:d.queuedTasks,costToday:d.totalCostToday})}),g.connect().then(async()=>{if(m){a(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await b("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{m&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{m&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{m=!1,a(),g?.close()}},[t])}import{useEffect as dn,useRef as un,useState as Qo,useCallback as mn}from"react";function Yo(e){let[t,o]=Qo([]),[u,m]=Qo(!1),g=un(null),a=mn(()=>{o([]),m(!1)},[]);return dn(()=>{if(!e)return;let i=!0;o([]),m(!0);try{let s=new Go(e);return g.current=s,s.on("reasoning",r=>{if(!i)return;let f=r.content??"";o(S=>{let h=S[S.length-1];if(h?.type==="reasoning"){let C=[...S];return C[C.length-1]={...h,content:h.content+f},C}return[...S,{type:"reasoning",content:f,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"tool_call",content:d.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:d.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"tool_result",content:d.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"error",content:d.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"complete",content:d.result??"",timestamp:Date.now(),metadata:{cost:d.costUsd,turns:d.numTurns,duration:d.totalDurationMs}}]),m(!1)}),s.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),m(!1))}),()=>{i=!1,s.close()}}catch{m(!1)}},[e]),{events:t,isStreaming:u,clearEvents:a}}import{useState as xo,useEffect as gn,useCallback as Lt}from"react";function To(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function Zo(){let[e,t]=xo(null),[o,u]=xo(!0),[m,g]=xo(null),a=Lt(async()=>{try{let S=(await b("/chat/sessions?status=active")).sessions.find(h=>h.source.type==="tui");return S?To(S):null}catch{return null}},[]),i=Lt(async()=>{try{let f=await b("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),S=To(f.session);return t(S),S}catch{return g("Failed to create session"),null}},[]),s=Lt(async f=>{try{let S=await b("/chat/messages",{method:"POST",body:{content:f,source:{type:"tui"}}});return t(h=>h&&{...h,messageCount:h.messageCount+1,lastActiveAt:Date.now()}),S}catch{return null}},[]),r=Lt(async()=>{if(!e)return!1;try{return await b(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),d=Lt(async()=>{if(e)try{let f=await b(`/chat/sessions/${e.id}`);t(To(f.session))}catch{t(null)}},[e]);return gn(()=>{let f=!1;async function S(){u(!0);let h=await a();f||(h?t(h):await i(),f||u(!1))}return S(),()=>{f=!0}},[]),{session:e,loading:o,error:m,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:d,setSession:t}}import{useEffect as Jo,useRef as fn,useState as pn}from"react";function er(e){let[t,o]=pn(null),u=fn(new Set);return Jo(()=>{if(!e)return;let m=!0,g=null;try{g=new Qt("/chat/stream"),g.on("chat_message",a=>{if(!m)return;let s=a.message;s&&s.sessionId===e&&s.role==="assistant"&&(u.current.has(s.id)||(u.current.add(s.id),o(s)))}),g.connect().catch(()=>{})}catch{}return()=>{m=!1,g?.close()}},[e]),Jo(()=>{u.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as ho,Text as Ae}from"ink";import{Fragment as Yt,jsx as xe,jsxs as Ct}from"react/jsx-runtime";var xn=90;function tr({children:e}){return xe(ho,{children:e})}function or(){let{state:e}=He(),t=e.session,u=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,m=e.connected?"up":"down",g=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),a=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,s=(process.stdout.columns??100)<xn,r=Ct(Yt,{children:[xe(Ae,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),xe(Ae,{children:` ${m}`}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:g.toLowerCase()})]}),d=Ct(Yt,{children:[xe(Ae,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&Ct(Yt,{children:[xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:a}),u&&Ct(Yt,{children:[xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{color:"yellow",children:"timeout"})]})]})]});return s?Ct(ho,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[xe(tr,{children:r}),xe(tr,{children:d})]}):Ct(ho,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[r,xe(Ae,{dimColor:!0,children:" | "}),d]})}import{Box as Zt,Text as Jt,useInput as hn}from"ink";import{useState as bo,useMemo as yn}from"react";import bn from"ink-text-input";var Tn=[{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 yo(e){let t=e.toLowerCase();return Tn.filter(o=>o.name.startsWith(t))}function rr(e){let t=yo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as eo,jsxs as _t}from"react/jsx-runtime";function nr({onSubmit:e}){let[t,o]=bo(""),[u,m]=bo(0),[g,a]=bo(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=yn(()=>i?yo(s):[],[i,s]),d=h=>{o(h),h.startsWith("/")?(a(!0),m(0)):a(!1)},f=()=>{let h=t.trim();if(h){if(h.startsWith("/")){let C=h.slice(1),n=rr(C);e(n?`/${n.name}`:h)}else e(h);o(""),a(!1)}},S=h=>{e(`/${h.name}`),o(""),a(!1)};return hn((h,C)=>{if(!(!g||!i||r.length===0)){if(C.upArrow){m(n=>n<=0?r.length-1:n-1);return}if(C.downArrow){m(n=>n>=r.length-1?0:n+1);return}if(C.tab){let n=r[u];n&&S(n);return}if(C.escape){a(!1),o("");return}}},{isActive:g&&i&&r.length>0}),_t(Zt,{flexDirection:"column",children:[g&&i&&r.length>0&&eo(Zt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((h,C)=>{let n=C===u;return _t(Zt,{children:[eo(Jt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),_t(Jt,{color:n?"cyan":"white",bold:n,children:["/",h.name]}),_t(Jt,{dimColor:!0,children:[" \u2014 ",h.description]})]},h.name)})}),_t(Zt,{borderStyle:"round",borderDimColor:!0,children:[eo(Jt,{bold:!0,children:"\u25B8 "}),eo(bn,{value:t,onChange:d,onSubmit:f,placeholder:"Type a message or / for commands..."})]})]})}import{Box as St,Text as Se,useInput as vn}from"ink";import{useState as Cn}from"react";import{jsx as $e,jsxs as je}from"react/jsx-runtime";function Sn({content:e,expanded:t}){let o=e.split(`
2
- `);return o.length<=5?$e(Se,{color:"green",children:e}):t?$e(Se,{color:"green",children:e}):je(Se,{color:"green",children:[o.slice(0,3).join(`
3
- `),`
4
- `,je(Se,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function wn({event:e,expanded:t}){switch(e.type){case"reasoning":return $e(St,{children:$e(Se,{color:"gray",children:e.content})});case"tool_call":return $e(St,{children:je(Se,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return je(St,{flexDirection:"column",children:[$e(Se,{color:"blue",dimColor:!0,children:"[result]"}),$e(Sn,{content:e.content,expanded:t})]});case"error":return $e(St,{children:je(Se,{color:"red",children:["[error] ",e.content]})});case"complete":return je(St,{flexDirection:"column",marginTop:1,children:[e.content&&$e(Se,{children:e.content}),$e(Se,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&je(Se,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&je(Se,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&je(Se,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function sr({events:e,isStreaming:t}){let[o,u]=Cn(!1),m=e.some(g=>g.type==="tool_result"&&g.content.split(`
5
- `).length>5);return vn((g,a)=>{a.ctrl&&g==="o"&&u(i=>!i)},{isActive:m}),e.length===0&&!t?null:je(St,{flexDirection:"column",children:[t&&e.length===0&&$e(Se,{dimColor:!0,children:"Waiting for response..."}),e.map((g,a)=>$e(wn,{event:g,expanded:o},a)),m&&$e(Se,{dimColor:!0,children:o?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as ir,Text as ar}from"ink";import{jsx as vo,jsxs as Bn}from"react/jsx-runtime";function lr({messages:e}){return e.length===0?null:vo(ir,{flexDirection:"column",children:e.map((t,o)=>Bn(ir,{flexDirection:"column",marginBottom:1,children:[vo(ar,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),vo(ar,{children:t.content})]},o))})}import{Box as Ot,Text as Ke,useInput as En}from"ink";import{jsx as ze,jsxs as Vt}from"react/jsx-runtime";function cr({approval:e,onResolved:t}){return En(o=>{o==="a"?b(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&b(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Vt(Ot,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[ze(Ke,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Vt(Ot,{marginTop:1,children:[ze(Ke,{children:"Tool: "}),ze(Ke,{bold:!0,children:e.toolName})]}),Vt(Ot,{children:[ze(Ke,{children:"Input: "}),ze(Ke,{children:JSON.stringify(e.toolInput)})]}),Vt(Ot,{children:[ze(Ke,{children:"Pattern: "}),ze(Ke,{dimColor:!0,children:e.matchedPattern})]}),Vt(Ot,{marginTop:1,children:[ze(Ke,{color:"green",children:"[a] Approve"}),ze(Ke,{children:" "}),ze(Ke,{color:"red",children:"[r] Reject"})]})]})}import{Box as qt,Text as we,useInput as kn}from"ink";import{useState as In,useEffect as An}from"react";import{jsx as ot,jsxs as Fe}from"react/jsx-runtime";var Pn=300;function dr({approval:e,onResolved:t,onTimeout:o}){let[u,m]=In(Pn);An(()=>{let a=setInterval(()=>{m(i=>i<=1?(clearInterval(a),o(),0):i-1)},1e3);return()=>clearInterval(a)},[o]),kn(a=>{a==="a"?b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):a==="r"?b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):a==="p"&&b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let g=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Fe(qt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ot(we,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Fe(we,{dimColor:!0,children:["Plan ID: ",e.planId]}),Fe(we,{dimColor:!0,children:["Time remaining: ",u,"s"]}),Fe(qt,{marginTop:1,children:[ot(we,{children:"Overall Risk: "}),ot(we,{bold:!0,color:g,children:e.plan.overallRisk.toUpperCase()})]}),Fe(we,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(a=>{let i=a.riskLevel==="high"?"red":a.riskLevel==="medium"?"yellow":"green";return Fe(qt,{paddingLeft:2,children:[Fe(we,{children:["[",a.index,"] "]}),ot(we,{children:a.description}),Fe(we,{dimColor:!0,children:[" (",a.toolsNeeded.join(", "),")"]}),Fe(we,{color:i,children:[" [",a.riskLevel,"]"]})]},a.index)}),Fe(qt,{marginTop:1,children:[ot(we,{dimColor:!0,children:"Permissions: "}),ot(we,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Fe(qt,{marginTop:1,children:[ot(we,{color:"green",children:"[a] Allow once "}),ot(we,{color:"green",children:"[p] Allow permanent "}),ot(we,{color:"red",children:"[r] Deny"})]})]})}import{Box as Te,Text as j,useInput as Vn}from"ink";import{useEffect as qn,useState as ct,useCallback as xr}from"react";import{Box as fe,Text as F,useInput as Dn}from"ink";import{useEffect as Rn,useState as wt}from"react";import{jsx as ie,jsxs as W}from"react/jsx-runtime";var ur={plan:!0,result:!1,routing:!0,error:!0},Mn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"};function pr({taskId:e,onBack:t}){let[o,u]=wt(null),[m,g]=wt([]),[a,i]=wt([]),[s,r]=wt(null),[d,f]=wt(ur),[S,h]=wt(!1);Rn(()=>{let E=!1;return u(null),g([]),i([]),r(null),f(ur),h(!1),b(`/tasks/${e}`).then(({task:k})=>{E||u(k)}).catch(k=>{E||r(k instanceof Error?k.message:String(k))}),b(`/tasks/${e}/plan`).then(({plans:k})=>{E||g(k)}).catch(()=>{E||g([])}),b(`/tasks/${e}/delivery-log?limit=8`).then(({logs:k})=>{E||i(k)}).catch(()=>{E||i([])}),()=>{E=!0}},[e]);let C=E=>{f(k=>({...k,[E]:!k[E]}))};if(Dn((E,k)=>{if(E==="b"||k.escape){t();return}E==="1"&&C("plan"),E==="2"&&C("result"),E==="3"&&C("routing"),E==="4"&&C("error"),E==="5"&&h(H=>!H)}),s)return W(fe,{flexDirection:"column",children:[W(F,{color:"red",children:["Task detail failed: ",s]}),ie(F,{dimColor:!0,children:"[b] Back"})]});if(!o)return W(F,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let n=m[0],T=_n(o.deliverTo,o.reportTo),_=a.length>0?`${a.length} delivery event${a.length===1?"":"s"}`:"No delivery events";return W(fe,{flexDirection:"column",children:[W(fe,{children:[W(F,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ie(F,{dimColor:!0,children:" \u2022 "}),ie(F,{color:Mn[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),W(F,{dimColor:!0,children:[o.roleId?`role ${o.roleId}`:"no role"," \u2022 ",fr(o.createdAt)," \u2022 ",Ln(o.totalDurationMs)]}),W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{bold:!0,children:"Summary"}),ie(F,{children:S?o.prompt:Nn(o.prompt,240)}),o.prompt.length>240&&W(F,{dimColor:!0,children:["[5] ",S?"collapse prompt":"expand prompt"]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{dimColor:!0,children:["Cost: ",$n(o.costUsd)]}),W(F,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),W(F,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),W(F,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[1] Plan ",d.plan?"hide":"show"]}),ie(F,{dimColor:!0,children:n?`${n.plan.steps.length} planned step${n.plan.steps.length===1?"":"s"} \u2022 ${n.plan.overallRisk} risk \u2022 ${n.status}`:"No execution plan"}),d.plan&&n&&W(fe,{marginTop:1,flexDirection:"column",children:[n.plan.steps.map(E=>W(fe,{flexDirection:"column",marginBottom:1,children:[W(F,{children:[E.index,". ",E.description]}),W(F,{dimColor:!0,children:[E.riskLevel," risk \u2022 ",E.toolsNeeded.join(", ")||"no tools listed"]}),E.expectedOutput?W(F,{dimColor:!0,children:["Expected: ",E.expectedOutput]}):null]},E.index)),n.learnedRules&&n.learnedRules.length>0&&W(fe,{flexDirection:"column",children:[ie(F,{color:"blue",bold:!0,children:"Learned Rules"}),n.learnedRules.map((E,k)=>W(F,{dimColor:!0,children:["\u2022 ",E]},k))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[2] Result ",d.result?"hide":"show"]}),ie(F,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),d.result&&ie(fe,{marginTop:1,children:ie(F,{children:o.result?gr(o.result,18):"No result yet."})})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[3] Routing ",d.routing?"hide":"show"]}),W(F,{dimColor:!0,children:[T," \u2022 ",_]}),d.routing&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Deliver To"}),mr(o.deliverTo),ie(F,{color:"cyan",children:"Report To"}),mr(o.reportTo),a.length>0&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Recent Delivery"}),a.map(E=>W(F,{dimColor:!0,children:[E.status," \u2022 ",On(E)," \u2022 ",fr(E.createdAt)]},E.id))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[4] Error ",d.error?"hide":"show"]}),ie(F,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),d.error&&o.error&&ie(fe,{marginTop:1,children:ie(F,{color:"red",children:gr(o.error,16)})})]}),ie(fe,{marginTop:1,children:ie(F,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function mr(e){return!e||e.length===0?ie(F,{dimColor:!0,children:" none"}):ie(fe,{flexDirection:"column",children:e.map((t,o)=>ie(F,{dimColor:!0,children:t.type==="channel"?` channel ${t.channelId.slice(0,8)}${t.chatId?` / ${t.chatId.slice(0,8)}`:""}`:` session ${t.sessionId.slice(0,8)}`},`${t.type}-${o}`))})}function gr(e,t){let o=e.split(`
6
- `);return o.length<=t?e:`${o.slice(0,t).join(`
7
- `)}
8
- \u2026`}function Nn(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function $n(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Ln(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let o=Math.floor(t/60),u=t%60;return u===0?`${o}m`:`${o}m ${u}s`}function fr(e){return new Date(e).toLocaleString()}function _n(e,t){let o=e?.length??0,u=t?.length??0;return o===0&&u===0?"No delivery targets":`${o} output target${o===1?"":"s"} \u2022 ${u} report target${u===1?"":"s"}`}function On(e){return e.target.type==="webhook"?e.target.webhookUrl??"webhook":e.target.type==="channel"?`channel ${e.target.channelId?.slice(0,8)??"unknown"}`:"unknown target"}import{Fragment as Un,jsx as ee,jsxs as oe}from"react/jsx-runtime";var Tr={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},to=["all","pending","queued","running","completed","failed","cancelled"],Co=15;function ro({onBack:e}){let[t,o]=ct([]),[u,m]=ct(!0),[g,a]=ct("list"),[i,s]=ct(0),[r,d]=ct("all"),[f,S]=ct(0),[h,C]=ct(0),[n,T]=ct(null),_=xr(async()=>{m(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let O=await b(`/tasks?${I}`);o(O.tasks)}catch{o([])}finally{m(!1)}},[r]);qn(()=>{_()},[_]);let E=Math.max(1,Math.ceil(t.length/Co)),k=t.slice(h*Co,(h+1)*Co),H=xr(async()=>{let I=k[i];if(I)try{await b(`/tasks/${I.id}/cancel`,{method:"POST"}),T(`Cancelled: ${I.id.slice(0,8)}`),a("list"),_()}catch(O){T(`Failed: ${O instanceof Error?O.message:String(O)}`),a("list")}},[k,i,_]);if(Vn((I,O)=>{if(g==="detail"){(O.escape||O.return||I==="q")&&a("list");return}if(g==="cancelling"){I==="y"?H():a("list");return}if(g==="filter"){if(O.escape){a("list");return}O.upArrow&&f>0&&S(R=>R-1),O.downArrow&&f<to.length-1&&S(R=>R+1),O.return&&(d(to[f]),C(0),s(0),a("list"));return}if(O.escape||I==="q"){e();return}if(O.upArrow&&i>0&&s(R=>R-1),O.downArrow&&i<k.length-1&&s(R=>R+1),O.return&&k[i]&&a("detail"),I==="x"&&k[i]){let R=k[i];["running","pending","queued","paused"].includes(R.status)?(a("cancelling"),T(null)):T(`Cannot cancel task in status: ${R.status}`)}I==="f"&&(S(to.indexOf(r)),a("filter")),I==="r"&&_(),(O.pageDown||I==="n")&&h<E-1&&(C(R=>R+1),s(0)),(O.pageUp||I==="p")&&h>0&&(C(R=>R-1),s(0))}),u)return ee(j,{dimColor:!0,children:"Loading tasks..."});if(g==="filter")return oe(Te,{flexDirection:"column",children:[ee(j,{bold:!0,children:"Filter by status:"}),to.map((I,O)=>ee(Te,{children:oe(j,{color:O===f?"cyan":"white",children:[O===f?"> ":" ",I,I===r?" (current)":""]})},I)),ee(j,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(g==="detail"&&k[i])return ee(pr,{taskId:k[i].id,onBack:()=>a("list")});if(g==="cancelling"&&k[i])return oe(Te,{flexDirection:"column",children:[oe(j,{color:"red",children:['Cancel task "',k[i].id.slice(0,8),'"? (y/n)']}),n&&ee(j,{color:"red",children:n})]});let Q=k[i]??null;return oe(Te,{flexDirection:"column",children:[oe(Te,{children:[oe(j,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&oe(j,{dimColor:!0,children:[" [filter: ",r,"]"]}),oe(j,{dimColor:!0,children:[" \u2022 Page ",h+1,"/",E]})]}),n&&ee(j,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?oe(j,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):oe(Te,{marginTop:1,flexDirection:"row",gap:2,children:[ee(Te,{flexDirection:"column",flexGrow:3,children:k.map((I,O)=>{let R=O===i,D=Tr[I.status]??"white";return oe(Te,{flexDirection:"column",marginBottom:1,children:[oe(Te,{children:[ee(j,{color:R?"cyan":"gray",bold:R,children:R?"\u276F ":" "}),ee(j,{color:D,bold:!0,children:I.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${I.id.slice(0,8)}`})]}),ee(Te,{paddingLeft:2,children:ee(j,{color:R?"white":void 0,children:oo(I.prompt,R?72:56)})}),ee(Te,{paddingLeft:2,children:oe(j,{dimColor:!0,children:[br(I.createdAt)," \u2022 ",hr(I)," \u2022 ",yr(I.costUsd)]})})]},I.id)})}),ee(Te,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Q?oe(Un,{children:[ee(j,{bold:!0,children:"Preview"}),oe(Te,{marginTop:1,children:[ee(j,{color:Tr[Q.status]??"white",bold:!0,children:Q.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${Q.id.slice(0,8)}`})]}),ee(j,{children:oo(Q.prompt,220)}),oe(Te,{marginTop:1,flexDirection:"column",children:[oe(j,{dimColor:!0,children:["Role: ",Q.roleId??Q.agentId??"\u2014"]}),oe(j,{dimColor:!0,children:["Created: ",br(Q.createdAt)]}),oe(j,{dimColor:!0,children:["Duration: ",hr(Q)]}),oe(j,{dimColor:!0,children:["Cost: ",yr(Q.costUsd)]}),oe(j,{dimColor:!0,children:["Turns: ",Q.numTurns??"\u2014"]})]}),Q.error?oe(Te,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"red",bold:!0,children:"Error"}),ee(j,{color:"red",children:oo(Q.error,180)})]}):Q.result?oe(Te,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"green",bold:!0,children:"Latest Result"}),ee(j,{children:oo(Q.result,180)})]}):null,ee(Te,{marginTop:1,children:ee(j,{dimColor:!0,children:"Enter opens full detail"})})]}):ee(j,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Fn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function oo(e,t){return Fn(e.replace(/\s+/g," ").trim(),t)}function hr(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let o=Math.max(1,Math.round(t/1e3));if(o<60)return`${o}s`;let u=Math.floor(o/60),m=o%60;return m===0?`${u}m`:`${u}m ${m}s`}function yr(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function br(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let o=Math.floor(t/60);if(o<60)return`${o}m ago`;let u=Math.floor(o/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}Wo();import{Box as ft,Text as Pe,useInput as Wn}from"ink";import{useEffect as Gn,useState as vr}from"react";import{readFileSync as Hn,existsSync as jn}from"fs";import{parse as Kn}from"yaml";import{Fragment as Xn,jsx as Be,jsxs as Le}from"react/jsx-runtime";function Cr({onBack:e}){let[t,o]=vr(null),[u,m]=vr(null);return Wn((g,a)=>{(a.escape||g==="q")&&e()}),Gn(()=>{try{let g=Uo;if(!jn(g)){m(`Config file not found: ${g}`);return}let a=Hn(g,"utf-8");o(Kn(a))}catch(g){m(g.message)}},[]),u?Le(ft,{flexDirection:"column",children:[Be(Pe,{color:"red",children:u}),Be(Pe,{dimColor:!0,children:"Press Esc to go back"})]}):t?Le(ft,{flexDirection:"column",children:[Be(Pe,{bold:!0,children:"Configuration (Esc to go back)"}),Be(ft,{marginTop:1,flexDirection:"column",children:Be(So,{obj:t,indent:0})})]}):Be(Pe,{dimColor:!0,children:"Loading config..."})}function So({obj:e,indent:t}){let o=" ".repeat(t);return Be(Xn,{children:Object.entries(e).map(([u,m])=>Be(zn,{label:u,value:m,indent:t,parentKey:u},u))})}function zn({label:e,value:t,indent:o,parentKey:u}){let m=" ".repeat(o);return Array.isArray(t)?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),":"]}),t.length===0?Le(Pe,{dimColor:!0,children:[m," []"]}):t.map((g,a)=>Be(Sr,{value:g,indent:o+1,parentKey:u,index:a},`${e}-${a}`))]}):t&&typeof t=="object"?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),":"]}),Be(So,{obj:t,indent:o+1})]}):Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),": ",wr(u,Br(t))]})}function Sr({value:e,indent:t,parentKey:o,index:u}){let m=" ".repeat(t);return Array.isArray(e)?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,"- [",u,"]"]}),e.map((g,a)=>Be(Sr,{value:g,indent:t+1,parentKey:o,index:a},`${u}-${a}`))]}):e&&typeof e=="object"?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,"-"]}),Be(So,{obj:e,indent:t+1})]}):Le(Pe,{children:[m,"- ",wr(o,Br(e))]})}function wr(e,t){let o=e.toLowerCase();return o.includes("key")||o.includes("token")||o.includes("secret")||o.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function Br(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as no,Text as Ue,useInput as Qn}from"ink";import{useEffect as Yn,useState as wo}from"react";import{jsx as Ft,jsxs as Xe}from"react/jsx-runtime";function Er({onBack:e}){let[t,o]=wo([]),[u,m]=wo(!0),[g,a]=wo(null);return Qn((i,s)=>{(s.escape||i==="q")&&e()}),Yn(()=>{b("/evolution-audit?limit=20").then(i=>{o(i),m(!1)}).catch(i=>{a(i.message),m(!1)})},[]),u?Ft(Ue,{dimColor:!0,children:"Loading evolution log..."}):g?Xe(no,{flexDirection:"column",children:[Ft(Ue,{color:"red",children:g}),Ft(Ue,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Xe(no,{flexDirection:"column",children:[Ft(Ue,{dimColor:!0,children:"No evolution records yet"}),Ft(Ue,{dimColor:!0,children:"Press Esc to go back"})]}):Xe(no,{flexDirection:"column",children:[Xe(Ue,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>Xe(no,{flexDirection:"column",marginTop:1,children:[Xe(Ue,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&Xe(Ue,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
9
- `).map((s,r)=>s.startsWith("+")?Xe(Ue,{color:"green",children:[" ",s]},r):s.startsWith("-")?Xe(Ue,{color:"red",children:[" ",s]},r):Xe(Ue,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as rt,Text as ae,useInput as Zn}from"ink";import Jn from"ink-text-input";import{useEffect as es,useState as Bt}from"react";import{jsx as De,jsxs as he}from"react/jsx-runtime";var ts={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function os(e,t=20){let o=Math.round(e*t),u=t-o;return"\u2588".repeat(o)+"\u2591".repeat(u)}function rs(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function so({onBack:e}){let[t,o]=Bt([]),[u,m]=Bt(null),[g,a]=Bt("list"),[i,s]=Bt(""),[r,d]=Bt(!1),[f,S]=Bt(null);Zn((n,T)=>{if(g==="create"){T.escape&&(a("list"),s(""),S(null));return}(T.escape||n==="q")&&e(),n==="c"&&(a("create"),S(null)),n==="r"&&h()});let h=()=>{b("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>m(n.message))};es(()=>{h()},[]);let C=async n=>{if(n.trim()){d(!0),S(null);try{let T=await b("/goals",{method:"POST",body:{input:n.trim()}});S(`Goal created: ${T.goal.name}`),s(""),a("list"),h()}catch(T){S(`Failed: ${T instanceof Error?T.message:String(T)}`)}finally{d(!1)}}};return u?he(rt,{flexDirection:"column",children:[he(ae,{color:"red",children:["Failed to load goals: ",u]}),De(ae,{dimColor:!0,children:"Press Esc or q to return"})]}):g==="create"?he(rt,{flexDirection:"column",children:[De(ae,{bold:!0,children:"Create Goal"}),De(ae,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),he(rt,{marginTop:1,children:[De(ae,{color:"cyan",children:"> "}),De(Jn,{value:i,onChange:s,onSubmit:C})]}),r&&De(ae,{color:"yellow",children:"Creating goal..."}),f&&De(ae,{color:f.startsWith("Failed")?"red":"green",children:f}),De(ae,{dimColor:!0,children:"Press Esc to cancel"})]}):he(rt,{flexDirection:"column",children:[he(ae,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?De(ae,{dimColor:!0,children:"No goals found. Press c to create one."}):De(rt,{marginTop:1,flexDirection:"column",children:t.map(n=>{let T=n.targetValue>0?n.currentValue/n.targetValue:0,_=ts[n.status]??"white";return he(rt,{marginBottom:1,flexDirection:"column",children:[he(rt,{children:[De(ae,{bold:!0,color:_,children:n.name}),he(ae,{dimColor:!0,children:[" (",n.role,")"]}),De(ae,{dimColor:!0,children:" \u2014 "}),De(ae,{color:_,children:n.status})]}),he(rt,{children:[he(ae,{dimColor:!0,children:[" ",os(T)," "]}),he(ae,{color:T>=1?"green":"white",children:[Math.round(T*100),"%"]}),he(ae,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),he(rt,{children:[he(ae,{dimColor:!0,children:[" \u23F0 ",rs(n.deadline)," left"]}),he(ae,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),he(ae,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),De(ae,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as Et,Text as Oe,useInput as ns}from"ink";import{useEffect as ss,useState as kr}from"react";import{jsx as st,jsxs as nt}from"react/jsx-runtime";function is(e,t,o=15){let u=e/(e+t),m=Math.round(u*o);return"\u2593".repeat(m)+"\u2591".repeat(o-m)}function Ir({onBack:e}){let[t,o]=kr([]),[u,m]=kr(null);if(ns((a,i)=>{(i.escape||a==="q")&&e()}),ss(()=>{b("/strategies?limit=50").then(a=>o(a.strategies??[])).catch(a=>m(a.message))},[]),u)return nt(Et,{flexDirection:"column",children:[nt(Oe,{color:"red",children:["Failed to load strategies: ",u]}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return nt(Et,{flexDirection:"column",children:[st(Oe,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]});let g=new Map;for(let a of t){let i=`${a.role}/${a.taskType}`,s=g.get(i)??[];s.push(a),g.set(i,s)}return nt(Et,{flexDirection:"column",children:[st(Oe,{bold:!0,children:"Strategy Lab"}),st(Oe,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),st(Et,{marginTop:1,flexDirection:"column",children:Array.from(g.entries()).map(([a,i])=>nt(Et,{marginBottom:1,flexDirection:"column",children:[st(Oe,{bold:!0,color:"cyan",children:a}),i.sort((s,r)=>{let d=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-d}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return nt(Et,{children:[st(Oe,{dimColor:!0,children:" "}),nt(Oe,{children:[is(s.alpha,s.beta)," "]}),nt(Oe,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),nt(Oe,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},a))}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as ve,Text as Y,useInput as us}from"ink";import Bo from"ink-text-input";import{useEffect as ms,useState as Qe,useCallback as kt}from"react";import{CronExpressionParser as gs}from"cron-parser";import{useState as as,useEffect as ls,useCallback as Ar,useRef as cs}from"react";var ds=3e3;function dt(){let[e,t]=as(null),o=cs(null),u=Ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),m=Ar((g,a)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:g,type:a}),a==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},ds))},[]);return ls(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:m,clearMessage:u}}import{jsx as te,jsxs as ne}from"react/jsx-runtime";var Eo=["manual","cron","event"],io={name:"",triggerType:"manual",cron:"",stepPrompt:""};function fs(e){try{return gs.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function ao({onBack:e}){let[t,o]=Qe([]),[u,m]=Qe(!0),[g,a]=Qe(0),[i,s]=Qe("list"),[r,d]=Qe({...io}),[f,S]=Qe("name"),[h,C]=Qe(null),{message:n,setMessage:T,clearMessage:_}=dt(),[E,k]=Qe(!1),[H,Q]=Qe(!1),[I,O]=Qe({}),R=kt(()=>{m(!0),b("/task-templates").then(({templates:v})=>{o(v),new Set(v.flatMap(M=>M.steps?.map(J=>J.roleId).filter(Boolean)??[])).size>0?b("/roles").then(({roles:M})=>{if(!Array.isArray(M)){O({});return}O(Object.fromEntries(M.map(J=>[J.id,J.name])))}).catch(()=>O({})):O({}),m(!1)}).catch(()=>m(!1))},[]);ms(()=>{R()},[R]);let D=i==="create"||i==="edit",Z=kt(async()=>{let v=t[g];if(!(!v||E)){k(!0),T(`Triggering ${v.name}...`,"loading");try{let $=await b(`/task-templates/${v.id}/run`,{method:"POST"});T(`Triggered: ${v.name} (${$.executionId})`,"success")}catch($){T(`Trigger failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{k(!1)}}},[t,g,E,T]),le=kt(async()=>{let v=t[g];if(!v||H)return;if(v.trigger?.type!=="cron"&&v.trigger?.type!=="event"){T("Toggle not applicable for manual triggers","error");return}let $=!v.enabled;Q(!0),T(`${v.name} \u2192 ${$?"enabling":"disabling"}...`,"loading");try{await b(`/task-templates/${v.id}`,{method:"PATCH",body:{enabled:$}}),o(M=>M.map(J=>J.id===v.id?{...J,enabled:$}:J)),T(`${v.name} ${$?"enabled":"disabled"}`,"success")}catch(M){T(`Toggle failed: ${M instanceof Error?M.message:String(M)}`,"error")}finally{Q(!1)}},[t,g,H,T]),Je=kt(async()=>{let v=t[g];if(v)try{await b(`/task-templates/${v.id}`,{method:"DELETE"}),T(`Deleted: ${v.name}`,"success"),R(),a($=>Math.max(0,Math.min($,t.length-2)))}catch($){T(`Delete failed: ${$ instanceof Error?$.message:String($)}`,"error")}},[t,g,R]),ht=kt(()=>{let v=t[g];v&&(C(v.id),d({name:v.name,triggerType:v.trigger?.type??"manual",cron:v.trigger?.cron??"",stepPrompt:v.steps?.[0]?.prompt??""}),S("name"),s("edit"))},[t,g]),Ne=kt(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 b("/task-templates",{method:"POST",body:v}),T(`Created: ${r.name}`,"success")):i==="edit"&&h&&(await b(`/task-templates/${h}`,{method:"PATCH",body:v}),T(`Updated: ${r.name}`,"success"))}catch($){T(`Save failed: ${$ instanceof Error?$.message:String($)}`,"error")}s("list"),d({...io}),C(null),R()},[r,i,h,R]);return us((v,$)=>{if(D){if($.escape){s("list"),d({...io}),C(null);return}if($.return){let M=["name","triggerType","cron","stepPrompt"],J=M.indexOf(f);if(J<M.length-1){let Ie=J+1;if(M[Ie]==="cron"&&r.triggerType!=="cron"&&Ie++,Ie<M.length){S(M[Ie]);return}}Ne();return}if($.tab&&f==="triggerType"){d(M=>{let J=Eo.indexOf(M.triggerType);return{...M,triggerType:Eo[(J+1)%Eo.length]}});return}return}if($.escape||v==="q"){e();return}if($.upArrow){a(M=>Math.max(0,M-1));return}if($.downArrow){a(M=>Math.min(t.length-1,M+1));return}if(v==="t"){Z();return}if(v==="d"){Je();return}if(v==="e"){ht();return}if(v==="c"){d({...io}),S("name"),s("create");return}if(v==="s"||v===" "){le();return}v==="r"&&(R(),_())}),u?te(Y,{dimColor:!0,children:"Loading templates..."}):D?ne(ve,{flexDirection:"column",children:[ne(Y,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),ne(ve,{marginTop:1,flexDirection:"column",children:[ne(ve,{children:[ne(Y,{bold:f==="name",color:f==="name"?"cyan":void 0,children:["Name:"," "]}),f==="name"?te(Bo,{value:r.name,onChange:v=>d($=>({...$,name:v})),placeholder:"template name"}):te(Y,{children:r.name||"(empty)"})]}),ne(ve,{children:[ne(Y,{bold:f==="triggerType",color:f==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),te(Y,{children:r.triggerType}),f==="triggerType"&&te(Y,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&ne(ve,{children:[ne(Y,{bold:f==="cron",color:f==="cron"?"cyan":void 0,children:["Cron:"," "]}),f==="cron"?te(Bo,{value:r.cron,onChange:v=>d($=>({...$,cron:v})),placeholder:"*/5 * * * *"}):te(Y,{children:r.cron||"(empty)"})]}),ne(ve,{children:[ne(Y,{bold:f==="stepPrompt",color:f==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),f==="stepPrompt"?te(Bo,{value:r.stepPrompt,onChange:v=>d($=>({...$,stepPrompt:v})),placeholder:"What should this template do?"}):te(Y,{children:r.stepPrompt||"(empty)"})]})]}),te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):ne(ve,{flexDirection:"column",children:[ne(Y,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&te(ve,{marginTop:1,children:ne(Y,{color:n.type==="success"?"green":n.type==="error"?"red":"gray",children:[n.type==="success"?"\u2713 ":n.type==="error"?"\u2717 ":"\u2192 ",n.text]})}),t.length===0?te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"No templates found. Press c to create one."})}):te(ve,{marginTop:1,flexDirection:"column",children:t.map((v,$)=>{let M=$===g,J=v.trigger?.type==="cron"&&v.trigger?.cron?fs(v.trigger.cron):"",Ie=new Set(v.steps?.filter(A=>A.roleId).map(A=>A.roleId)),N=v.steps?.length>1?`${v.steps.length} steps${Ie.size>0?` / ${Ie.size} roles`:""}`:`${v.steps?.length??0} step`;return ne(ve,{flexDirection:"column",children:[ne(ve,{children:[te(Y,{color:M?"cyan":void 0,bold:M,children:M?"> ":" "}),te(Y,{color:M?"cyan":void 0,bold:M,children:Ut(v.name,24)}),te(Y,{dimColor:!0,children:Ut(v.trigger?.type,10)}),v.trigger?.type!=="cron"&&v.trigger?.type!=="event"?te(Y,{dimColor:!0,children:Ut("\u2014",6)}):te(Y,{color:v.enabled?"green":"gray",children:Ut(v.enabled?"on":"off",6)}),te(Y,{dimColor:!0,children:Ut(N,18)}),J&&ne(Y,{dimColor:!0,children:["next: ",J]})]}),M&&v.steps?.length>1&&te(ve,{flexDirection:"column",marginLeft:4,marginTop:0,children:v.steps.map((A,G)=>ne(ve,{children:[ne(Y,{dimColor:!0,children:[" ",G+1,". "]}),te(Y,{dimColor:!0,children:A.id}),A.roleId&&ne(Y,{color:"yellow",children:[" @",I[A.roleId]??A.roleId]}),A.dependsOn&&A.dependsOn.length>0&&ne(Y,{dimColor:!0,children:[" (after: ",A.dependsOn.join(", "),")"]}),A.config&&ne(Y,{dimColor:!0,children:[" ","[",[A.config.timeout!==void 0?`timeout:${A.config.timeout}s`:"",A.config.maxTurns!==void 0?`turns:${A.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},A.id))})]},v.id)})}),te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Ut(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ut,Text as _e,useInput as ps}from"ink";import xs from"ink-text-input";import{useEffect as Ts,useState as It,useCallback as Pr}from"react";import{jsx as Ee,jsxs as pt}from"react/jsx-runtime";function Dr({onBack:e}){let[t,o]=It([]),[u,m]=It(""),[g,a]=It(!0),[i,s]=It(!1),[r,d]=It(""),[f,S]=It(null),h=Pr(()=>{a(!0),b("/webhooks").then(({webhooks:n,auth:T})=>{o(n),m(T),a(!1)}).catch(()=>a(!1))},[]);Ts(()=>{h()},[h]);let C=Pr(async n=>{if(n.trim())try{let T=await b(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});S(`Triggered: ${T.executionId}`)}catch(T){S(`Trigger failed: ${T instanceof Error?T.message:String(T)}`)}},[]);return ps((n,T)=>{if(i){if(T.escape){s(!1),d("");return}if(T.return){C(r),s(!1),d("");return}return}if(T.escape||n==="q"){e();return}if(n==="t"){s(!0),d(""),S(null);return}n==="r"&&(h(),S(null))}),g?Ee(_e,{dimColor:!0,children:"Loading webhooks..."}):pt(ut,{flexDirection:"column",children:[pt(_e,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),pt(_e,{dimColor:!0,children:["Auth: ",u]}),f&&Ee(ut,{marginTop:1,children:Ee(_e,{color:"yellow",children:f})}),i&&pt(ut,{marginTop:1,children:[Ee(_e,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Ee(xs,{value:r,onChange:d,placeholder:"webhook name or ID"}),Ee(_e,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Ee(ut,{marginTop:1,children:Ee(_e,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):pt(ut,{marginTop:1,flexDirection:"column",children:[Ee(ut,{children:pt(_e,{bold:!0,children:[At("NAME",24),At("DESCRIPTION",36),At("TRIGGER",28),"TAGS"]})}),t.map(n=>pt(ut,{children:[Ee(_e,{children:At(n.displayName,24)}),Ee(_e,{dimColor:!0,children:At(hs(n.description??"",34),36)}),Ee(_e,{dimColor:!0,children:At(n.trigger,28)}),Ee(_e,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),Ee(ut,{marginTop:1,children:Ee(_e,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function At(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function hs(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ye,Text as me,useInput as ys}from"ink";import bs from"ink-text-input";import{useEffect as Rr,useState as it,useCallback as ko}from"react";import{jsx as ge,jsxs as We}from"react/jsx-runtime";function vs(e){return e>=4?"red":e===3?"yellow":"gray"}function Cs(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Ss(e){return new Date(e).toLocaleDateString()}function Nr({onBack:e}){let[t,o]=it([]),[u,m]=it(0),[g,a]=it([]),[i,s]=it(!0),[r,d]=it(!1),[f,S]=it(""),[h,C]=it("all"),[n,T]=it(null),[_,E]=it(!1),k=ko(()=>{b("/agents").then(({agents:D})=>{o(D),s(!1)}).catch(()=>s(!1))},[]);Rr(()=>{k()},[k]);let H=t[u],Q=ko(()=>{H&&(E(!1),b(`/memories/${H.id}`).then(({memories:D})=>{a(D),T(null)}).catch(D=>T(`Failed: ${D instanceof Error?D.message:String(D)}`)))},[H]);Rr(()=>{H&&Q()},[H,Q]);let I=ko(async D=>{if(!(!H||!D.trim()))try{let Z=await b("/memories/query",{method:"POST",body:{agentId:H.id,prompt:D.trim()}});a(Z.memories),E(!0),T(`Search: ${Z.count} results`)}catch(Z){T(`Search failed: ${Z instanceof Error?Z.message:String(Z)}`)}},[H]),O=r,R=g.filter(D=>h==="all"?!0:h==="high"?D.importance>3:h==="medium"?D.importance===3:D.importance<3);return ys((D,Z)=>{if(O){if(Z.escape){d(!1),S("");return}if(Z.return){I(f),d(!1),S("");return}return}if(Z.escape||D==="q"){e();return}if(D==="a"){m(le=>(le+1)%Math.max(1,t.length));return}if(Z.leftArrow){m(le=>(le-1+t.length)%Math.max(1,t.length));return}if(Z.rightArrow){m(le=>(le+1)%Math.max(1,t.length));return}if(D==="s"){d(!0),S(""),T(null);return}if(D==="h"){C(le=>le==="high"?"all":"high");return}if(D==="m"){C(le=>le==="medium"?"all":"medium");return}if(D==="l"){C(le=>le==="low"?"all":"low");return}D==="r"&&Q()}),i?ge(me,{dimColor:!0,children:"Loading agents..."}):t.length===0?We(Ye,{flexDirection:"column",children:[ge(me,{dimColor:!0,children:"No agents found"}),ge(me,{dimColor:!0,children:"Press Esc to go back"})]}):We(Ye,{flexDirection:"column",children:[ge(me,{bold:!0,children:"Memories (Esc to go back)"}),We(Ye,{marginTop:1,children:[ge(me,{children:"Agent: "}),ge(me,{bold:!0,color:"cyan",children:H?.name??"?"}),We(me,{dimColor:!0,children:[" (",u+1,"/",t.length,") [a/arrows to switch]"]})]}),ge(Ye,{children:We(me,{dimColor:!0,children:["Filter: ",h==="all"?"all":h," | ",_?"search results":"all memories"," (",R.length,")"]})}),n&&ge(Ye,{children:ge(me,{color:"yellow",children:n})}),r&&We(Ye,{marginTop:1,children:[ge(me,{bold:!0,color:"cyan",children:"Search: "}),ge(bs,{value:f,onChange:S,placeholder:"search query..."}),ge(me,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),R.length===0?ge(Ye,{marginTop:1,children:We(me,{dimColor:!0,children:["No memories",h!=="all"?` matching filter '${h}'`:""]})}):ge(Ye,{marginTop:1,flexDirection:"column",children:R.map(D=>We(Ye,{marginBottom:0,children:[We(me,{color:vs(D.importance),bold:!0,children:[Cs(D.importance)," "]}),ge(me,{dimColor:!0,children:Mr(D.type??"?",12)}),ge(me,{dimColor:!0,children:Mr(`\xD7${D.retrievedCount??0}`,5)}),We(me,{children:[ws(D.content,55)," "]}),ge(me,{dimColor:!0,children:Ss(D.createdAt)}),D.score!==void 0&&We(me,{dimColor:!0,children:[" (",D.score.toFixed(2),")"]})]},D.id))}),ge(Ye,{marginTop:1,children:ge(me,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Mr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function ws(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ge,Text as de,useInput as Bs}from"ink";import lo from"ink-text-input";import{useState as Re,useEffect as $r,useCallback as Io}from"react";import{jsx as ye,jsxs as pe}from"react/jsx-runtime";var Lr={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"]},Es={"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 _r({onBack:e}){let{state:t}=He(),[o,u]=Re({}),[m,g]=Re([]),[a,i]=Re(null),[s,r]=Re("view"),[d,f]=Re(0),[S,h]=Re(""),[C,n]=Re(null),[T,_]=Re(!1),[E,k]=Re([]),[H,Q]=Re({}),[I,O]=Re(0),[R,D]=Re(""),[Z,le]=Re(""),[Je,ht]=Re(""),Ne=Object.values(Lr).flat(),v=Io(()=>{b("/config").then(N=>{u(N.config),g(N.mutable)}).catch(N=>i(N.message)),b("/config/env-diff").then(N=>{k(N.diffs)}).catch(()=>{}),b("/config/env").then(N=>Q(N.env??{})).catch(()=>{})},[]);$r(()=>{v()},[v]),$r(()=>{t.configVersion>0&&v()},[t.configVersion,v]);let $=Io(async()=>{let N=Ne[d];if(N){_(!0),n(null);try{let A=S,G=o[N];if(G&&typeof G.value=="number"&&(A=Number(S),isNaN(A))){n("Invalid number"),_(!1);return}let ue=await b("/config",{method:"PATCH",body:{[N]:A}});ue.updated.length>0&&(n(`Updated: ${N}`),v()),ue.errors.length>0&&n(ue.errors[0]),r("view")}catch(A){n(`Failed: ${A instanceof Error?A.message:String(A)}`)}finally{_(!1)}}},[Ne,d,S,o,v]),M=Object.keys(H),J=Io(async N=>{try{await b("/config/env",{method:"PUT",body:N}),n("Env vars saved"),v()}catch(A){n(`Failed: ${A instanceof Error?A.message:String(A)}`)}},[v]);if(Bs((N,A)=>{if(s==="edit"){if(A.escape){r("view");return}return}if(s==="env-list"){if(A.escape){r("view");return}if(A.upArrow&&I>0&&O(G=>G-1),A.downArrow&&I<M.length-1&&O(G=>G+1),N==="a"){D(""),r("env-add-key");return}if(N==="d"&&M.length>0){let G=M[I],ue={...H};delete ue[G],J(ue),I>=M.length-1&&I>0&&O(et=>et-1);return}if(A.return&&M.length>0){ht(H[M[I]]??""),r("env-edit-value");return}return}if(s==="env-add-key"){if(A.escape){r("env-list");return}return}if(s==="env-add-value"){if(A.escape){r("env-list");return}return}if(s==="env-edit-value"){if(A.escape){r("env-list");return}return}if(A.escape||N==="q"){e();return}if(A.upArrow&&d>0&&f(G=>G-1),A.downArrow&&d<Ne.length-1&&f(G=>G+1),A.return||N==="e"){let G=Ne[d],ue=o[G];ue&&ue.mutable?(h(String(ue.value??"")),r("edit"),n(null)):ue&&!ue.mutable&&n("This setting requires a restart to change")}N==="v"&&(O(0),r("env-list"),n(null)),N==="r"&&(v(),n("Refreshed")),N==="s"&&E.length>0&&b("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),k([]),v()}),N==="l"&&E.length>0&&b("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),v()})}),a)return pe(Ge,{flexDirection:"column",children:[pe(de,{color:"red",children:["Failed to load config: ",a]}),ye(de,{dimColor:!0,children:"Press Esc or q to return"})]});let Ie=0;return pe(Ge,{flexDirection:"column",children:[ye(de,{bold:!0,children:"Settings"}),C&&ye(de,{color:C.startsWith("Failed")||C.startsWith("This setting")?"yellow":"green",children:C}),E&&E.length>0&&pe(Ge,{flexDirection:"column",marginBottom:1,children:[pe(de,{color:"yellow",children:[".env differs from DB (",E.length," key(s)): ",E.map(N=>N.envKey).join(", ")]}),ye(de,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ye(Ge,{marginTop:1,flexDirection:"column",children:Object.entries(Lr).map(([N,A])=>pe(Ge,{marginBottom:1,flexDirection:"column",children:[ye(de,{bold:!0,color:"cyan",children:N}),A.map(G=>{let ue=o[G],yt=Ie++===d,bt=m.includes(G),jt=Es[G]??G,lt=ue?String(ue.value??""):"...";return s==="edit"&&yt?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",jt,": "]}),ye(lo,{value:S,onChange:h,onSubmit:()=>{$()}}),T&&ye(de,{color:"yellow",children:" saving..."})]},G):pe(Ge,{children:[pe(de,{color:yt?"cyan":"white",children:[yt?"> ":" ",bt?" ":"\u{1F512} ",jt,": "," "]}),ye(de,{color:bt?"white":"gray",children:lt}),!bt&&ye(de,{dimColor:!0,children:" (restart required)"})]},G)})]},N))}),ye(de,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),s.startsWith("env")&&pe(Ge,{flexDirection:"column",marginTop:1,children:[pe(de,{bold:!0,color:"cyan",children:["Environment Variables (",M.length,")"]}),M.length===0&&s==="env-list"&&ye(de,{dimColor:!0,children:" No env vars. Press a to add."}),M.map((N,A)=>{let G=A===I;return s==="env-edit-value"&&G?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",N," = "]}),ye(lo,{value:Je,onChange:ht,onSubmit:()=>{J({...H,[N]:Je}),r("env-list")}})]},N):pe(de,{color:G&&s==="env-list"?"cyan":"white",children:[G&&s==="env-list"?"> ":" ",N," = ",H[N]]},N)}),s==="env-add-key"&&pe(Ge,{children:[ye(de,{color:"green",children:" New key: "}),ye(lo,{value:R,onChange:D,onSubmit:()=>{R.trim()&&(le(""),r("env-add-value"))}})]}),s==="env-add-value"&&pe(Ge,{children:[pe(de,{color:"green",children:[" ",R," = "]}),ye(lo,{value:Z,onChange:le,onSubmit:()=>{J({...H,[R.trim()]:Z}),r("env-list")}})]}),ye(de,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as xt,Text as ke,useInput as ks}from"ink";import{useEffect as Is,useState as Ao,useCallback as As}from"react";import{jsx as Ce,jsxs as Dt}from"react/jsx-runtime";function Or({onBack:e}){let[t,o]=Ao([]),[u,m]=Ao(!0),[g,a]=Ao(0),{message:i,setMessage:s,clearMessage:r}=dt(),d=As(()=>{m(!0),b("/plugins").then(({plugins:f})=>{o(f),m(!1)}).catch(()=>m(!1))},[]);return Is(()=>{d()},[d]),ks((f,S)=>{if(S.escape||f==="q"){e();return}if(S.upArrow){a(h=>Math.max(0,h-1));return}if(S.downArrow){a(h=>Math.min(t.length-1,h+1));return}f==="r"&&(d(),r())}),u?Ce(ke,{dimColor:!0,children:"Loading plugins..."}):Dt(xt,{flexDirection:"column",children:[Dt(ke,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Ce(xt,{marginTop:1,children:Dt(ke,{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?Ce(xt,{marginTop:1,children:Ce(ke,{dimColor:!0,children:"No plugins installed."})}):Dt(xt,{marginTop:1,flexDirection:"column",children:[Dt(xt,{children:[Ce(ke,{dimColor:!0,children:" "}),Ce(ke,{dimColor:!0,children:Pt("Name",24)}),Ce(ke,{dimColor:!0,children:Pt("Scope",8)}),Ce(ke,{dimColor:!0,children:Pt("User",6)}),Ce(ke,{dimColor:!0,children:"Path"})]}),t.map((f,S)=>{let h=S===g,C=f.id.split("@")[0];return Dt(xt,{children:[Ce(ke,{color:h?"cyan":void 0,bold:h,children:h?"> ":" "}),Ce(ke,{color:h?"cyan":void 0,bold:h,children:Pt(C,24)}),Ce(ke,{color:h?"cyan":void 0,bold:h,children:Pt(f.scope,8)}),Ce(ke,{color:f.globalEnabled?"green":"gray",children:Pt(f.globalEnabled?"on":"off",6)}),Ce(ke,{dimColor:!0,children:f.installPath})]},f.id)})]}),Ce(xt,{marginTop:1,children:Ce(ke,{dimColor:!0,children:"r:refresh"})})]})}function Pt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Po,Text as Do,useInput as Ps}from"ink";import{useState as Ds}from"react";import{jsx as Tt,jsxs as Vr}from"react/jsx-runtime";var Rs=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function qr({onBack:e}){let[t,o]=Ds("tasks");return Ps((u,m)=>{if(m.escape||u==="q"){e();return}if(u==="1"){o("tasks");return}if(u==="2"){o("automations");return}if(u==="3"){o("goals");return}}),Vr(Po,{flexDirection:"column",children:[Tt(Do,{bold:!0,children:"Work Surface"}),Tt(Do,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Tt(Po,{gap:3,marginBottom:1,marginTop:1,children:Rs.map(u=>{let m=t===u.id;return Tt(Po,{children:Vr(Do,{color:m?"cyan":"gray",bold:m,children:[m?"\u25CF":"\u25CB"," ",u.key,". ",u.label]})},u.id)})}),t==="tasks"&&Tt(ro,{onBack:e}),t==="automations"&&Tt(ao,{onBack:e}),t==="goals"&&Tt(so,{onBack:e})]})}import{Box as re,Text as K,useInput as Ms}from"ink";import{useEffect as Ns,useState as Wt}from"react";import{jsx as q,jsxs as be}from"react/jsx-runtime";var Fr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Ur({onBack:e}){let[t,o]=Wt([]),[u,m]=Wt(!0),[g,a]=Wt(0),[i,s]=Wt(null),[r,d]=Wt("");Ns(()=>{f()},[]);async function f(){try{let C=await b("/channels");o(C.channels)}catch{}m(!1)}async function S(C){if(t.find(T=>T.id===C)?.platform==="wechat")try{d("Starting WeChat QR login...");let T=await b(`/channels/${C}/wechat/qr-start`,{method:"POST"});if(T.qrcodeUrl){d(`Scan QR: ${T.qrcodeUrl}
10
- Waiting for scan...`);let _=await b(`/channels/${C}/wechat/qr-wait`,{method:"POST",body:{sessionKey:T.sessionKey,timeoutMs:12e4}});d(_.message)}else d(T.message);f()}catch{d("WeChat connect failed")}else try{await b(`/channels/${C}/connect`,{method:"POST"}),d("Connecting..."),f()}catch{d("Connect failed")}}async function h(C){try{await b(`/channels/${C}/disconnect`,{method:"POST"}),d("Disconnected"),f()}catch{d("Disconnect failed")}}return Ms((C,n)=>{if(i){if(n.escape||C==="q"){s(null);return}if(C==="c"){S(i.id);return}if(C==="d"){h(i.id);return}return}if(n.escape){e();return}if(n.upArrow){a(T=>Math.max(0,T-1));return}if(n.downArrow){a(T=>Math.min(t.length-1,T+1));return}if(n.return&&t[g]){s(t[g]),d("");return}}),u?q(re,{flexDirection:"column",children:q(K,{dimColor:!0,children:"Loading channels..."})}):i?be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[be(K,{bold:!0,children:["Channel: ",i.name]}),q(K,{dimColor:!0,children:" (Esc to go back)"})]}),be(re,{flexDirection:"column",gap:0,children:[be(K,{children:["ID: ",i.id]}),be(K,{children:["Platform: ",i.platform]}),be(K,{children:["Status: ",q(K,{color:Fr[i.status]??"white",children:i.status})]}),be(K,{children:["Enabled: ",i.enabled?"yes":"no"]}),be(K,{children:["Messages: ",i.messageCount]}),be(K,{children:["Config: ",JSON.stringify(i.config)]})]}),q(re,{marginTop:1,children:q(K,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&q(K,{color:"yellow",children:r})]}):be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[q(K,{bold:!0,children:"Channels"}),be(K,{dimColor:!0,children:[" (",t.length," total) "]}),q(K,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?q(K,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):be(re,{flexDirection:"column",children:[be(re,{children:[q(re,{width:3,children:q(K,{dimColor:!0,children:" "})}),q(re,{width:12,children:q(K,{bold:!0,dimColor:!0,children:"ID"})}),q(re,{width:16,children:q(K,{bold:!0,dimColor:!0,children:"Name"})}),q(re,{width:12,children:q(K,{bold:!0,dimColor:!0,children:"Platform"})}),q(re,{width:14,children:q(K,{bold:!0,dimColor:!0,children:"Status"})}),q(re,{width:10,children:q(K,{bold:!0,dimColor:!0,children:"Enabled"})}),q(re,{width:10,children:q(K,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((C,n)=>be(re,{children:[q(re,{width:3,children:q(K,{children:n===g?">":" "})}),q(re,{width:12,children:q(K,{inverse:n===g,children:C.id.slice(0,8)})}),q(re,{width:16,children:q(K,{children:C.name})}),q(re,{width:12,children:q(K,{children:C.platform})}),q(re,{width:14,children:be(K,{color:Fr[C.status]??"white",children:[C.status==="connected"?"\u25CF":C.status==="error"?"\u2717":"\u25CB"," ",C.status]})}),q(re,{width:10,children:q(K,{color:C.enabled?"green":"gray",children:C.enabled?"yes":"no"})}),q(re,{width:10,children:q(K,{children:C.messageCount})})]},C.id))]})]})}import{Box as Rt,Text as at,useInput as _s}from"ink";import{useEffect as Os,useState as Gt,useCallback as Vs}from"react";import{Box as P,Text as p,useInput as $s}from"ink";import Ze from"ink-text-input";import{useEffect as Wr,useState as z,useCallback as mt}from"react";Wo();import{Fragment as Gr,jsx as x,jsxs as w}from"react/jsx-runtime";var Ls=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function Hr({roleId:e,onBack:t}){let[o,u]=z(null),[m,g]=z([]),[a,i]=z(!0),[s,r]=z("view"),[d,f]=z(""),[S,h]=z(0),[C,n]=z(""),[T,_]=z([]),[E,k]=z(0),[H,Q]=z(new Set),[I,O]=z("inline"),[R,D]=z(""),[Z,le]=z(""),[Je,ht]=z([]),[Ne,v]=z(new Set),[$,M]=z(0),[J,Ie]=z("default"),[N,A]=z(""),[G,ue]=z(""),[et,yt]=z("mode"),[bt,jt]=z([]),[lt,zr]=z(null),[go,Xr]=z([]),[vt,fo]=z([]),[$o,po]=z(""),[gt,Kt]=z(0),[zt,Lo]=z(""),[_o,Oo]=z(""),[Vo,qo]=z(""),{message:L,setMessage:U}=dt(),se=mt(()=>{i(!0),b(`/roles/${e}`).then(({role:c,boundPlugins:y})=>{u(c),g(y??[]),f(c.cagPrompt??""),Q(new Set(c.allowedTools??[])),O(c.executionMode??"inline"),D(c.model??""),le(c.maxBudgetUsd!=null?String(c.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Wr(()=>{se(),b("/config").then(c=>{let y=c.config["defaults.deniedReadPaths"]?.value;Array.isArray(y)&&jt(y),zr(c.sandbox),Xr(c.osCapabilities?.registry??[])}).catch(()=>{})},[se]),Wr(()=>{O(o?.executionMode??"inline"),D(o?.model??""),le(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Ie(o?.permissionMode??"default"),A((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),fo(o?.osCapabilities??[]);let c=o?.osCapabilities?.find(y=>y.id==="automation")?.targets??[];po(c.join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let Qr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:d}}),U("CAG prompt saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,d,se,U]),Yr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:qe}}),U("Directories saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,se,U]),Zr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),U("Tool permissions saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,H,se,U]),Jr=mt(async()=>{if(!o)return;let c={executionMode:I};R!==void 0&&(c.model=R);let y=parseFloat(Z);isNaN(y)||(c.maxBudgetUsd=y);try{await b(`/roles/${o.id}`,{method:"PATCH",body:c}),U("Execution config saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,I,R,Z,se,U]),en=mt(async()=>{if(!o)return;let c={permissionMode:J},y=N.split(",").map(B=>B.trim()).filter(Boolean),l=G.split(",").map(B=>B.trim()).filter(Boolean);c.allowedBashPatterns=y.length>0?y:[],c.deniedBashPatterns=l.length>0?l:[];try{await b(`/roles/${o.id}`,{method:"PATCH",body:c}),U("Permission config saved","success"),r("view"),se()}catch(B){U(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[o,J,N,G,se,U]),Fo=mt(c=>{let y=new Map;for(let l of c){if(!l.id)continue;let B={id:l.id};l.targets?.length&&(B.targets=Array.from(new Set(l.targets.map(V=>V.trim()).filter(Boolean)))),y.set(l.id,B)}return Array.from(y.values()).sort((l,B)=>l.id.localeCompare(B.id))},[]),tn=mt(async()=>{if(!o)return;let c=Fo(vt),y=c.find(l=>l.id==="automation")?.targets??[];if(c.some(l=>l.id==="automation")&&(y.length===0||y.some(l=>!Ls.test(l)))){U("Automation requires valid bundle id targets","error");return}try{await b(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:c}}),U("OS capabilities saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,vt,Fo,se,U]),qe=o?.additionalDirectories??[];if($s((c,y)=>{if(y.escape){r("view");return}if(c==="r"){se();return}switch(s){case"view":{if(c==="c"){r("edit-cag");return}if(c==="d"){r("edit-dirs"),h(0),n("");return}if(c==="t"){r("edit-tools");return}if(c==="o"){r("edit-oscaps");return}if(c==="x"){r("edit-exec");return}if(c==="h"){b("/channels?enabled=true").then(({channels:l})=>{ht(l.map(B=>({name:B.name,id:B.id}))),v(new Set(o?.allowedChannels??[])),M(0),r("edit-channels")}).catch(()=>U("Failed to load channels","error"));return}if(c==="p"){Ie(o?.permissionMode??"default"),A((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),yt("mode"),r("edit-permissions");return}if(c==="v"){Kt(0),r("edit-env");return}if(c==="i"){if(!o)return;let l=!o.inheritUserSettings;b(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:l}}).then(()=>{U(`Inherit user settings: ${l?"ON":"OFF"}`,"success"),se()}).catch(()=>U("Failed to toggle","error"));return}break}case"edit-cag":{if(y.ctrl&&c==="s"){Qr();return}break}case"edit-dirs":{if(c==="s"){Yr();return}if(c==="a"){r("edit-dirs-add");return}if(c==="m"&&qe.length>0){let l=qe[S];if(l){u(V=>V&&{...V,additionalDirectories:V.additionalDirectories?.map((ce,tt)=>tt===S?{...typeof ce=="string"?{path:ce}:ce,mode:ce.mode==="ro"?"rw":"ro"}:ce)});let B=l.mode==="ro"?"rw":"ro";U(`Mode set to ${B.toUpperCase()}`,"success")}return}if(c==="x"&&qe.length>0){u(l=>l&&{...l,additionalDirectories:qe.filter((B,V)=>V!==S)}),h(l=>Math.max(0,Math.min(l,qe.length-2)));return}if(y.upArrow){h(l=>Math.max(0,l-1));return}if(y.downArrow){h(l=>Math.min(qe.length-1,l+1));return}break}case"edit-dirs-add":{if(y.escape){r("edit-dirs"),n(""),_([]);return}if(y.return&&T.length>0){let l=T[E];l&&(n(l.endsWith("/")?l:l+"/"),_([]));return}if(y.return){let l=C.trim();l&&l.startsWith("/")?(u(B=>B&&{...B,additionalDirectories:[...B.additionalDirectories??[],{path:l,mode:"rw"}]}),n(""),_([]),r("edit-dirs")):U("Path must be absolute (must start with /)","error");return}if(y.tab){let l=C.trim();if(!l||!l.startsWith("/"))return;b(`/fs/suggest-dirs?prefix=${encodeURIComponent(l)}`).then(({suggestions:B})=>{B.length===1?(n(B[0]+"/"),_([])):B.length>1&&(_(B),k(0))}).catch(()=>{_([])});return}if(y.upArrow&&T.length>0){k(l=>Math.max(0,l-1));return}if(y.downArrow&&T.length>0){k(l=>Math.min(T.length-1,l+1));return}break}case"edit-tools":{if(c==="s"){Zr();return}let l=parseInt(c,10)-1;if(!isNaN(l)&&l>=0&&l<Xt.length){let B=Xt[l];Q(V=>{let ce=new Set(V);return ce.has(B)?ce.delete(B):ce.add(B),ce});return}break}case"edit-oscaps":{if(c==="s"){tn();return}if(c==="a"&&vt.some(V=>V.id==="automation")){let V=vt.find(ce=>ce.id==="automation")?.targets??[];po(V.join(", ")),r("edit-oscaps-targets");return}let l=go.filter(V=>V.editable),B=parseInt(c,10)-1;if(!isNaN(B)&&B>=0&&B<l.length){let V=l[B];fo(ce=>ce.some($t=>$t.id===V.id)?ce.filter($t=>$t.id!==V.id):[...ce,{id:V.id,targets:V.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(y.return){let l=$o.split(",").map(B=>B.trim()).filter(Boolean);fo(B=>B.map(V=>V.id==="automation"?{...V,targets:l}:V)),r("edit-oscaps");return}break}case"edit-exec":{if(c==="s"){Jr();return}if(y.tab){O(l=>l==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(c==="s"){en();return}if(y.tab){yt(l=>l==="mode"?"allowed":l==="allowed"?"denied":"mode");return}if(et==="mode"&&(y.upArrow||y.downArrow)){let l=["default","acceptEdits","dontAsk","bypassPermissions"],B=l.indexOf(J);y.upArrow&&Ie(l[Math.max(0,B-1)]),y.downArrow&&Ie(l[Math.min(l.length-1,B+1)]);return}break}case"edit-channels":{if(c==="s"){if(!o)return;let l=Ne.size>0?Array.from(Ne):[];b(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:l}}).then(()=>{U("Channels saved","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(c==="u"){if(!o)return;b(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{U("Channels: unrestricted","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(c===" "){let l=Je[$];l&&v(B=>{let V=new Set(B);return V.has(l.name)?V.delete(l.name):V.add(l.name),V});return}if(y.upArrow){M(l=>Math.max(0,l-1));return}if(y.downArrow){M(l=>Math.min(Je.length-1,l+1));return}break}case"edit-env":{let l=Object.keys(o?.envVars??{});if(c==="a"){Lo(""),r("edit-env-add-key");return}if(c==="d"&&l.length>0){let B=l[gt],V={...o?.envVars??{}};delete V[B],b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:V}}).then(()=>{U("Deleted","success"),se()}).catch(()=>U("Delete failed","error")),gt>=l.length-1&&gt>0&&Kt(ce=>ce-1);return}if(y.return&&l.length>0){qo((o?.envVars??{})[l[gt]]??""),r("edit-env-edit-value");return}y.upArrow&&gt>0&&Kt(B=>B-1),y.downArrow&&gt<l.length-1&&Kt(B=>B+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),a)return x(p,{dimColor:!0,children:"Loading role..."});if(!o)return x(p,{dimColor:!0,children:"Role not found."});if(s==="edit-cag")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),x(Ze,{value:d,onChange:f,placeholder:"Character And Guidance prompt..."}),L&&x(P,{marginTop:1,children:x(p,{color:L.type==="error"?"red":"green",children:L.text})})]});if(s==="edit-dirs-add")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),x(Ze,{value:C,onChange:c=>{n(c),_([])},placeholder:"/absolute/path/to/directory"}),T.length>0&&w(P,{flexDirection:"column",marginTop:1,children:[T.map((c,y)=>w(p,{color:y===E?"cyan":void 0,dimColor:y!==E,children:[y===E?"> ":" ",c,"/"]},c)),x(p,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),L&&x(P,{marginTop:1,children:x(p,{color:L.type==="error"?"red":"green",children:L.text})})]});if(s==="edit-dirs")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),qe.length===0?x(p,{dimColor:!0,children:"No directories. Press a to add one."}):qe.map((c,y)=>{let l=typeof c=="string"?{path:c,mode:"rw"}:c,B=l.mode!=="ro";return w(P,{children:[x(p,{color:y===S?"cyan":void 0,bold:y===S,children:y===S?"> ":" "}),w(p,{color:B?"green":"yellow",children:["[",B?"RW":"RO","]"," "]}),x(p,{color:y===S?"cyan":void 0,children:l.path})]},l.path)})]});if(s==="edit-tools")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),Xt.map((c,y)=>{let l=H.has(c);return w(P,{children:[w(p,{dimColor:!0,children:[y+1,". "]}),x(p,{color:l?"green":"red",children:l?"[ON] ":"[OFF] "}),x(p,{children:c})]},c)})]});if(s==="edit-oscaps"){let c=go.filter(y=>y.editable);return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),lt&&w(p,{dimColor:!0,children:["Platform: ",lt.platform," ",lt.available?"(sandbox active)":"(sandbox unavailable)"]}),go.map(y=>{let l=c.findIndex(tt=>tt.id===y.id),B=vt.some(tt=>tt.id===y.id),V=l>=0?`${l+1}.`:" -",ce=y.id==="automation"?(()=>{let tt=vt.find($t=>$t.id===y.id)?.targets??[];return tt.length>0?` targets: ${tt.join(", ")}`:" targets: (none)"})():"";return w(P,{flexDirection:"column",marginBottom:1,children:[w(p,{color:B?"green":y.editable?"red":"gray",children:[V," ",B?"[ON]":"[OFF]"," ",y.label," [",y.availability,"]"]}),w(p,{dimColor:!0,children:[" ",y.description,ce]}),y.effectiveDisabledReason&&!y.editable&&w(p,{dimColor:!0,children:[" ",y.effectiveDisabledReason]})]},y.id)}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]})}if(s==="edit-oscaps-targets")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),x(Ze,{value:$o,onChange:po,placeholder:"com.apple.mail, com.apple.systemevents"}),x(p,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-exec")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),w(P,{children:[x(p,{bold:!0,children:" Mode: "}),x(p,{color:"cyan",children:I}),x(p,{dimColor:!0,children:" (Tab to toggle)"})]}),w(P,{children:[x(p,{bold:!0,children:" Model: "}),x(Ze,{value:R,onChange:D,placeholder:"sonnet, opus, haiku, or blank"})]}),w(P,{children:[x(p,{bold:!0,children:" Max Budget (USD): "}),x(Ze,{value:Z,onChange:le,placeholder:"0 = unlimited"})]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-permissions")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),w(P,{children:[x(p,{bold:!0,color:et==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(y=>w(p,{color:y===J?"green":"gray",children:[y===J?`[${y}]`:` ${y} `," "]},y))]}),w(P,{children:[x(p,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?x(Ze,{value:N,onChange:A,placeholder:"git add *, pnpm test*"}):x(p,{children:N||"(none)"})]}),w(P,{children:[x(p,{bold:!0,color:et==="denied"?"cyan":void 0,children:" Denied Bash: "}),et==="denied"?x(Ze,{value:G,onChange:ue,placeholder:"rm -rf *, ssh *"}):x(p,{children:G||"(none)"})]}),x(p,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-channels")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Je.length===0?x(p,{dimColor:!0,children:"No channels available"}):Je.map((c,y)=>w(P,{children:[w(p,{children:[y===$?">":" "," "]}),w(p,{color:Ne.has(c.name)?"green":"gray",children:["[",Ne.has(c.name)?"x":" ","] ",c.name]})]},c.id)),w(p,{dimColor:!0,children:["Selected: ",Ne.size>0?Array.from(Ne).join(", "):"none (= block all)"]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s.startsWith("edit-env")){let c=Object.keys(o.envVars??{});return w(P,{flexDirection:"column",children:[w(p,{bold:!0,children:["Environment Variables (",c.length,")"]}),c.length===0&&s==="edit-env"&&x(p,{dimColor:!0,children:" No env vars. Press a to add."}),c.map((y,l)=>{let B=l===gt;return s==="edit-env-edit-value"&&B?w(P,{children:[w(p,{color:"cyan",children:["> ",y," = "]}),x(Ze,{value:Vo,onChange:qo,onSubmit:()=>{let V={...o.envVars??{},[y]:Vo};b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:V}}).then(()=>{U("Saved","success"),se(),r("edit-env")}).catch(()=>U("Save failed","error"))}})]},y):w(p,{color:B&&s==="edit-env"?"cyan":"white",children:[B&&s==="edit-env"?"> ":" ",y," = ",(o.envVars??{})[y]]},y)}),s==="edit-env-add-key"&&w(P,{children:[x(p,{color:"green",children:" New key: "}),x(Ze,{value:zt,onChange:Lo,onSubmit:()=>{zt.trim()&&(Oo(""),r("edit-env-add-value"))}})]}),s==="edit-env-add-value"&&w(P,{children:[w(p,{color:"green",children:[" ",zt," = "]}),x(Ze,{value:_o,onChange:Oo,onSubmit:()=>{let y={...o.envVars??{},[zt.trim()]:_o};b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:y}}).then(()=>{U("Added","success"),se(),r("edit-env")}).catch(()=>U("Add failed","error"))}})]}),x(p,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),L&&x(p,{color:L.type==="error"?"red":"green",children:L.text})]})}return w(P,{flexDirection:"column",children:[w(p,{bold:!0,children:["Role: ",o.name]}),w(P,{children:[x(p,{dimColor:!0,children:"ID: "}),x(p,{children:o.id})]}),w(P,{children:[x(p,{dimColor:!0,children:"Status: "}),x(p,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&w(P,{children:[x(p,{dimColor:!0,children:"Score: "}),w(p,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"Created: "}),x(p,{children:new Date(o.createdAt).toLocaleString()})]}),w(P,{children:[x(p,{dimColor:!0,children:"Execution: "}),w(p,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"OS Capabilities: "}),x(p,{children:(o.osCapabilities?.length??0)>0?o.osCapabilities.map(c=>c.id==="automation"&&c.targets?.length?`automation(${c.targets.join(",")})`:c.id).join(", "):"None"})]}),lt&&w(P,{children:[x(p,{dimColor:!0,children:"Sandbox Platform: "}),w(p,{children:[lt.platform," ",lt.available?"(active)":"(unavailable)"]})]}),qe.length>0&&w(Gr,{children:[x(p,{bold:!0,children:"Additional Directories:"}),qe.map(c=>w(p,{dimColor:!0,children:[" ",c.path]},c.path))]}),w(P,{children:[x(p,{dimColor:!0,children:"Permission: "}),x(p,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&w(P,{children:[x(p,{dimColor:!0,children:" Bash Allow: "}),x(p,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&w(P,{children:[x(p,{dimColor:!0,children:" Bash Deny: "}),x(p,{children:o.deniedBashPatterns.join(", ")})]}),bt.length>0&&w(P,{flexDirection:"column",children:[x(p,{dimColor:!0,children:"Denied Read Paths (global):"}),bt.map(c=>w(p,{dimColor:!0,children:[" ",c]},c)),w(p,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"Channels: "}),x(p,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),w(P,{children:[x(p,{dimColor:!0,children:"Inherit User Settings: "}),x(p,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&w(Gr,{children:[x(p,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(c=>w(p,{dimColor:!0,children:[" - ",c]},c))]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),x(P,{marginTop:1,children:x(p,{dimColor:!0,children:"c:CAG d:dirs t:tools o:oscaps x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as Ve,jsxs as co}from"react/jsx-runtime";function jr({onBack:e}){let[t,o]=Gt([]),[u,m]=Gt(!0),[g,a]=Gt(0),[i,s]=Gt("list"),[r,d]=Gt(null),{message:f,setMessage:S,clearMessage:h}=dt(),C=Vs(()=>{m(!0),b("/roles").then(({roles:n})=>{o(n.map(T=>({id:T.id,name:T.name,status:T.status,performanceScore:T.performanceScore,createdAt:T.createdAt}))),m(!1)}).catch(()=>m(!1))},[]);return Os(()=>{C()},[C]),_s((n,T)=>{if(T.escape||n==="q"){e();return}if(T.upArrow){a(_=>Math.max(0,_-1));return}if(T.downArrow){a(_=>Math.min(t.length-1,_+1));return}if(n==="r"&&(C(),h()),n===`
11
- `||n==="o"||n==="e"){t.length>0&&(d(t[g].id),s("detail"));return}}),u?Ve(at,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Ve(Hr,{roleId:r,onBack:()=>s("list")}):co(Rt,{flexDirection:"column",children:[co(at,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),f&&Ve(Rt,{marginTop:1,children:co(at,{color:f.type==="success"?"green":f.type==="error"?"red":"gray",children:[f.type==="success"?"\u2713 ":f.type==="error"?"\u2717 ":"\u2192 ",f.text]})}),t.length===0?Ve(Rt,{marginTop:1,children:Ve(at,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ve(Rt,{marginTop:1,flexDirection:"column",children:t.map((n,T)=>{let _=T===g,E=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return co(Rt,{children:[Ve(at,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),Ve(at,{color:_?"cyan":void 0,bold:_,children:Ro(n.name,24)}),Ve(at,{color:qs(n.status),children:Ro(n.status,12)}),Ve(at,{dimColor:!0,children:Ro(E,8)})]},n.id)})}),Ve(Rt,{marginTop:1,children:Ve(at,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function qs(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Ro(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Fs,Text as Mo}from"ink";import Us from"react";import{jsx as uo,jsxs as Gs}from"react/jsx-runtime";var Me={key:"Esc",label:"back"},Ws={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},Me],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},Me],config:[Me],evolution:[Me],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},Me],strategies:[Me],templates:[{key:"\u2191\u2193",label:"move"},{key:"t",label:"run"},{key:"s",label:"toggle"},{key:"e",label:"edit"},{key:"c",label:"create"},{key:"d",label:"delete"},{key:"r",label:"refresh"},Me],webhooks:[Me],memories:[Me],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},Me],roles:[Me],settings:[Me],channels:[Me]};function Kr(){let{state:e}=He(),t=Ws[e.view]??[Me];return uo(Fs,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,u)=>Gs(Us.Fragment,{children:[u>0&&uo(Mo,{dimColor:!0,children:" "}),uo(Mo,{color:"cyan",children:o.key}),uo(Mo,{dimColor:!0,children:` ${o.label}`})]},`${o.key}-${o.label}`))})}import{Fragment as Qs,jsx as X,jsxs as Nt}from"react/jsx-runtime";function Ks(){let{state:e,dispatch:t}=He(),{session:o,sendMessage:u,createNewSession:m,archiveCurrentSession:g}=Zo(),[a,i]=js([]);mo(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Xo();let{latestMessage:s}=er(o?.id??null),r=No(null);mo(()=>{s&&s.id!==r.current&&(r.current=s.id,i(k=>[...k,{role:"assistant",content:s.content}]))},[s]);let{events:d,isStreaming:f,clearEvents:S}=Yo(e.activeTaskId),h=d[d.length-1],C=h?.type==="complete"&&!f,n=No(null),T=No("");mo(()=>{T.current=d.filter(k=>k.type==="reasoning").map(k=>k.content).join("")},[d]),mo(()=>{if(C&&e.activeTaskId!==n.current){n.current=e.activeTaskId;let k=h?.content||T.current;k&&i(H=>[...H,{role:"assistant",content:k}])}},[C,h,e.activeTaskId]);let _=async k=>{let H=k.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),k.startsWith("/")){let I=k.slice(1),R={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"}[I];if(R){t({type:"SET_VIEW",view:R});return}if(I==="new"){if(await g()){let Z=await m();i([]),S(),Z&&i([{role:"assistant",content:`Session archived. New session started: ${Z.id.slice(0,8)}`}])}return}if(I==="session"){let D=o?`Session: ${o.id}
12
- Turns: ${o.messageCount}
13
- Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(Z=>[...Z,{role:"assistant",content:D}]);return}}if(i(I=>[...I,{role:"user",content:k}]),S(),!await u(k)){i(I=>[...I,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},E=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval;return Nt(Ht,{flexDirection:"column",paddingX:1,children:[X(or,{}),Nt(Ht,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Nt(Qs,{children:[X(lr,{messages:a}),X(sr,{events:d,isStreaming:f}),!e.connected&&!e.serverUnreachable&&X(Ht,{children:X(Mt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Nt(Ht,{flexDirection:"column",children:[X(Mt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),X(Mt,{dimColor:!0,children:"Check: adam server logs"}),X(Mt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&X(qr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&X(ro,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&X(Cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&X(Er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&X(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&X(Ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&X(ao,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&X(Dr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&X(Nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&X(Or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&X(jr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&X(_r,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&X(Ur,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?X(dr,{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?X(cr,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):E?X(nr,{onSubmit:_}):X(Kr,{}),e.planTimeoutNotice&&X(zs,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function zs({planId:e,onDismiss:t}){return Hs(o=>{o==="d"&&t()}),Nt(Ht,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Nt(Mt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),X(Mt,{dimColor:!0,children:" [d] Dismiss"})]})}function Xs(){return X(jo,{children:X(Ks,{})})}export{Xs as default};
@@ -1 +0,0 @@
1
- import{n as a,o as b}from"./chunk-DBI36EGR.js";import"./chunk-5V36ACKZ.js";import"./chunk-HQ66TFYI.js";import"./chunk-YHH3QMLL.js";import"./chunk-6THDALGC.js";import"./chunk-L4Y3GR6W.js";import"./chunk-NOUSHXGX.js";import"./chunk-XAMLLKKA.js";import"./chunk-KO5AFX5U.js";import"./chunk-JKPSEMUZ.js";import"./chunk-GYHOPV4Q.js";import"./chunk-I5IUTZA3.js";import"./chunk-24GTCFEV.js";import"./chunk-L7JP7DUO.js";import"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-T7GEINGZ.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-RUY23IJK.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.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 +0,0 @@
1
- import{j as a,k as b,l as c,m as d,n as e}from"./chunk-WRETNOC3.js";import"./chunk-HQ66TFYI.js";import"./chunk-YHH3QMLL.js";import"./chunk-6THDALGC.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-HYDCXE5K.js";import"./chunk-DMZM7RU6.js";import"./chunk-24GTCFEV.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-ZRUVORAJ.js";import"./chunk-NOUSHXGX.js";import"./chunk-I67UMGJM.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-7BSWC62F.js";import"./chunk-T7GEINGZ.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -1 +0,0 @@
1
- import{c as a,d as b,e as c}from"./chunk-KOWFPY2J.js";import"./chunk-KO5AFX5U.js";import"./chunk-I5IUTZA3.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1,83 +0,0 @@
1
- import{a as re}from"./chunk-5V36ACKZ.js";import{a as Ae,c as Ne,d as Ue,e as Z,f as $e,g as Oe,h as je,i as It,j as Fe,k as He,l as N,n as we,o as Ke,p as Qe}from"./chunk-HQ66TFYI.js";import{b as Ee,c as ge,e as De}from"./chunk-YHH3QMLL.js";import{b as z}from"./chunk-6THDALGC.js";import{a as Ye,c as ve,e as ze}from"./chunk-L4Y3GR6W.js";import{a as ee,b as x,c as te,d as We,e as Je}from"./chunk-NOUSHXGX.js";import{a as Y,b as y,c as O,d as E}from"./chunk-XAMLLKKA.js";import{d as be}from"./chunk-KO5AFX5U.js";import{j as ye}from"./chunk-JKPSEMUZ.js";import{e as Pe,f as Q,g as Le,i as me,j as X}from"./chunk-24GTCFEV.js";import{a as fe}from"./chunk-L7JP7DUO.js";import{g as Ge}from"./chunk-7BSWC62F.js";import{a as he,b as j,c as Ve,f as Be,g as qe}from"./chunk-T7GEINGZ.js";import{d as T,j as Re}from"./chunk-GSMC3VUM.js";import{e as Me,f as ue,h as vt,j as xe,k as v,m as D,n as A,o as Ce,p as pe,q as K}from"./chunk-J3NIPZ73.js";import{b as w,d as de}from"./chunk-4VHBKJD5.js";import{c as S,d as _e,h as $}from"./chunk-INNDBLZE.js";import{f as P}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Gt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as o}from"zod";K();X();import{v4 as G}from"uuid";de();function Tt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function F(e){w().prepare(`
2
- INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
3
- weight, calibration_factor, created_at)
4
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5
- `).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function Xe(e){return w().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Tt)}$();var St=S("goal-manager");async function Br(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await kt(e)}let r=Rt(t);return{goalState:t,validationResult:r,rawInput:e}}async function kt(e){let t=`Extract SMART goal fields from this natural language input.
6
-
7
- Input: "${e}"
8
-
9
- Respond ONLY with a JSON object:
10
- {
11
- "name": "short goal name (max 100 chars)",
12
- "description": "detailed description of what the goal aims to achieve",
13
- "metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
14
- "targetValue": <number, the target to reach>,
15
- "deadline_days": <number, days from now to complete>,
16
- "budget": <number, estimated budget in USD>,
17
- "role": "<best matching role: engineer | analyst | content_creator | reviewer>"
18
- }
19
-
20
- Rules:
21
- - name: concise, actionable title
22
- - metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
23
- - targetValue: realistic target for the metric; use 1 for binary goals
24
- - deadline_days: reasonable timeframe; default 7 if unclear
25
- - budget: estimated cost in USD; default 5 if unclear
26
- - role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await re(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let a=JSON.parse(n[0]),i=a.deadline_days??7;return{name:(a.name??e.slice(0,100)).slice(0,100),description:a.description??e,metric:a.metric??"completion",targetValue:a.targetValue??1,currentValue:0,deadline:Date.now()+i*24*60*60*1e3,budget:a.budget??5,roleId:a.roleId??"engineer",status:"active"}}}catch(r){St.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function Rt(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function qr(e,t,r){let n=G(),a=Date.now(),i={id:n,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:a,deliverTo:t,reportTo:r};return ee(i),i}function Ze(e,t){let r=Date.now(),n=[],a={id:G(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(a),F(a);let i={id:G(),goalId:e,level:"L1",parentId:a.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(i),F(i);let l={id:G(),goalId:e,level:"L2",parentId:i.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(l),F(l);let d={id:G(),goalId:e,level:"L3",parentId:l.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(d),F(d),n}var ne=class{static collect(t,r){let n=y(t);if(!n)return this.emptyMetrics(t,r);let a=z(t,500,0),i=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,l=new Set,d=0,u=0;for(let m of a)m.type==="tool_call"&&m.toolName&&l.add(m.toolName),m.type==="error"&&d++,m.type==="approval_request"&&u++;let c={taskId:t,goalId:r,timestamp:Date.now(),durationMs:i,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:l.size,errorCount:d,approvalCount:u,rawScore:0,isComplete:n.status==="completed"};return c.rawScore=this.computeRawScore(c),c}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),i=1-Math.min(t.costUsd/5,1),d=1-Math.min(t.turns/50,1),u;t.toolCount>=3&&t.toolCount<=15?u=1:t.toolCount<3?u=t.toolCount/3:u=Math.max(0,1-(t.toolCount-15)/15);let c=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),m=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*i+.2*d+.1*u+.15*c+.05*m}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};de();function _t(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function et(e){w().prepare(`
27
- INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
28
- metric_l2_score, metric_l3_score, context, completed_at)
29
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
30
- `).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function tt(e,t=100){return w().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(_t)}var oe=class{static collect(t){let r=x(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),a=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,i=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),l=this.calculateBudgetSpent(t),d=r.budgetUsd>0?Math.max(0,1-l/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),c={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:a,deadlineRemainingDays:i,budgetRemainingPct:d,expectedCompletionPct:u,rawScore:0};return c.rawScore=this.computeRawScore(c),c}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let a=t.budgetRemainingPct;return .5*r+.3*n+.2*a}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,a=r-t.createdAt;if(n<=0)return 0;let i=a/n;if(i<.1)return .5;let l=t.targetValue>0?t.currentValue/t.targetValue:0;return i>0?l/i:0}static calculateBudgetSpent(t){let r=tt(t,1e3),n=0,a=new Set;for(let i of r)if(i.taskId&&!a.has(i.taskId)){a.add(i.taskId);let l=y(i.taskId);l?.costUsd&&(n+=l.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};$();var Mt=S("agent"),V=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let a=(await re(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!a)throw new Error("Failed to parse LLM Judge response as JSON");let i=JSON.parse(a[0]);return{score:Math.max(0,Math.min(1,i.score??0)),confidence:Math.max(.3,Math.min(.95,i.confidence??.5)),reasoning:i.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,a=this.cache.get(n);if(a&&Date.now()-a.evaluatedAt<this.CACHE_TTL)return a;let i=y(t);if(!i){let f={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,f),f}let l=this.getPromptTemplate(i.prompt??"",i.result??i.error??"",r),d,u,c;try{let f=await this.callClaude(l);d=f.score,u=f.confidence,c=f.reasoning}catch(f){Mt.warn({error:f,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),i.status==="failed"?(d=.1,u=.6,c=`Task failed: ${i.error??"unknown error"} (heuristic fallback)`):i.status==="completed"&&i.result?(d=.7,u=.5,c="Task completed with result (heuristic fallback due to API error)"):i.status==="completed"?(d=.5,u=.4,c="Task completed without explicit result (heuristic fallback)"):(d=.3,u=.3,c=`Task in status: ${i.status} (heuristic fallback)`)}let m={taskId:t,criteria:r,score:d,confidence:u,reasoning:c,evaluatedAt:Date.now()};return this.cache.set(n,m),m}static shouldUseObjective(t){let r=y(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
31
-
32
- Task: ${t}
33
- Result: ${r}
34
- Criteria: ${n}
35
-
36
- Provide:
37
- 1. Score (0-1): How well did the task meet the criteria?
38
- 2. Confidence (0-1): How confident are you in this evaluation?
39
- 3. Reasoning: Brief explanation of your scoring
40
-
41
- Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var xt={L0:.2,L1:.15,L2:.35,L3:.3},ae=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let a=n.parentId,i=this.children.get(a)??[];i.push(n),this.children.set(a,i)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=Xe(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,a)=>a.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let a=0,i=0;for(let l of n){let d=r.get(l.id)??0,u=l.weight*l.calibrationFactor;a+=d*u,i+=u}return i>0?a/i:0}getWeightedScore(t){let r=0;for(let[n,a]of Object.entries(xt)){let i=this.aggregateScores(n,t);r+=i*a}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};$();var mn=S("agent");function ie(e,t){let r=Date.now(),n=ae.buildFromGoal(e),a=new Map,i=oe.collect(e);for(let u of n.queryPath("L0"))a.set(u.id,i.rawScore);let l=Ct(n);if(t){let u=ne.collect(t,e);if(u.isComplete){for(let m of n.queryPath("L3"))a.set(m.id,u.rawScore);let c=n.getNodeCount()>0?n.getWeightedScore(a):Math.max(0,Math.min(1,u.rawScore*.65+i.rawScore*.35));return{goalId:e,taskId:t,reward:c,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:l,source:"objective",confidence:.9,computedAt:r}}}if(t&&!V.shouldUseObjective(t)){let c=V.evaluate(t,"general_quality"),m=i.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:i.rawScore,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:l,source:"llm_judge",confidence:.4,computedAt:r}}let d=n.getNodeCount()>0?n.getWeightedScore(a):i.rawScore;return{goalId:e,reward:d,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0},calibrationFactors:l,source:"fallback",confidence:.3,computedAt:r}}function Ct(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as it}from"uuid";de();function se(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function rt(e){w().prepare(`
42
- INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
43
- alpha, beta, total_trials, avg_reward, created_at, updated_at)
44
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
45
- `).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function nt(e){let r=w().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?se(r):void 0}function hn(e=100){return w().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(se)}function ot(e){return w().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(se)}function L(e,t){return w().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(se)}function at(e,t){w().prepare(`
46
- UPDATE strategies
47
- SET alpha = alpha + ?,
48
- beta = beta + ?,
49
- total_trials = total_trials + 1,
50
- avg_reward = CASE
51
- WHEN total_trials = 0 THEN ?
52
- ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
53
- END,
54
- updated_at = ?
55
- WHERE id = ?
56
- `).run(t,1-t,t,t,Date.now(),e)}var B=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),a=this.sampleGamma(r,1);return n/(n+a)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,a=1/Math.sqrt(9*n);for(;;){let i,l;do i=this.randn(),l=1+a*i;while(l<=0);l=l*l*l;let d=Math.random();if(d<1-.0331*i*i*i*i||Math.log(d)<.5*i*i+n*(1-l+Math.log(l)))return n*l/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let a of t){let i=this.sampleBeta(a.alpha,a.beta);i>n&&(n=i,r=a)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let i=0;i<r;i++){let l=this.sample(t);l&&n.set(l.id,(n.get(l.id)||0)+1)}let a=new Map;for(let[i,l]of n)a.set(i,l/r);return a}};var Pt=5,Ie=20,st=.5,k=class{static selectStrategy(t,r){let n=L(t,r);return B.sample(n)}static recordTrial(t,r,n,a,i,l,d){at(t,a),et({id:it(),strategyId:t,goalId:r,taskId:n,reward:a,metricL2Score:i,metricL3Score:l,context:d,completedAt:Date.now()})}static getStrategies(t,r){return L(t,r)}static getStrategyById(t){return nt(t)}static getPopulationStats(t,r){let n=L(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let i=n.reduce((u,c)=>u+c.totalTrials,0)/n.length,l=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),d=l.length>0?l.reduce((u,c)=>u+c,0)/l.length:0;return{count:n.length,avgTrials:i,avgReward:d,minTrials:Math.min(...n.map(u=>u.totalTrials)),maxTrials:Math.max(...n.map(u=>u.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Pt?!0:n.count<Ie&&n.maxTrials>0}static addStrategy(t,r,n,a){if(L(t,r).length>=Ie)throw new Error(`Strategy population at maximum (${Ie}) for ${t}/${r}`);let l={id:`strat-${it().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:a,alpha:st,beta:st,totalTrials:0,createdAt:Date.now()};return rt(l),l}static getTopStrategies(t,r,n=3){let i=L(t,r).filter(l=>l.totalTrials>0);return i.sort((l,d)=>(d.avgReward??0)-(l.avgReward??0)),i.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return B.getProbabilities(n)}static evaluateAndRecord(t,r,n,a,i,l){let d=ie(r,n);return this.recordTrial(t,r,n,d.reward,a,i,l),d.reward}};var Lt=3,Et=2,le=class{static async generateVariants(t,r,n=Lt,a=Et){let i=k.getTopStrategies(t,r,n);if(i.length===0){let d=`baseline-${r}-v1`;return k.addStrategy(t,r,d,this.generateBaselinePrompt(t,r)),[d]}let l=[];for(let d=0;d<a;d++){let u=i[0].totalTrials+d+1,c=`${r}-evolved-v${u}`,m=i[0].promptTemplate,f=this.mutateTemplate(m);k.addStrategy(t,r,c,f),l.push(c)}return l}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
57
-
58
- ## Core Focus
59
- Complete tasks with high quality.
60
-
61
- ## Approach
62
- 1. Understand the task requirements thoroughly
63
- 2. Plan your approach before executing
64
- 3. Execute systematically, checking your work
65
- 4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
66
-
67
- ## Evolution
68
- ${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};$();Fe();import{v4 as I}from"uuid";import{spawnSync as lt}from"child_process";import{createRequire as Dt}from"module";import{dirname as At,join as ct}from"path";import{openSync as Nt,readFileSync as Ut,unlinkSync as $t}from"fs";var Ot=3e4,dt=12e4;function ut(){let t=Dt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return ct(At(t),"cli.js")}function q(e,t){let r=ut(),n=t?.timeout??Ot;if(t?.json){let i=ct("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),l=Nt(i,"w");try{let d=lt("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",l,"pipe"],encoding:"utf-8"});if(d.status!==0)throw new Error(d.stderr?.trim()||`CLI exited with status ${d.status}`);return Ut(i,"utf-8")}finally{try{$t(i)}catch{}}}let a=lt("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(a.status!==0)throw new Error(a.stderr?.trim()||`CLI exited with status ${a.status}`);return a.stdout}function pt(){let e=q(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function Te(e,t="user",r){return q(["plugin","install",e,"--scope",t],{cwd:r,timeout:dt})}function Se(e,t,r){let n=["plugin","uninstall",e];return t&&n.push("--scope",t),q(n,{cwd:r,timeout:dt})}function mt(e,t){return q(["plugin","enable",e])}function gt(e,t){return q(["plugin","disable",e])}function Ln(){try{return!!ut()}catch{return!1}}$();import*as ft from"crypto";var W=S("api"),J=class{cancelTask(t){let r=y(t);r&&(O(t,{status:"cancelled",completedAt:Date.now()}),fe.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),W.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return W.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,a){let i=Ee(t);if(!i)return W.warn({planId:t},"Plan not found or already resolved"),!1;let l=y(i.taskId);return l?(De(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&Ae({id:ft.randomUUID(),roleId:i.roleId,taskPattern:l.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:l.id}),fe.emit({type:"plan_approval_decision",taskId:l.id,planId:t,decision:r,approvalType:n,reason:a}),W.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(W.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as bt}from"fs";function ht(e,t){return t?{allowedTools:Ft(t.allowedTools,e.allowedTools),disallowedTools:ke(e.disallowedTools,t.disallowedTools),approvalRequired:ke(e.approvalRequired,t.approvalRequired),maxBudgetUsd:t.maxBudgetUsd!==void 0&&t.maxBudgetUsd>0?Math.min(t.maxBudgetUsd,e.maxBudgetUsd):e.maxBudgetUsd,plugins:ke(e.plugins??[],t.plugins)}:{allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,approvalRequired:e.approvalRequired,maxBudgetUsd:e.maxBudgetUsd,plugins:e.plugins??[]}}function Ft(e,t){if(e===void 0)return t;if(e.length===0)return[];if(t.length===0)return e;let r=new Set(t);return e.filter(n=>r.has(n))}function ke(e,t){return t===void 0?e:[...new Set([...e,...t])]}vt();var H=S("manager");function s(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function R(e){let{listChannels:t}=await import("./channels-PUOPR5Y2.js"),r=t(),{listSessions:n}=await import("./session-manager-PWJLU6KZ.js"),a=[...n("active"),...n("archived")],i=[];for(let l of e)if(l.type==="session"&&l.sessionId)i.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,u=l.chatId;if(!d&&l.channelName){let c=r.find(m=>m.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!u){let c=a.find(m=>m.source.type==="channel"&&m.source.channelId===d&&m.source.chatId);c?.source.chatId?u=c.source.chatId:u=r.find(f=>f.id===d)?.config?.userId}d&&u?i.push({type:"channel",channelId:d,chatId:u}):H.warn({channelName:l.channelName,channelId:d,chatId:u},"Could not resolve channel notify target")}return i}async function Vt(e){let{listRoles:t}=await import("./roles-3AEHVOEW.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var Bt={goalId:o.string()},qt={goalId:o.string(),status:o.string().optional(),currentValue:o.number().optional(),budgetUsd:o.number().optional(),notes:o.string().optional()},Wt={goalId:o.string(),goalDescription:o.string(),maxSubtasks:o.number().optional()},_=o.union([o.object({type:o.literal("session"),sessionId:o.string()}),o.object({type:o.literal("channel"),channelName:o.string()}),o.object({type:o.literal("channel"),channelId:o.string(),chatId:o.string().optional()})]),Jt={prompt:o.string(),roleId:o.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:o.object({allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional()}).optional()},Ht={taskId:o.string(),goalId:o.string().optional(),strategyId:o.string().optional()},Yt={roleId:o.string(),taskType:o.string(),name:o.string().optional()},zt={status:o.string().optional(),limit:o.number().optional()},Kt={taskId:o.string(),roleId:o.string()},Qt={taskId:o.string().optional(),status:o.string().optional(),limit:o.number().optional()},Xt={roleId:o.string(),allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional(),osCapabilities:o.array(o.object({id:o.string().min(1),targets:o.array(o.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:o.array(o.object({path:o.string(),mode:o.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:o.boolean().optional(),inheritMcp:o.boolean().optional(),inheritPermissions:o.boolean().optional()})).optional(),allowedChannels:o.array(o.string()).optional(),inheritUserSettings:o.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Zt={roleId:o.string().describe("Role ID to update."),name:o.string().min(1).optional(),cagPrompt:o.string().optional(),learnedRules:o.array(o.string()).optional(),status:o.enum(["active","inactive","retired"]).optional(),executionMode:o.enum(["isolated","inline"]).optional(),model:o.string().optional(),maxBudgetUsd:o.number().optional(),approvalRequired:o.array(o.string()).optional(),preferences:o.object({model:o.string().optional(),effort:o.enum(["low","medium","high","max"]).optional(),maxTurns:o.number().optional()}).optional(),permissionMode:o.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:o.array(o.string()).optional(),deniedBashPatterns:o.array(o.string()).optional(),evaluationCriteria:o.record(o.string(),o.number()).optional(),envVars:o.record(o.string(),o.string()).optional()},er={roleId:o.string().optional(),limit:o.number().optional()},tr={name:o.string(),cagPrompt:o.string(),traits:o.array(o.string()).optional(),allowedTools:o.array(o.string()).optional(),disallowedTools:o.array(o.string()).optional(),osCapabilities:o.array(o.object({id:o.string().min(1),targets:o.array(o.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:o.array(o.object({path:o.string(),mode:o.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:o.boolean().optional(),inheritMcp:o.boolean().optional(),inheritPermissions:o.boolean().optional()})).optional()},rr={roleId:o.string(),reason:o.string().optional()},nr={name:o.string(),description:o.string().optional(),roleId:o.string().optional(),metric:o.string().optional(),targetValue:o.number().optional(),deadline:o.number().optional(),budgetUsd:o.number().optional(),deliverTo:o.array(_).optional().describe("Where to deliver goal completion notifications.")},or={name:o.string(),description:o.string().optional(),triggerType:o.enum(["cron","event"]),triggerCron:o.string().optional(),triggerEvent:o.string().optional(),prompt:o.string(),roleId:o.string().optional(),enabled:o.boolean().optional(),goalIds:o.array(o.string()).optional(),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text)."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary).")},ar={status:o.enum(["active","retired","probation"]).optional(),limit:o.number().optional()},ir={enabled:o.boolean().optional()},sr={},lr={},cr={prompt:o.string().describe("The task prompt to execute after the delay"),delayMinutes:o.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:o.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:o.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:o.array(_).optional().describe("Where to deliver the task output (result full text)."),reportTo:o.array(_).optional().describe("Where to send status reports (completion summary).")},dr={roleId:o.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},ur={roleId:o.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:o.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},pr={roleId:o.string().describe("Role ID to uninstall the plugin from."),pluginId:o.string().describe("Plugin ID to uninstall.")},mr={roleId:o.string().describe("Role ID to bind the MCP server to."),mcpName:o.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:o.record(o.string(),o.unknown()).describe("MCP server configuration object.")},gr={roleId:o.string().describe("Role ID to unbind the MCP server from."),mcpName:o.string().describe("Name of the MCP server to remove.")},fr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},hr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},br={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},yr={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},wr={},vr={},Ir={pluginId:o.string().describe("Plugin ID (e.g., 'github@anthropic').")},Tr={roleId:o.string().describe("Role ID to associate scanned plugins with."),path:o.string().describe("Directory path to scan for .claude/settings.json.")},Sr={taskId:o.string().describe("Task ID to cancel.")},kr={taskId:o.string().describe("Task ID to get logs for."),limit:o.number().optional().describe("Max log entries (default 20).")},Rr={roleId:o.string().describe("Role ID to delete.")},_r={},Mr={updates:o.record(o.string(),o.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},xr={roleId:o.string().describe("Role ID to list memories for."),limit:o.number().optional().describe("Max results (default 20).")},Cr={templateId:o.string().describe("Template ID to update."),name:o.string().optional(),enabled:o.boolean().optional(),prompt:o.string().optional(),triggerCron:o.string().optional(),triggerEvent:o.string().optional(),roleId:o.string().optional()},Pr={templateId:o.string().describe("Template ID to delete.")},Lr={templateId:o.string().describe("Template ID to run immediately.")},Er={enabled:o.boolean().optional().describe("Filter by enabled status.")},Dr={eventType:o.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:o.string().describe("Channel ID to deliver to."),format:o.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:o.record(o.string(),o.unknown()).optional().describe("JSON match criteria for event fields."),enabled:o.boolean().optional().describe("Enable this rule immediately (default true).")},Ar={ruleId:o.string().describe("Delivery rule ID to delete.")},Nr={roleId:o.string().optional().describe("Role ID to filter strategies by.")},yt=[p("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",Bt,async e=>{let t=x(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),p("update_goal_state","Update a goal's status, current value, or budget.",qt,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),te(e.goalId,t)),s({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Wt,async e=>{let t=T(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),i=`Decompose this goal into ${r} actionable subtasks.
69
-
70
- Goal: ${e.goalDescription}
71
-
72
- Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
73
-
74
- Rules:
75
- - Each subtask must be independently executable
76
- - Order from foundational to dependent
77
- - Be specific about what each subtask should accomplish
78
- - For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,l=a({prompt:i,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),d="";for await(let c of l){let m=c;m.type==="result"&&typeof m.result=="string"&&(d=m.result)}let u=d.match(/\[[\s\S]*\]/);if(u){let c=JSON.parse(u[0]),m=[];for(let f=0;f<Math.min(c.length,r);f++){let h=c[f],U=`subtask-${I().slice(0,8)}`,C=h.role,g=C?await Vt(C):void 0;Y({id:U,status:"pending",prompt:h.prompt,parentId:e.goalId,roleId:g,config:t.defaults,createdAt:Date.now()}),m.push({id:U,description:h.description,prompt:h.prompt,dependencies:f>0?[m[f-1].id]:[],estimatedComplexity:h.complexity??"medium",role:C})}if(m.length>0)return s({subtasks:m})}}catch(a){H.error({error:a},"LLM decomposition failed, using fallback")}let n=[];for(let a=0;a<r;a++){let i=`subtask-${I().slice(0,8)}`,l=`Subtask ${a+1} of goal: ${e.goalDescription.slice(0,100)}`,d=`${e.goalDescription}
79
-
80
- Subtask ${a+1}/${r}`;Y({id:i,status:"pending",prompt:d,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:i,description:l,prompt:d,dependencies:a>0?[n[a-1].id]:[],estimatedComplexity:"medium"})}return s({subtasks:n})}),p("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Jt,async e=>{let t=v(e.roleId);if(!t||t.status!=="active"){let ce=A("active",20,0).filter(M=>M.source!=="system").map(M=>({id:M.id,name:M.name,allowedTools:M.allowedTools??[],capabilitySummary:N(M)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:ce})}let r=I(),n=T(),a=e.prompt.toLowerCase(),i={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},l="general";for(let[ce,M]of Object.entries(i))if(M.some(wt=>a.includes(wt))){l=ce;break}let d,u=e.prompt,c=k.selectStrategy(e.roleId,l);c?.promptTemplate&&(u=`${c.promptTemplate}
81
-
82
- ## Task
83
- ${e.prompt}`,d=c.id);let m=t?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools,approvalRequired:t.approvalRequired,maxBudgetUsd:t.maxBudgetUsd,plugins:void 0}:void 0,f=ht(n.defaults,m),h=f.allowedTools;e.toolOverrides?.allowedTools&&(h=[...e.toolOverrides.allowedTools]);let U={...n.defaults,...f,allowedTools:h,disallowedTools:e.toolOverrides?.disallowedTools??f.disallowedTools},C=e.deliverTo?await R(e.deliverTo):void 0,g=e.reportTo?await R(e.reportTo):void 0;Y({id:r,status:"pending",prompt:u,roleId:e.roleId,deliverTo:C,reportTo:g,config:U,createdAt:Date.now()});let{serverBus:b}=await import("./server-bus-GEGVMSCA.js");return b.emit({type:"task_created",taskId:r}),s({taskId:r,roleId:e.roleId,strategyId:d})}),p("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:o.array(o.object({id:o.string().describe("Unique step identifier"),prompt:o.string().describe("Task prompt for this step"),roleId:o.string().describe("Role ID for this step. Call list_roles first to find roles."),dependsOn:o.array(o.string()).optional().describe("Step IDs this step depends on"),config:o.object({timeout:o.number().optional(),maxTurns:o.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:o.string().optional().describe("Workflow name for tracking"),deliverTo:o.array(_).optional().describe("Where to deliver the aggregated workflow output"),reportTo:o.array(_).optional().describe("Where to send workflow status reports"),continueOnError:o.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let g of e.steps){let b=v(g.roleId);(!b||b.status!=="active")&&t.push(g.roleId)}if(t.length>0){let g=A("active",20,0).filter(b=>b.source!=="system").map(b=>({id:b.id,name:b.name,capabilitySummary:N(b)}));return s({error:`Invalid or inactive roles: ${t.join(", ")}. Pick from available roles.`,availableRoles:g})}let r=new Set(e.steps.map(g=>g.id));for(let g of e.steps)if(g.dependsOn)for(let b of g.dependsOn){if(!r.has(b))return s({error:`Step "${g.id}" depends on unknown step "${b}"`});if(b===g.id)return s({error:`Step "${g.id}" cannot depend on itself`})}let n=new Set,a=new Set,i=new Map(e.steps.map(g=>[g.id,g.dependsOn??[]])),l=g=>{if(a.has(g))return!0;if(n.has(g))return!1;n.add(g),a.add(g);for(let b of i.get(g)??[])if(l(b))return!0;return a.delete(g),!1};for(let g of e.steps)if(l(g.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await R(e.deliverTo):void 0,u=e.reportTo?await R(e.reportTo):void 0,c=I(),m=T(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(g=>({id:g.id,prompt:g.prompt,roleId:g.roleId,dependsOn:g.dependsOn,config:g.config})),enabled:!0,createdAt:Date.now(),config:{...m.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:u};he(f);let{WorkflowExecutor:h}=await import("./workflow-executor-XFTTJQNE.js");new h().execute(f,c).catch(g=>{H.error({executionId:c,error:g},"dispatch_workflow execution failed")});let C=e.steps.map(g=>v(g.roleId)?.name??g.roleId);return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(C)],status:"started"})}),p("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Ht,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,a=ie(t??"",r);return n&&t&&k.recordTrial(n,t,r,a.reward,a.breakdown.L2||void 0,a.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:a.reward,metricL2Score:a.breakdown.L2||void 0,metricL3Score:a.breakdown.L3||void 0,source:a.source,reasoning:`Evaluated via ${a.source} with confidence ${a.confidence.toFixed(2)}`})}),p("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Yt,async e=>{let{roleId:t,taskType:r}=e;await le.generateVariants(t,r,3,1);let n=k.getStrategies(t,r),a=n[n.length-1];return s(a?{id:a.id,name:a.name,promptTemplate:a.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),p("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",zt,async e=>{let t=e.status;return s(We(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:o.string()},async e=>x(e.goalId)?(Je(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),p("pause_goal","Pause an active goal.",{goalId:o.string()},async e=>x(e.goalId)?(te(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),p("assign_role","Assign a role to a pending task.",Kt,async e=>{let{taskId:t,roleId:r}=e;if(!y(t))return s({error:`Task not found: ${t}`});let a=v(r);return a?(O(t,{roleId:r}),H.debug({taskId:t,roleId:r,roleName:a.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...He(),p("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",Qt,async e=>{if(e.taskId){let r=y(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(E(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Xt,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=ue(e.osCapabilities)}catch(n){return s({error:n instanceof Error?n.message:String(n)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),D(e.roleId,r),s({success:!0})}),p("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Zt,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...n}=e,a={...n,updatedAt:Date.now()};D(r,a);let i=v(r);if(!i)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=Pe(i.name);bt(l)&&Le(l,i)}return s({success:!0,role:i})}),p("view_audit_log","View the evolution audit log for role changes.",er,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-JZ2U7J4C.js"),r=t(e.limit??50);return s({entries:r})}),p("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",ar,async e=>{let r=A(e.status,e.limit??50,0).map(n=>{let a=we(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],osCapabilities:n.osCapabilities??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:N(n,a),plugins:a.plugins.map(i=>({name:i.name,skills:i.skills.map(l=>l.name),agents:i.agents.map(l=>l.name)}))}});return s({roles:r})}),p("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",tr,async e=>{let t;try{t=ue(e.osCapabilities)}catch(a){return s({error:a instanceof Error?a.message:String(a)})}let r=`role-${I().slice(0,8)}`,n={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${I().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return xe(n),Q(n),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:n.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),p("retire_role","Retire a role (marks as retired, stops receiving tasks).",rr,async e=>v(e.roleId)?(D(e.roleId,{status:"retired"}),H.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),p("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",nr,async e=>{let t=I(),r=Date.now(),n=r+10080*60*1e3,a={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};ee(a),Ze(t,a.metricType);let i=x(t);return s({goalId:i.id,name:i.name,status:i.status})}),p("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",or,async e=>{let{createTaskTemplate:t}=await import("./task-templates-ED2UCUPE.js"),r=I(),n=I(),a=e.deliverTo?await R(e.deliverTo):void 0,i=e.reportTo?await R(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:a,reportTo:i};return t(l),s({templateId:r,name:l.name,trigger:l.trigger})}),p("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:o.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:o.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-ED2UCUPE.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),p("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:o.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:o.string().describe("The message content to send (text caption when sending media)"),mediaUrl:o.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:o.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!bt(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-U5LP54JG.js"),i=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:i.success,channelName:e.channelName,...i.error?{error:i.error}:{}})}),p("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",ir,async e=>{let t=be(e.enabled),r=[...ye("active"),...ye("archived")],n=t.map(a=>{let i,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===a.id&&d.source.chatId);return l?.source.chatId?i=l.source.chatId:i=a.config?.userId,{id:a.id,name:a.name,platform:a.platform,status:a.status,chatId:i}});return s({channels:n})}),p("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",sr,async()=>{let e=T(),t=E("running"),r=E("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),p("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",cr,async e=>{let t=v(e.roleId);if(!t||t.status!=="active"){let f=A("active",20,0).filter(h=>h.source!=="system").map(h=>({id:h.id,name:h.name,allowedTools:h.allowedTools??[],capabilitySummary:N(h)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(n<=r)return s({error:"Scheduled time must be in the future"});let a=10080*60*1e3;if(n-r>a)return s({error:"Schedule exceeds maximum of 7 days"});let i=I(),l=new Date(n).toISOString(),d=e.deliverTo?await R(e.deliverTo):void 0,u=e.reportTo?await R(e.reportTo):void 0;he({id:i,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...T().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:u});let{getBreeEngine:c}=await import("./bree-engine-CRK73AI4.js"),m=c();return m&&m.scheduleOnceJob(i),s({templateId:i,executeAt:l,prompt:e.prompt})}),p("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:o.string().describe("The template ID returned by schedule_task")},async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Be(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-CRK73AI4.js"),n=r();return n&&await n.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),p("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",dr,async e=>{let t=Ne(),r=Z(),n=e.roleId?(()=>{let{getRoleWorkspacePath:a}=(X(),P(me)),{getRole:i}=(K(),P(pe)),{listInstalledPlugins:l}=(Fe(),P(It)),d=i(e.roleId);if(!d)return[];let u=a(d.name);return l({scope:"project",projectPath:u}).map(c=>c.id)})():[];return s({plugins:r.map(a=>({id:a.id,name:a.name,scope:a.scope,projectPath:a.projectPath,enabled:a.enabled,globalEnabled:t[a.id]??a.enabled,isInstalledInRole:n.includes(a.id),description:a.version?`v${a.version}`:void 0}))})}),p("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",ur,async e=>{let{getRole:t}=(K(),P(pe)),{getRoleWorkspacePath:r}=(X(),P(me)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let a=r(n.name);try{return Te(e.pluginId,"project",a),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:a})}catch(i){return s({error:`Failed to install plugin: ${i}`})}}),p("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",pr,async e=>{let{getRole:t}=(K(),P(pe)),{getRoleWorkspacePath:r}=(X(),P(me)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let a=r(n.name);try{return Se(e.pluginId,"project",a),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(i){return s({error:`Failed to uninstall plugin: ${i}`})}}),p("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",mr,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return D(e.roleId,{mcpServers:n}),Q(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(a){return s({error:`Failed to bind MCP server: ${a}`})}}),p("unbind_mcp_from_role","Remove an MCP server binding from a role.",gr,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return D(e.roleId,{mcpServers:r}),Q(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return s({error:`Failed to unbind MCP server: ${n}`})}}),p("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",lr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-ED2UCUPE.js"),t=T(),r=A(void 0,100,0),n=be(),a=e(!0,100,0),i=E("running"),l=E("pending"),d=Ke(),u=await Qe();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let m=we(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:N(c,m),plugins:m.plugins.map(f=>({name:f.name,skills:f.skills.map(h=>h.name),agents:f.agents.map(h=>h.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:u},registry:Me(d.platform,u)},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:Z().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:a.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:i.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),p("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",fr,async e=>{try{return mt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),p("disable_plugin","Disable a globally installed plugin (removes it from all roles).",hr,async e=>{try{return gt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),p("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",br,async e=>{try{return Te(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),p("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",yr,async e=>{try{return Se(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),p("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",wr,async()=>{try{let e=pt(),t=Z();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),p("list_marketplace_sources","List configured plugin marketplace sources.",vr,async()=>{let e=Oe();return s({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Ir,async e=>{let t=$e(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=Ue(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),p("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Tr,async e=>{let{getRole:t}=await import("./roles-3AEHVOEW.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let n=je(e.path);return s({roleId:e.roleId,path:e.path,config:n})}catch(n){return s({error:`Failed to scan directory: ${n}`})}}),p("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Sr,async e=>{let t=y(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;O(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),p("view_task_logs","Retrieve step-by-step execution logs for a task.",kr,async e=>{let t=z(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),p("delete_role","Delete a role by ID. This removes the role and its workspace.",Rr,async e=>v(e.roleId)?(Ce(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),p("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",_r,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-VDBZZ4KG.js"),r=T(),n={};try{let d=T().server?.port??7100,u=await fetch(`http://127.0.0.1:${d}/config`);u.ok&&(n=await u.json())}catch{}let a=[...e,...t],i=[...t],l={};for(let d of a){let u=d.split("."),c=r;for(let m of u)if(c&&typeof c=="object")c=c[m];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),p("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Mr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-VDBZZ4KG.js"),{setConfigValue:r}=await import("./config-CBNOT66B.js"),n=Re(e.updates,r);if(e.updates["logging.level"]&&_e(e.updates["logging.level"]),n.updated.length>0){let{serverBus:a}=await import("./server-bus-GEGVMSCA.js");a.emit({type:"config_changed",changes:n.updated.map(i=>({path:i,value:e.updates[i]}))})}return s(n)}),p("list_memories","List memories stored under a specific role.",xr,async e=>{let t=Ge(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),p("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Cr,async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:I(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),Ve(e.templateId,r),s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",Pr,async e=>j(e.templateId)?(qe(e.templateId),s({success:!0,templateId:e.templateId})):s({error:`Template not found: ${e.templateId}`})),p("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Lr,async e=>{let t=j(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=T().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),a=await n.json();return n.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:a}):s({error:`Webhook failed: ${a.code??n.status} \u2014 ${a.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),p("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",Er,async e=>{let t=ve(e.enabled);return s({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Dr,async e=>{let t=I(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return Ye(r),s({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",Ar,async e=>ve().find(n=>n.id===e.ruleId)?(ze(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),p("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",Nr,async e=>{let t;if(e.roleId)t=ot(e.roleId);else{let{getDb:r}=await import("./db-XQUI4IBL.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(a=>({id:a.id,roleId:a.role_id,name:a.name,taskType:a.task_type,createdAt:a.created_at,updatedAt:a.updated_at??void 0,promptTemplate:a.prompt_template??"",alpha:a.alpha,beta:a.beta,totalTrials:a.trials,avgReward:a.total_reward&&a.trials>0?a.total_reward/a.trials:void 0,enabled:a.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),p("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:o.string(),operationId:o.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:o.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=ge(e.taskId),r=e.operationId?t.find(a=>a.id===e.operationId):t.find(a=>a.status==="pending");return r?(new J().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),p("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:o.string(),operationId:o.string().optional(),reason:o.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=ge(e.taskId),r=e.operationId?t.find(a=>a.id===e.operationId):t.find(a=>a.status==="pending");return r?(new J().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function fo(){return yt.map(e=>e.name).sort().join(",")}function ho(){return Gt({name:"adam-tools",version:"1.0.0",tools:yt})}export{J as a,Br as b,qr as c,Ze as d,hn as e,ot as f,k as g,pt as h,Te as i,Se as j,mt as k,gt as l,Ln as m,fo as n,ho as o};
@@ -1,19 +0,0 @@
1
- import{f as s,j as w}from"./chunk-24GTCFEV.js";import{j as i,k as f,n as g,q as y}from"./chunk-J3NIPZ73.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
- Capabilities: Read, write, and edit code; run shell commands; search codebases.
3
- Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
4
- Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
5
- Constraints: No web access. Works only within the assigned workspace directory.`,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{code_quality:4,test_pass:4,build_success:3},executionMode:"isolated"},{name:"Reviewer",cagPrompt:`Role: Code reviewer and security auditor. READ-ONLY \u2014 you do not modify files.
6
- Capabilities: Read files, search code, run analysis commands (linters, type-checkers, test suites).
7
- Approach: Systematically review code for bugs, security issues, performance problems, and style violations. Output structured findings with file:line references.
8
- Best for: Code review, security audit, dependency audit, test coverage analysis.
9
- Constraints: No Write or Edit tools. Cannot modify code \u2014 only report findings.`,allowedTools:["Read","Grep","Glob","Bash"],evaluationCriteria:{bug_detection_rate:5,insight_quality:4},executionMode:"isolated"},{name:"Researcher",cagPrompt:`Role: Information researcher and analyst with web access.
10
- Capabilities: Search the web, fetch web pages, read local files, run data processing scripts.
11
- Approach: Gather information from multiple sources \u2192 cross-reference \u2192 synthesize findings into structured reports.
12
- Best for: Market research, technical investigation, API documentation lookup, competitive analysis, news monitoring.
13
- Constraints: No file write/edit permissions. Cannot modify the codebase \u2014 only research and report.`,allowedTools:["WebSearch","WebFetch","Read","Grep","Glob","Bash"],evaluationCriteria:{insight_quality:5,data_accuracy:5},executionMode:"isolated"},{name:"Writer",cagPrompt:`Role: Content writer and document generator.
14
- Capabilities: Create and edit text files, read reference material, search for context.
15
- Approach: Understand the target audience and format \u2192 draft \u2192 refine. Match the project's existing tone and terminology.
16
- Best for: Documentation, reports, emails, translations, summaries, changelog entries.
17
- Constraints: No shell command execution. No web access. Works only with file read/write operations.`,allowedTools:["Read","Write","Edit","Grep","Glob"],evaluationCriteria:{content_quality:5,engagement:4},executionMode:"isolated"}];function M(){R();let r=g(void 0,1e3,0),o=new Set(l.map(e=>e.name)),d=r.filter(e=>o.has(e.name));if(d.length>0)return t.info({count:d.length},"Default roles already exist, skipping"),r;t.info({count:l.length},"Creating default roles");let u=[];for(let e of l){let m=`role-${c().slice(0,8)}`,n={id:m,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,evaluationCriteria:e.evaluationCriteria,executionMode:e.executionMode};i(n),u.push(n),s(n),t.info({roleId:m,name:e.name},"Created default role")}return u}function R(){if(f(a)){t.debug({roleId:a},"ChatManager system role already exists");return}let o={id:a,name:"Chat Manager",cagPrompt:`You are the Chat Manager \u2014 orchestrating conversations and managing agent interactions.
18
- You coordinate between user requests and agent execution, maintaining conversation context
19
- and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,M as b};