adam-agent-server 1.6.0 → 1.7.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 (96) hide show
  1. package/dist/App-ZRCRM7WR.js +13 -0
  2. package/dist/{adam-automator-skills-UFW5TXCC.js → adam-automator-skills-EZGBICHT.js} +1 -1
  3. package/dist/adam-tools-V5LPU47X.js +1 -0
  4. package/dist/{approval-handler-HQO62WK2.js → approval-handler-PB7PSLUS.js} +1 -1
  5. package/dist/audit-manager-BSBBDUER.js +1 -0
  6. package/dist/bree-engine-7S33CWS7.js +1 -0
  7. package/dist/channels-SITUUC4J.js +1 -0
  8. package/dist/{channels-J4STJ4X2.js → channels-ULFUCUUZ.js} +1 -1
  9. package/dist/{chunk-7446ZS6D.js → chunk-2L2347UQ.js} +1 -1
  10. package/dist/{chunk-FXQAUQTI.js → chunk-2YTDCR6A.js} +1 -1
  11. package/dist/chunk-4PQHGLZH.js +99 -0
  12. package/dist/{chunk-NCFVJCNQ.js → chunk-5EPG2US5.js} +2 -2
  13. package/dist/{chunk-2H7UOW4P.js → chunk-5QZXYKMS.js} +1 -1
  14. package/dist/chunk-5XOTPEAK.js +6 -0
  15. package/dist/{chunk-MDBVKBC7.js → chunk-6KF7OO2B.js} +1 -1
  16. package/dist/{chunk-TSPQ44HT.js → chunk-A5OCDYTW.js} +1 -1
  17. package/dist/{chunk-DWRYIN5N.js → chunk-AQ3ASS4B.js} +1 -1
  18. package/dist/{chunk-GMMWA5EG.js → chunk-B6LOT5CG.js} +1 -1
  19. package/dist/{chunk-MJSSCKMB.js → chunk-BCH2HAIM.js} +2 -2
  20. package/dist/{chunk-4C5ITATX.js → chunk-BQ3ZAYHC.js} +1 -1
  21. package/dist/{chunk-YHVYX3F4.js → chunk-DVN3BFPP.js} +1 -1
  22. package/dist/{chunk-P5ZXNBNV.js → chunk-EQZFOBAJ.js} +1 -1
  23. package/dist/{chunk-G5ESQEXN.js → chunk-FPZEZYUB.js} +1 -1
  24. package/dist/{chunk-YXYIA24D.js → chunk-GSFLLRS7.js} +1 -1
  25. package/dist/{chunk-7ZGSJCX5.js → chunk-HQRUJQN7.js} +1 -1
  26. package/dist/{chunk-52PR7XTN.js → chunk-IKPYPZ64.js} +1 -1
  27. package/dist/{chunk-FZCNYKNT.js → chunk-JJH2RCVC.js} +1 -1
  28. package/dist/chunk-K4C43YDD.js +7 -0
  29. package/dist/{chunk-V32YF3J5.js → chunk-M4YI4WVX.js} +1 -1
  30. package/dist/{chunk-WAG3MNMC.js → chunk-NASJH4NT.js} +1 -1
  31. package/dist/{chunk-TNL2LZB7.js → chunk-NUITL62I.js} +1 -1
  32. package/dist/{chunk-3LY6PD6A.js → chunk-NWMOV23A.js} +1 -1
  33. package/dist/chunk-PHT24MOV.js +1 -0
  34. package/dist/{chunk-ZL5JXLAX.js → chunk-QGYDGZSC.js} +1 -1
  35. package/dist/{chunk-VVSZZK5T.js → chunk-RI3V72RP.js} +2 -2
  36. package/dist/{chunk-RLJYEEQC.js → chunk-RZ7LCZVK.js} +1 -1
  37. package/dist/{chunk-5OQZPUBV.js → chunk-TAF2DBBC.js} +8 -8
  38. package/dist/{chunk-HWLSHTVX.js → chunk-ULTK7RD6.js} +3 -3
  39. package/dist/{chunk-DBP7GPWG.js → chunk-WMB7P64J.js} +1 -1
  40. package/dist/cli.js +2 -2
  41. package/dist/{config-KFPS7IEH.js → config-HBQPBIWL.js} +1 -1
  42. package/dist/{db-PZ2V7UCK.js → db-QEWTZGU3.js} +1 -1
  43. package/dist/{delivery-log-ACNJ66RD.js → delivery-log-AC476GX7.js} +1 -1
  44. package/dist/engine-6K4RG644.js +1 -0
  45. package/dist/{evolution-audit-OQDGPKYI.js → evolution-audit-XMBDUN3T.js} +1 -1
  46. package/dist/index.js +13 -10
  47. package/dist/{learner-QCD6BH2J.js → learner-VCS3Q7BR.js} +1 -1
  48. package/dist/{memories-QGMRSBJJ.js → memories-VMOGFVPU.js} +1 -1
  49. package/dist/{memory-extractor-3MRK43A2.js → memory-extractor-4WJNHYWR.js} +2 -2
  50. package/dist/memory-service-ZS6MBUIC.js +1 -0
  51. package/dist/outbound-gateway-H7RFG6D2.js +1 -0
  52. package/dist/role-presets-XAEOYEAW.js +1 -0
  53. package/dist/role-workspace-NKGAH6J6.js +1 -0
  54. package/dist/{roles-KYXNMO5H.js → roles-ZYCFQMAY.js} +1 -1
  55. package/dist/{session-manager-LZ77OT7A.js → session-manager-COLCNIB7.js} +1 -1
  56. package/dist/task-templates-4KCZOUN5.js +1 -0
  57. package/dist/workflow-executor-Z7JFMR56.js +1 -0
  58. package/package.json +25 -25
  59. package/web/dist/assets/{ChannelDetail-DHT8fW0C.js → ChannelDetail-DnL0_h8q.js} +1 -1
  60. package/web/dist/assets/{Channels-YHGNXcRu.js → Channels-dod8Q4oq.js} +1 -1
  61. package/web/dist/assets/{Dashboard-DsHC5W4C.js → Dashboard-Dl0vA6Ky.js} +1 -1
  62. package/web/dist/assets/{EnvVarEditor-Dxy1Kz1Z.js → EnvVarEditor-C-gErAzC.js} +1 -1
  63. package/web/dist/assets/{EventDefDetail-CwprP2ch.js → EventDefDetail-BhJZGNlX.js} +1 -1
  64. package/web/dist/assets/{Events-B19a8cEG.js → Events-DnNZ9-BN.js} +1 -1
  65. package/web/dist/assets/{Evolution-DT6iZvil.js → Evolution-BBWmrrnr.js} +1 -1
  66. package/web/dist/assets/{GoalDetail-BALsnPQl.js → GoalDetail-uqWQCOj3.js} +1 -1
  67. package/web/dist/assets/{Goals-BJIsKgfH.js → Goals-CylKmR9j.js} +1 -1
  68. package/web/dist/assets/{Logs-Cv15aV3l.js → Logs-6rf0KT0z.js} +1 -1
  69. package/web/dist/assets/{Memories-CKAXhAso.js → Memories-CrBTujU7.js} +1 -1
  70. package/web/dist/assets/{Plugins-NO0S2spH.js → Plugins-VKUSUcSE.js} +1 -1
  71. package/web/dist/assets/{RoleDetail-1FNyCD4u.js → RoleDetail-DJc4CWFN.js} +1 -1
  72. package/web/dist/assets/{Roles-grfjw2zy.js → Roles-6pmjn04G.js} +1 -1
  73. package/web/dist/assets/{Settings-9LRLfa_4.js → Settings-DW1jmrNj.js} +1 -1
  74. package/web/dist/assets/{Strategies-BMyd_7_5.js → Strategies-Bmke6qZo.js} +1 -1
  75. package/web/dist/assets/{Switch-CULsD-kC.js → Switch-CfTpXW9_.js} +1 -1
  76. package/web/dist/assets/{TaskDetail-C2yXy8gE.js → TaskDetail-CwJ_UKgt.js} +1 -1
  77. package/web/dist/assets/Work-DVdWNBEm.js +1 -0
  78. package/web/dist/assets/{index-qYKJGoIB.js → index-DYsO5Awn.js} +2 -2
  79. package/web/dist/index.html +1 -1
  80. package/dist/App-WJMHK5EO.js +0 -13
  81. package/dist/adam-tools-IAZSLWYB.js +0 -1
  82. package/dist/audit-manager-LC5EQXCI.js +0 -1
  83. package/dist/bree-engine-M5CZ6A62.js +0 -1
  84. package/dist/channels-5TFYQN5Z.js +0 -1
  85. package/dist/chunk-FIN36WAP.js +0 -99
  86. package/dist/chunk-GGIHDFRW.js +0 -6
  87. package/dist/chunk-I7ZZKPHE.js +0 -7
  88. package/dist/chunk-YDVTWPNA.js +0 -1
  89. package/dist/engine-5DHYHDAP.js +0 -1
  90. package/dist/memory-service-M5ADGITG.js +0 -1
  91. package/dist/outbound-gateway-QRL36F7K.js +0 -1
  92. package/dist/role-presets-DLO3XS54.js +0 -1
  93. package/dist/role-workspace-URSOBCDH.js +0 -1
  94. package/dist/task-templates-YPNWJOVV.js +0 -1
  95. package/dist/workflow-executor-3WMS2WV3.js +0 -1
  96. package/web/dist/assets/Work-dftf35Me.js +0 -1
@@ -1,13 +0,0 @@
1
- import{b as v,d as Qt,e as Go}from"./chunk-YDVTWPNA.js";import{a as Xt,f as Uo,h as Wo}from"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";import{Box as Ht,Text as Mt,useInput as js}from"ink";import{useState as Ks,useEffect as mo,useRef as No}from"react";import{createContext as rn,useContext as nn,useReducer as sn}from"react";import{jsx as cn}from"react/jsx-runtime";var an={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 ln(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=rn(null);function jo({children:e}){let[t,o]=sn(ln,an);return cn(Ho.Provider,{value:{state:t,dispatch:o},children:e})}function He(){let e=nn(Ho);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Ko,useRef as zo}from"react";var dn=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})},dn)};return(()=>{try{g=new Qt("/events"),g.on("task_status_change",()=>{}),g.on("approval_request",r=>{if(!m)return;let c=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:c.taskId,approvalId:c.approvalId,toolName:c.toolName,toolInput:c.toolInput,matchedPattern:c.matchedPattern}})}),g.on("plan_approval_request",r=>{if(!m)return;let c=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:c.taskId,planId:c.planId,roleId:c.roleId,plan:c.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 c=r,f=u.current;f&&(async()=>{try{let S=await v(`/tasks/${c.taskId}`);m&&S.sourceSessionId===f&&t({type:"SET_ACTIVE_TASK",taskId:c.taskId})}catch{}})()}),g.on("stats_update",r=>{if(!m)return;let c=r;t({type:"UPDATE_STATS",activeTasks:c.activeTasks,queuedTasks:c.queuedTasks,costToday:c.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 v("/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 un,useRef as mn,useState as Qo,useCallback as gn}from"react";function Yo(e){let[t,o]=Qo([]),[u,m]=Qo(!1),g=mn(null),a=gn(()=>{o([]),m(!1)},[]);return un(()=>{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 c=r;o(f=>[...f,{type:"tool_call",content:c.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:c.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let c=r;o(f=>[...f,{type:"tool_result",content:c.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let c=r;o(f=>[...f,{type:"error",content:c.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let c=r;o(f=>[...f,{type:"complete",content:c.result??"",timestamp:Date.now(),metadata:{cost:c.costUsd,turns:c.numTurns,duration:c.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 fn,useCallback as _t}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=_t(async()=>{try{let S=(await v("/chat/sessions?status=active")).sessions.find(h=>h.source.type==="tui");return S?To(S):null}catch{return null}},[]),i=_t(async()=>{try{let f=await v("/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=_t(async f=>{try{let S=await v("/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=_t(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),c=_t(async()=>{if(e)try{let f=await v(`/chat/sessions/${e.id}`);t(To(f.session))}catch{t(null)}},[e]);return fn(()=>{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:c,setSession:t}}import{useEffect as Jo,useRef as pn,useState as xn}from"react";function er(e){let[t,o]=xn(null),u=pn(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 Te,jsxs as Ct}from"react/jsx-runtime";var Tn=90;function tr({children:e}){return Te(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)<Tn,r=Ct(Yt,{children:[Te(Ae,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),Te(Ae,{dimColor:!0,children:" | "}),Te(Ae,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),Te(Ae,{children:` ${m}`}),Te(Ae,{dimColor:!0,children:" | "}),Te(Ae,{children:g.toLowerCase()})]}),c=Ct(Yt,{children:[Te(Ae,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),Te(Ae,{dimColor:!0,children:" | "}),Te(Ae,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&Ct(Yt,{children:[Te(Ae,{dimColor:!0,children:" | "}),Te(Ae,{children:a}),u&&Ct(Yt,{children:[Te(Ae,{dimColor:!0,children:" | "}),Te(Ae,{color:"yellow",children:"timeout"})]})]})]});return s?Ct(ho,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[Te(tr,{children:r}),Te(tr,{children:c})]}):Ct(ho,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[r,Te(Ae,{dimColor:!0,children:" | "}),c]})}import{Box as Zt,Text as Jt,useInput as yn}from"ink";import{useState as bo,useMemo as bn}from"react";import vn from"ink-text-input";var hn=[{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 hn.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 Lt}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=bn(()=>i?yo(s):[],[i,s]),c=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 yn((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}),Lt(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 Lt(Zt,{children:[eo(Jt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),Lt(Jt,{color:n?"cyan":"white",bold:n,children:["/",h.name]}),Lt(Jt,{dimColor:!0,children:[" \u2014 ",h.description]})]},h.name)})}),Lt(Zt,{borderStyle:"round",borderDimColor:!0,children:[eo(Jt,{bold:!0,children:"\u25B8 "}),eo(vn,{value:t,onChange:c,onSubmit:f,placeholder:"Type a message or / for commands..."})]})]})}import{Box as St,Text as we,useInput as Cn}from"ink";import{useState as Sn}from"react";import{jsx as $e,jsxs as je}from"react/jsx-runtime";function wn({content:e,expanded:t}){let o=e.split(`
2
- `);return o.length<=5?$e(we,{color:"green",children:e}):t?$e(we,{color:"green",children:e}):je(we,{color:"green",children:[o.slice(0,3).join(`
3
- `),`
4
- `,je(we,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function Bn({event:e,expanded:t}){switch(e.type){case"reasoning":return $e(St,{children:$e(we,{color:"gray",children:e.content})});case"tool_call":return $e(St,{children:je(we,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return je(St,{flexDirection:"column",children:[$e(we,{color:"blue",dimColor:!0,children:"[result]"}),$e(wn,{content:e.content,expanded:t})]});case"error":return $e(St,{children:je(we,{color:"red",children:["[error] ",e.content]})});case"complete":return je(St,{flexDirection:"column",marginTop:1,children:[e.content&&$e(we,{children:e.content}),$e(we,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&je(we,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&je(we,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&je(we,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function sr({events:e,isStreaming:t}){let[o,u]=Sn(!1),m=e.some(g=>g.type==="tool_result"&&g.content.split(`
5
- `).length>5);return Cn((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(we,{dimColor:!0,children:"Waiting for response..."}),e.map((g,a)=>$e(Bn,{event:g,expanded:o},a)),m&&$e(we,{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 En}from"react/jsx-runtime";function lr({messages:e}){return e.length===0?null:vo(ir,{flexDirection:"column",children:e.map((t,o)=>En(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 kn}from"ink";import{jsx as ze,jsxs as Vt}from"react/jsx-runtime";function cr({approval:e,onResolved:t}){return kn(o=>{o==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),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 Ft,Text as Be,useInput as In}from"ink";import{useState as An,useEffect as Pn}from"react";import{jsx as ot,jsxs as qe}from"react/jsx-runtime";var Dn=300;function dr({approval:e,onResolved:t,onTimeout:o}){let[u,m]=An(Dn);Pn(()=>{let a=setInterval(()=>{m(i=>i<=1?(clearInterval(a),o(),0):i-1)},1e3);return()=>clearInterval(a)},[o]),In(a=>{a==="a"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):a==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):a==="p"&&v(`/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 qe(Ft,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ot(Be,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),qe(Be,{dimColor:!0,children:["Plan ID: ",e.planId]}),qe(Be,{dimColor:!0,children:["Time remaining: ",u,"s"]}),qe(Ft,{marginTop:1,children:[ot(Be,{children:"Overall Risk: "}),ot(Be,{bold:!0,color:g,children:e.plan.overallRisk.toUpperCase()})]}),qe(Be,{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 qe(Ft,{paddingLeft:2,children:[qe(Be,{children:["[",a.index,"] "]}),ot(Be,{children:a.description}),qe(Be,{dimColor:!0,children:[" (",a.toolsNeeded.join(", "),")"]}),qe(Be,{color:i,children:[" [",a.riskLevel,"]"]})]},a.index)}),qe(Ft,{marginTop:1,children:[ot(Be,{dimColor:!0,children:"Permissions: "}),ot(Be,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),qe(Ft,{marginTop:1,children:[ot(Be,{color:"green",children:"[a] Allow once "}),ot(Be,{color:"green",children:"[p] Allow permanent "}),ot(Be,{color:"red",children:"[r] Deny"})]})]})}import{Box as he,Text as j,useInput as Fn}from"ink";import{useEffect as qn,useState as ct,useCallback as xr}from"react";import{Box as fe,Text as q,useInput as Rn}from"ink";import{useEffect as Mn,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},Nn={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),[c,f]=wt(ur),[S,h]=wt(!1);Mn(()=>{let k=!1;return u(null),g([]),i([]),r(null),f(ur),h(!1),v(`/tasks/${e}`).then(({task:I})=>{k||u(I)}).catch(I=>{k||r(I instanceof Error?I.message:String(I))}),v(`/tasks/${e}/plan`).then(({plans:I})=>{k||g(I)}).catch(()=>{k||g([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:I})=>{k||i(I)}).catch(()=>{k||i([])}),()=>{k=!0}},[e]);let C=k=>{f(I=>({...I,[k]:!I[k]}))};if(Rn((k,I)=>{if(k==="b"||I.escape){t();return}k==="1"&&C("plan"),k==="2"&&C("result"),k==="3"&&C("routing"),k==="4"&&C("error"),k==="5"&&h(H=>!H)}),s)return W(fe,{flexDirection:"column",children:[W(q,{color:"red",children:["Task detail failed: ",s]}),ie(q,{dimColor:!0,children:"[b] Back"})]});if(!o)return W(q,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let n=m[0],T=On(o.deliverTo,o.reportTo),L=a.length>0?`${a.length} delivery event${a.length===1?"":"s"}`:"No delivery events";return W(fe,{flexDirection:"column",children:[W(fe,{children:[W(q,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ie(q,{dimColor:!0,children:" \u2022 "}),ie(q,{color:Nn[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),W(q,{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(q,{bold:!0,children:"Summary"}),ie(q,{children:S?o.prompt:$n(o.prompt,240)}),o.prompt.length>240&&W(q,{dimColor:!0,children:["[5] ",S?"collapse prompt":"expand prompt"]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(q,{dimColor:!0,children:["Cost: ",_n(o.costUsd)]}),W(q,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),W(q,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),W(q,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(q,{bold:!0,children:["[1] Plan ",c.plan?"hide":"show"]}),ie(q,{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"}),c.plan&&n&&W(fe,{marginTop:1,flexDirection:"column",children:[n.plan.steps.map(k=>W(fe,{flexDirection:"column",marginBottom:1,children:[W(q,{children:[k.index,". ",k.description]}),W(q,{dimColor:!0,children:[k.riskLevel," risk \u2022 ",k.toolsNeeded.join(", ")||"no tools listed"]}),k.expectedOutput?W(q,{dimColor:!0,children:["Expected: ",k.expectedOutput]}):null]},k.index)),n.learnedRules&&n.learnedRules.length>0&&W(fe,{flexDirection:"column",children:[ie(q,{color:"blue",bold:!0,children:"Learned Rules"}),n.learnedRules.map((k,I)=>W(q,{dimColor:!0,children:["\u2022 ",k]},I))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(q,{bold:!0,children:["[2] Result ",c.result?"hide":"show"]}),ie(q,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),c.result&&ie(fe,{marginTop:1,children:ie(q,{children:o.result?gr(o.result,18):"No result yet."})})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(q,{bold:!0,children:["[3] Routing ",c.routing?"hide":"show"]}),W(q,{dimColor:!0,children:[T," \u2022 ",L]}),c.routing&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(q,{color:"cyan",children:"Deliver To"}),mr(o.deliverTo),ie(q,{color:"cyan",children:"Report To"}),mr(o.reportTo),a.length>0&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(q,{color:"cyan",children:"Recent Delivery"}),a.map(k=>W(q,{dimColor:!0,children:[k.status," \u2022 ",Vn(k)," \u2022 ",fr(k.createdAt)]},k.id))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(q,{bold:!0,children:["[4] Error ",c.error?"hide":"show"]}),ie(q,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),c.error&&o.error&&ie(fe,{marginTop:1,children:ie(q,{color:"red",children:gr(o.error,16)})})]}),ie(fe,{marginTop:1,children:ie(q,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function mr(e){return!e||e.length===0?ie(q,{dimColor:!0,children:" none"}):ie(fe,{flexDirection:"column",children:e.map((t,o)=>ie(q,{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 $n(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 On(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 Vn(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 Wn,jsx as te,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,c]=ct("all"),[f,S]=ct(0),[h,C]=ct(0),[n,T]=ct(null),L=xr(async()=>{m(!0);try{let A=new URLSearchParams({limit:"100"});r!=="all"&&A.set("status",r);let O=await v(`/tasks?${A}`);o(O.tasks)}catch{o([])}finally{m(!1)}},[r]);qn(()=>{L()},[L]);let k=Math.max(1,Math.ceil(t.length/Co)),I=t.slice(h*Co,(h+1)*Co),H=xr(async()=>{let A=I[i];if(A)try{await v(`/tasks/${A.id}/cancel`,{method:"POST"}),T(`Cancelled: ${A.id.slice(0,8)}`),a("list"),L()}catch(O){T(`Failed: ${O instanceof Error?O.message:String(O)}`),a("list")}},[I,i,L]);if(Fn((A,O)=>{if(g==="detail"){(O.escape||O.return||A==="q")&&a("list");return}if(g==="cancelling"){A==="y"?H():a("list");return}if(g==="filter"){if(O.escape){a("list");return}O.upArrow&&f>0&&S(M=>M-1),O.downArrow&&f<to.length-1&&S(M=>M+1),O.return&&(c(to[f]),C(0),s(0),a("list"));return}if(O.escape||A==="q"){e();return}if(O.upArrow&&i>0&&s(M=>M-1),O.downArrow&&i<I.length-1&&s(M=>M+1),O.return&&I[i]&&a("detail"),A==="x"&&I[i]){let M=I[i];["running","pending","queued","paused"].includes(M.status)?(a("cancelling"),T(null)):T(`Cannot cancel task in status: ${M.status}`)}A==="f"&&(S(to.indexOf(r)),a("filter")),A==="r"&&L(),(O.pageDown||A==="n")&&h<k-1&&(C(M=>M+1),s(0)),(O.pageUp||A==="p")&&h>0&&(C(M=>M-1),s(0))}),u)return te(j,{dimColor:!0,children:"Loading tasks..."});if(g==="filter")return oe(he,{flexDirection:"column",children:[te(j,{bold:!0,children:"Filter by status:"}),to.map((A,O)=>te(he,{children:oe(j,{color:O===f?"cyan":"white",children:[O===f?"> ":" ",A,A===r?" (current)":""]})},A)),te(j,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(g==="detail"&&I[i])return te(pr,{taskId:I[i].id,onBack:()=>a("list")});if(g==="cancelling"&&I[i])return oe(he,{flexDirection:"column",children:[oe(j,{color:"red",children:['Cancel task "',I[i].id.slice(0,8),'"? (y/n)']}),n&&te(j,{color:"red",children:n})]});let Y=I[i]??null;return oe(he,{flexDirection:"column",children:[oe(he,{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,"/",k]})]}),n&&te(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(he,{marginTop:1,flexDirection:"row",gap:2,children:[te(he,{flexDirection:"column",flexGrow:3,children:I.map((A,O)=>{let M=O===i,R=Tr[A.status]??"white";return oe(he,{flexDirection:"column",marginBottom:1,children:[oe(he,{children:[te(j,{color:M?"cyan":"gray",bold:M,children:M?"\u276F ":" "}),te(j,{color:R,bold:!0,children:A.status.toUpperCase()}),te(j,{dimColor:!0,children:` ${A.id.slice(0,8)}`})]}),te(he,{paddingLeft:2,children:te(j,{color:M?"white":void 0,children:oo(A.prompt,M?72:56)})}),te(he,{paddingLeft:2,children:oe(j,{dimColor:!0,children:[br(A.createdAt)," \u2022 ",hr(A)," \u2022 ",yr(A.costUsd)]})})]},A.id)})}),te(he,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?oe(Wn,{children:[te(j,{bold:!0,children:"Preview"}),oe(he,{marginTop:1,children:[te(j,{color:Tr[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),te(j,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),te(j,{children:oo(Y.prompt,220)}),oe(he,{marginTop:1,flexDirection:"column",children:[oe(j,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),oe(j,{dimColor:!0,children:["Created: ",br(Y.createdAt)]}),oe(j,{dimColor:!0,children:["Duration: ",hr(Y)]}),oe(j,{dimColor:!0,children:["Cost: ",yr(Y.costUsd)]}),oe(j,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?oe(he,{marginTop:1,flexDirection:"column",children:[te(j,{color:"red",bold:!0,children:"Error"}),te(j,{color:"red",children:oo(Y.error,180)})]}):Y.result?oe(he,{marginTop:1,flexDirection:"column",children:[te(j,{color:"green",bold:!0,children:"Latest Result"}),te(j,{children:oo(Y.result,180)})]}):null,te(he,{marginTop:1,children:te(j,{dimColor:!0,children:"Enter opens full detail"})})]}):te(j,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Un(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function oo(e,t){return Un(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 Gn}from"ink";import{useEffect as Hn,useState as vr}from"react";import{readFileSync as jn,existsSync as Kn}from"fs";import{parse as zn}from"yaml";import{Fragment as Qn,jsx as Ee,jsxs as _e}from"react/jsx-runtime";function Cr({onBack:e}){let[t,o]=vr(null),[u,m]=vr(null);return Gn((g,a)=>{(a.escape||g==="q")&&e()}),Hn(()=>{try{let g=Uo;if(!Kn(g)){m(`Config file not found: ${g}`);return}let a=jn(g,"utf-8");o(zn(a))}catch(g){m(g.message)}},[]),u?_e(ft,{flexDirection:"column",children:[Ee(Pe,{color:"red",children:u}),Ee(Pe,{dimColor:!0,children:"Press Esc to go back"})]}):t?_e(ft,{flexDirection:"column",children:[Ee(Pe,{bold:!0,children:"Configuration (Esc to go back)"}),Ee(ft,{marginTop:1,flexDirection:"column",children:Ee(So,{obj:t,indent:0})})]}):Ee(Pe,{dimColor:!0,children:"Loading config..."})}function So({obj:e,indent:t}){let o=" ".repeat(t);return Ee(Qn,{children:Object.entries(e).map(([u,m])=>Ee(Xn,{label:u,value:m,indent:t,parentKey:u},u))})}function Xn({label:e,value:t,indent:o,parentKey:u}){let m=" ".repeat(o);return Array.isArray(t)?_e(ft,{flexDirection:"column",children:[_e(Pe,{children:[m,Ee(Pe,{color:"cyan",children:e}),":"]}),t.length===0?_e(Pe,{dimColor:!0,children:[m," []"]}):t.map((g,a)=>Ee(Sr,{value:g,indent:o+1,parentKey:u,index:a},`${e}-${a}`))]}):t&&typeof t=="object"?_e(ft,{flexDirection:"column",children:[_e(Pe,{children:[m,Ee(Pe,{color:"cyan",children:e}),":"]}),Ee(So,{obj:t,indent:o+1})]}):_e(Pe,{children:[m,Ee(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)?_e(ft,{flexDirection:"column",children:[_e(Pe,{children:[m,"- [",u,"]"]}),e.map((g,a)=>Ee(Sr,{value:g,indent:t+1,parentKey:o,index:a},`${u}-${a}`))]}):e&&typeof e=="object"?_e(ft,{flexDirection:"column",children:[_e(Pe,{children:[m,"-"]}),Ee(So,{obj:e,indent:t+1})]}):_e(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 Yn}from"ink";import{useEffect as Zn,useState as wo}from"react";import{jsx as qt,jsxs as Xe}from"react/jsx-runtime";function Er({onBack:e}){let[t,o]=wo([]),[u,m]=wo(!0),[g,a]=wo(null);return Yn((i,s)=>{(s.escape||i==="q")&&e()}),Zn(()=>{v("/evolution-audit?limit=20").then(i=>{o(i),m(!1)}).catch(i=>{a(i.message),m(!1)})},[]),u?qt(Ue,{dimColor:!0,children:"Loading evolution log..."}):g?Xe(no,{flexDirection:"column",children:[qt(Ue,{color:"red",children:g}),qt(Ue,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Xe(no,{flexDirection:"column",children:[qt(Ue,{dimColor:!0,children:"No evolution records yet"}),qt(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 Jn}from"ink";import es from"ink-text-input";import{useEffect as ts,useState as Bt}from"react";import{jsx as De,jsxs as ye}from"react/jsx-runtime";var os={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function rs(e,t=20){let o=Math.round(e*t),u=t-o;return"\u2588".repeat(o)+"\u2591".repeat(u)}function ns(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,c]=Bt(!1),[f,S]=Bt(null);Jn((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=()=>{v("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>m(n.message))};ts(()=>{h()},[]);let C=async n=>{if(n.trim()){c(!0),S(null);try{let T=await v("/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{c(!1)}}};return u?ye(rt,{flexDirection:"column",children:[ye(ae,{color:"red",children:["Failed to load goals: ",u]}),De(ae,{dimColor:!0,children:"Press Esc or q to return"})]}):g==="create"?ye(rt,{flexDirection:"column",children:[De(ae,{bold:!0,children:"Create Goal"}),De(ae,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),ye(rt,{marginTop:1,children:[De(ae,{color:"cyan",children:"> "}),De(es,{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"})]}):ye(rt,{flexDirection:"column",children:[ye(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,L=os[n.status]??"white";return ye(rt,{marginBottom:1,flexDirection:"column",children:[ye(rt,{children:[De(ae,{bold:!0,color:L,children:n.name}),ye(ae,{dimColor:!0,children:[" (",n.role,")"]}),De(ae,{dimColor:!0,children:" \u2014 "}),De(ae,{color:L,children:n.status})]}),ye(rt,{children:[ye(ae,{dimColor:!0,children:[" ",rs(T)," "]}),ye(ae,{color:T>=1?"green":"white",children:[Math.round(T*100),"%"]}),ye(ae,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),ye(rt,{children:[ye(ae,{dimColor:!0,children:[" \u23F0 ",ns(n.deadline)," left"]}),ye(ae,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),ye(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 ss}from"ink";import{useEffect as is,useState as kr}from"react";import{jsx as st,jsxs as nt}from"react/jsx-runtime";function as(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(ss((a,i)=>{(i.escape||a==="q")&&e()}),is(()=>{v("/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 c=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-c}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return nt(Et,{children:[st(Oe,{dimColor:!0,children:" "}),nt(Oe,{children:[as(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 be,Text as K,useInput as ms}from"ink";import Bo from"ink-text-input";import{useEffect as gs,useState as Qe,useCallback as kt}from"react";import{CronExpressionParser as fs}from"cron-parser";import{useState as ls,useEffect as cs,useCallback as Ar,useRef as ds}from"react";var us=3e3;function dt(){let[e,t]=ls(null),o=ds(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},us))},[]);return cs(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:m,clearMessage:u}}import{jsx as J,jsxs as re}from"react/jsx-runtime";var Eo=["manual","cron","once","template_complete"],Pr=["cron","once","template_complete"],io={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function ps(e){try{return fs.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,c]=Qe({...io}),[f,S]=Qe("name"),[h,C]=Qe(null),{message:n,setMessage:T,clearMessage:L}=dt(),[k,I]=Qe(!1),[H,Y]=Qe(!1),[A,O]=Qe({}),M=kt(()=>{m(!0),v("/task-templates").then(({templates:b})=>{o(b),new Set(b.flatMap($=>$.steps?.map(Z=>Z.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:$})=>{if(!Array.isArray($)){O({});return}O(Object.fromEntries($.map(Z=>[Z.id,Z.name])))}).catch(()=>O({})):O({}),m(!1)}).catch(()=>m(!1))},[]);gs(()=>{M()},[M]);let R=i==="create"||i==="edit",ee=kt(async()=>{let b=t[g];if(!(!b||k)){I(!0),T(`Triggering ${b.name}...`,"loading");try{let N=await v(`/task-templates/${b.id}/run`,{method:"POST"});T(`Triggered: ${b.name} (${N.executionId})`,"success")}catch(N){T(`Trigger failed: ${N instanceof Error?N.message:String(N)}`,"error")}finally{I(!1)}}},[t,g,k,T]),le=kt(async()=>{let b=t[g];if(!b||H)return;if(!Pr.includes(b.trigger?.type??"manual")){T("Toggle not applicable for manual triggers","error");return}let N=!b.enabled;Y(!0),T(`${b.name} \u2192 ${N?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${b.id}`,{method:"PATCH",body:{enabled:N}}),o($=>$.map(Z=>Z.id===b.id?{...Z,enabled:N}:Z)),T(`${b.name} ${N?"enabled":"disabled"}`,"success")}catch($){T(`Toggle failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{Y(!1)}},[t,g,H,T]),Je=kt(async()=>{let b=t[g];if(b)try{await v(`/task-templates/${b.id}`,{method:"DELETE"}),T(`Deleted: ${b.name}`,"success"),M(),a(N=>Math.max(0,Math.min(N,t.length-2)))}catch(N){T(`Delete failed: ${N instanceof Error?N.message:String(N)}`,"error")}},[t,g,M]),ht=kt(()=>{let b=t[g];b&&(C(b.id),c({name:b.name,triggerType:b.trigger?.type==="workflow_complete"?"template_complete":b.trigger?.type??"manual",cron:b.trigger?.cron??"",targetTemplateId:b.trigger?.type==="template_complete"||b.trigger?.type==="workflow_complete"?b.trigger.event?.split(":")[1]??"":"",stepPrompt:b.steps?.[0]?.prompt??""}),S("name"),s("edit"))},[t,g]),Ne=kt(async()=>{let b={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{},...r.triggerType==="template_complete"&&r.targetTemplateId?{event:`template_complete:${r.targetTemplateId}`}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await v("/task-templates",{method:"POST",body:b}),T(`Created: ${r.name}`,"success")):i==="edit"&&h&&(await v(`/task-templates/${h}`,{method:"PATCH",body:b}),T(`Updated: ${r.name}`,"success"))}catch(N){T(`Save failed: ${N instanceof Error?N.message:String(N)}`,"error")}s("list"),c({...io}),C(null),M()},[r,i,h,M]);return ms((b,N)=>{if(R){if(N.escape){s("list"),c({...io}),C(null);return}if(N.return){let $=["name","triggerType","cron","stepPrompt"],xe=r.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:$.filter(E=>E!=="targetTemplateId"),D=xe.indexOf(f);if(D<xe.length-1){let E=D+1;if(xe[E]==="cron"&&r.triggerType!=="cron"&&E++,E<xe.length){S(xe[E]);return}}Ne();return}if(N.tab&&f==="triggerType"){c($=>{let Z=Eo.indexOf($.triggerType);return{...$,triggerType:Eo[(Z+1)%Eo.length]}});return}if(N.tab&&f==="targetTemplateId"){c($=>{let Z=t.filter(E=>E.id!==h),xe=Z.findIndex(E=>E.id===$.targetTemplateId),D=Z[(xe+1)%Z.length];return{...$,targetTemplateId:D?.id??""}});return}return}if(N.escape||b==="q"){e();return}if(N.upArrow){a($=>Math.max(0,$-1));return}if(N.downArrow){a($=>Math.min(t.length-1,$+1));return}if(b==="t"){ee();return}if(b==="d"){Je();return}if(b==="e"){ht();return}if(b==="c"){c({...io}),S("name"),s("create");return}if(b==="s"||b===" "){le();return}b==="r"&&(M(),L())}),u?J(K,{dimColor:!0,children:"Loading templates..."}):R?re(be,{flexDirection:"column",children:[re(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),re(be,{marginTop:1,flexDirection:"column",children:[re(be,{children:[re(K,{bold:f==="name",color:f==="name"?"cyan":void 0,children:["Name:"," "]}),f==="name"?J(Bo,{value:r.name,onChange:b=>c(N=>({...N,name:b})),placeholder:"template name"}):J(K,{children:r.name||"(empty)"})]}),re(be,{children:[re(K,{bold:f==="triggerType",color:f==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),J(K,{children:r.triggerType}),f==="triggerType"&&J(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&re(be,{children:[re(K,{bold:f==="cron",color:f==="cron"?"cyan":void 0,children:["Cron:"," "]}),f==="cron"?J(Bo,{value:r.cron,onChange:b=>c(N=>({...N,cron:b})),placeholder:"*/5 * * * *"}):J(K,{children:r.cron||"(empty)"})]}),(r.triggerType==="template_complete"||r.triggerType==="workflow_complete")&&re(be,{children:[re(K,{bold:f==="targetTemplateId",color:f==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),J(K,{children:(()=>{let b=t.find(N=>N.id===r.targetTemplateId);return b?b.name:r.targetTemplateId?`(id: ${r.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),f==="targetTemplateId"&&J(K,{dimColor:!0,children:" (Tab to cycle)"})]}),re(be,{children:[re(K,{bold:f==="stepPrompt",color:f==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),f==="stepPrompt"?J(Bo,{value:r.stepPrompt,onChange:b=>c(N=>({...N,stepPrompt:b})),placeholder:"What should this template do?"}):J(K,{children:r.stepPrompt||"(empty)"})]})]}),J(be,{marginTop:1,children:J(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):re(be,{flexDirection:"column",children:[re(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&J(be,{marginTop:1,children:re(K,{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?J(be,{marginTop:1,children:J(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):J(be,{marginTop:1,flexDirection:"column",children:t.map((b,N)=>{let $=N===g,Z=b.trigger?.type==="cron"&&b.trigger?.cron?ps(b.trigger.cron):"",xe=new Set(b.steps?.filter(E=>E.roleId).map(E=>E.roleId)),D=b.steps?.length>1?`${b.steps.length} steps${xe.size>0?` / ${xe.size} roles`:""}`:`${b.steps?.length??0} step`;return re(be,{flexDirection:"column",children:[re(be,{children:[J(K,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),J(K,{color:$?"cyan":void 0,bold:$,children:Ut(b.name,24)}),J(K,{dimColor:!0,children:Ut(b.trigger?.type,10)}),Pr.includes(b.trigger?.type??"manual")?J(K,{color:b.enabled?"green":"gray",children:Ut(b.enabled?"on":"off",6)}):J(K,{dimColor:!0,children:Ut("\u2014",6)}),J(K,{dimColor:!0,children:Ut(D,18)}),Z&&re(K,{dimColor:!0,children:["next: ",Z]})]}),$&&b.steps?.length>1&&J(be,{flexDirection:"column",marginLeft:4,marginTop:0,children:b.steps.map((E,G)=>re(be,{children:[re(K,{dimColor:!0,children:[" ",G+1,". "]}),J(K,{dimColor:!0,children:E.id}),E.roleId&&re(K,{color:"yellow",children:[" @",A[E.roleId]??E.roleId]}),E.dependsOn&&E.dependsOn.length>0&&re(K,{dimColor:!0,children:[" (after: ",E.dependsOn.join(", "),")"]}),E.config&&re(K,{dimColor:!0,children:[" ","[",[E.config.timeout!==void 0?`timeout:${E.config.timeout}s`:"",E.config.maxTurns!==void 0?`turns:${E.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},E.id))})]},b.id)})}),J(be,{marginTop:1,children:J(K,{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 Le,useInput as xs}from"ink";import Ts from"ink-text-input";import{useEffect as hs,useState as It,useCallback as Dr}from"react";import{jsx as ke,jsxs as pt}from"react/jsx-runtime";function Rr({onBack:e}){let[t,o]=It([]),[u,m]=It(""),[g,a]=It(!0),[i,s]=It(!1),[r,c]=It(""),[f,S]=It(null),h=Dr(()=>{a(!0),v("/webhooks").then(({webhooks:n,auth:T})=>{o(n),m(T),a(!1)}).catch(()=>a(!1))},[]);hs(()=>{h()},[h]);let C=Dr(async n=>{if(n.trim())try{let T=await v(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});S(`Triggered: ${T.executionId}`)}catch(T){S(`Trigger failed: ${T instanceof Error?T.message:String(T)}`)}},[]);return xs((n,T)=>{if(i){if(T.escape){s(!1),c("");return}if(T.return){C(r),s(!1),c("");return}return}if(T.escape||n==="q"){e();return}if(n==="t"){s(!0),c(""),S(null);return}n==="r"&&(h(),S(null))}),g?ke(Le,{dimColor:!0,children:"Loading webhooks..."}):pt(ut,{flexDirection:"column",children:[pt(Le,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),pt(Le,{dimColor:!0,children:["Auth: ",u]}),f&&ke(ut,{marginTop:1,children:ke(Le,{color:"yellow",children:f})}),i&&pt(ut,{marginTop:1,children:[ke(Le,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ke(Ts,{value:r,onChange:c,placeholder:"webhook name or ID"}),ke(Le,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ke(ut,{marginTop:1,children:ke(Le,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):pt(ut,{marginTop:1,flexDirection:"column",children:[ke(ut,{children:pt(Le,{bold:!0,children:[At("NAME",24),At("DESCRIPTION",36),At("TRIGGER",28),"TAGS"]})}),t.map(n=>pt(ut,{children:[ke(Le,{children:At(n.displayName,24)}),ke(Le,{dimColor:!0,children:At(ys(n.description??"",34),36)}),ke(Le,{dimColor:!0,children:At(n.trigger,28)}),ke(Le,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),ke(ut,{marginTop:1,children:ke(Le,{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 ys(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ye,Text as me,useInput as bs}from"ink";import vs from"ink-text-input";import{useEffect as Mr,useState as it,useCallback as ko}from"react";import{jsx as ge,jsxs as We}from"react/jsx-runtime";function Cs(e){return e>=4?"red":e===3?"yellow":"gray"}function Ss(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function ws(e){return new Date(e).toLocaleDateString()}function $r({onBack:e}){let[t,o]=it([]),[u,m]=it(0),[g,a]=it([]),[i,s]=it(!0),[r,c]=it(!1),[f,S]=it(""),[h,C]=it("all"),[n,T]=it(null),[L,k]=it(!1),I=ko(()=>{v("/agents").then(({agents:R})=>{o(R),s(!1)}).catch(()=>s(!1))},[]);Mr(()=>{I()},[I]);let H=t[u],Y=ko(()=>{H&&(k(!1),v(`/memories/${H.id}`).then(({memories:R})=>{a(R),T(null)}).catch(R=>T(`Failed: ${R instanceof Error?R.message:String(R)}`)))},[H]);Mr(()=>{H&&Y()},[H,Y]);let A=ko(async R=>{if(!(!H||!R.trim()))try{let ee=await v("/memories/query",{method:"POST",body:{agentId:H.id,prompt:R.trim()}});a(ee.memories),k(!0),T(`Search: ${ee.count} results`)}catch(ee){T(`Search failed: ${ee instanceof Error?ee.message:String(ee)}`)}},[H]),O=r,M=g.filter(R=>h==="all"?!0:h==="high"?R.importance>3:h==="medium"?R.importance===3:R.importance<3);return bs((R,ee)=>{if(O){if(ee.escape){c(!1),S("");return}if(ee.return){A(f),c(!1),S("");return}return}if(ee.escape||R==="q"){e();return}if(R==="a"){m(le=>(le+1)%Math.max(1,t.length));return}if(ee.leftArrow){m(le=>(le-1+t.length)%Math.max(1,t.length));return}if(ee.rightArrow){m(le=>(le+1)%Math.max(1,t.length));return}if(R==="s"){c(!0),S(""),T(null);return}if(R==="h"){C(le=>le==="high"?"all":"high");return}if(R==="m"){C(le=>le==="medium"?"all":"medium");return}if(R==="l"){C(le=>le==="low"?"all":"low");return}R==="r"&&Y()}),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," | ",L?"search results":"all memories"," (",M.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(vs,{value:f,onChange:S,placeholder:"search query..."}),ge(me,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),M.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:M.map(R=>We(Ye,{marginBottom:0,children:[We(me,{color:Cs(R.importance),bold:!0,children:[Ss(R.importance)," "]}),ge(me,{dimColor:!0,children:Nr(R.type??"?",12)}),ge(me,{dimColor:!0,children:Nr(`\xD7${R.retrievedCount??0}`,5)}),We(me,{children:[Bs(R.content,55)," "]}),ge(me,{dimColor:!0,children:ws(R.createdAt)}),R.score!==void 0&&We(me,{dimColor:!0,children:[" (",R.score.toFixed(2),")"]})]},R.id))}),ge(Ye,{marginTop:1,children:ge(me,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Nr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Bs(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ge,Text as de,useInput as Es}from"ink";import lo from"ink-text-input";import{useState as Re,useEffect as _r,useCallback as Io}from"react";import{jsx as ve,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"]},ks={"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 Or({onBack:e}){let{state:t}=He(),[o,u]=Re({}),[m,g]=Re([]),[a,i]=Re(null),[s,r]=Re("view"),[c,f]=Re(0),[S,h]=Re(""),[C,n]=Re(null),[T,L]=Re(!1),[k,I]=Re([]),[H,Y]=Re({}),[A,O]=Re(0),[M,R]=Re(""),[ee,le]=Re(""),[Je,ht]=Re(""),Ne=Object.values(Lr).flat(),b=Io(()=>{v("/config").then(D=>{u(D.config),g(D.mutable)}).catch(D=>i(D.message)),v("/config/env-diff").then(D=>{I(D.diffs)}).catch(()=>{}),v("/config/env").then(D=>Y(D.env??{})).catch(()=>{})},[]);_r(()=>{b()},[b]),_r(()=>{t.configVersion>0&&b()},[t.configVersion,b]);let N=Io(async()=>{let D=Ne[c];if(D){L(!0),n(null);try{let E=S,G=o[D];if(G&&typeof G.value=="number"&&(E=Number(S),isNaN(E))){n("Invalid number"),L(!1);return}let ue=await v("/config",{method:"PATCH",body:{[D]:E}});ue.updated.length>0&&(n(`Updated: ${D}`),b()),ue.errors.length>0&&n(ue.errors[0]),r("view")}catch(E){n(`Failed: ${E instanceof Error?E.message:String(E)}`)}finally{L(!1)}}},[Ne,c,S,o,b]),$=Object.keys(H),Z=Io(async D=>{try{await v("/config/env",{method:"PUT",body:D}),n("Env vars saved"),b()}catch(E){n(`Failed: ${E instanceof Error?E.message:String(E)}`)}},[b]);if(Es((D,E)=>{if(s==="edit"){if(E.escape){r("view");return}return}if(s==="env-list"){if(E.escape){r("view");return}if(E.upArrow&&A>0&&O(G=>G-1),E.downArrow&&A<$.length-1&&O(G=>G+1),D==="a"){R(""),r("env-add-key");return}if(D==="d"&&$.length>0){let G=$[A],ue={...H};delete ue[G],Z(ue),A>=$.length-1&&A>0&&O(et=>et-1);return}if(E.return&&$.length>0){ht(H[$[A]]??""),r("env-edit-value");return}return}if(s==="env-add-key"){if(E.escape){r("env-list");return}return}if(s==="env-add-value"){if(E.escape){r("env-list");return}return}if(s==="env-edit-value"){if(E.escape){r("env-list");return}return}if(E.escape||D==="q"){e();return}if(E.upArrow&&c>0&&f(G=>G-1),E.downArrow&&c<Ne.length-1&&f(G=>G+1),E.return||D==="e"){let G=Ne[c],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")}D==="v"&&(O(0),r("env-list"),n(null)),D==="r"&&(b(),n("Refreshed")),D==="s"&&k.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),I([]),b()}),D==="l"&&k.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),b()})}),a)return pe(Ge,{flexDirection:"column",children:[pe(de,{color:"red",children:["Failed to load config: ",a]}),ve(de,{dimColor:!0,children:"Press Esc or q to return"})]});let xe=0;return pe(Ge,{flexDirection:"column",children:[ve(de,{bold:!0,children:"Settings"}),C&&ve(de,{color:C.startsWith("Failed")||C.startsWith("This setting")?"yellow":"green",children:C}),k&&k.length>0&&pe(Ge,{flexDirection:"column",marginBottom:1,children:[pe(de,{color:"yellow",children:[".env differs from DB (",k.length," key(s)): ",k.map(D=>D.envKey).join(", ")]}),ve(de,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ve(Ge,{marginTop:1,flexDirection:"column",children:Object.entries(Lr).map(([D,E])=>pe(Ge,{marginBottom:1,flexDirection:"column",children:[ve(de,{bold:!0,color:"cyan",children:D}),E.map(G=>{let ue=o[G],yt=xe++===c,bt=m.includes(G),jt=ks[G]??G,lt=ue?String(ue.value??""):"...";return s==="edit"&&yt?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",jt,": "]}),ve(lo,{value:S,onChange:h,onSubmit:()=>{N()}}),T&&ve(de,{color:"yellow",children:" saving..."})]},G):pe(Ge,{children:[pe(de,{color:yt?"cyan":"white",children:[yt?"> ":" ",bt?" ":"\u{1F512} ",jt,": "," "]}),ve(de,{color:bt?"white":"gray",children:lt}),!bt&&ve(de,{dimColor:!0,children:" (restart required)"})]},G)})]},D))}),ve(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 (",$.length,")"]}),$.length===0&&s==="env-list"&&ve(de,{dimColor:!0,children:" No env vars. Press a to add."}),$.map((D,E)=>{let G=E===A;return s==="env-edit-value"&&G?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",D," = "]}),ve(lo,{value:Je,onChange:ht,onSubmit:()=>{Z({...H,[D]:Je}),r("env-list")}})]},D):pe(de,{color:G&&s==="env-list"?"cyan":"white",children:[G&&s==="env-list"?"> ":" ",D," = ",H[D]]},D)}),s==="env-add-key"&&pe(Ge,{children:[ve(de,{color:"green",children:" New key: "}),ve(lo,{value:M,onChange:R,onSubmit:()=>{M.trim()&&(le(""),r("env-add-value"))}})]}),s==="env-add-value"&&pe(Ge,{children:[pe(de,{color:"green",children:[" ",M," = "]}),ve(lo,{value:ee,onChange:le,onSubmit:()=>{Z({...H,[M.trim()]:ee}),r("env-list")}})]}),ve(de,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as xt,Text as Ie,useInput as Is}from"ink";import{useEffect as As,useState as Ao,useCallback as Ps}from"react";import{jsx as Se,jsxs as Dt}from"react/jsx-runtime";function Vr({onBack:e}){let[t,o]=Ao([]),[u,m]=Ao(!0),[g,a]=Ao(0),{message:i,setMessage:s,clearMessage:r}=dt(),c=Ps(()=>{m(!0),v("/plugins").then(({plugins:f})=>{o(f),m(!1)}).catch(()=>m(!1))},[]);return As(()=>{c()},[c]),Is((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"&&(c(),r())}),u?Se(Ie,{dimColor:!0,children:"Loading plugins..."}):Dt(xt,{flexDirection:"column",children:[Dt(Ie,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Se(xt,{marginTop:1,children:Dt(Ie,{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?Se(xt,{marginTop:1,children:Se(Ie,{dimColor:!0,children:"No plugins installed."})}):Dt(xt,{marginTop:1,flexDirection:"column",children:[Dt(xt,{children:[Se(Ie,{dimColor:!0,children:" "}),Se(Ie,{dimColor:!0,children:Pt("Name",24)}),Se(Ie,{dimColor:!0,children:Pt("Scope",8)}),Se(Ie,{dimColor:!0,children:Pt("User",6)}),Se(Ie,{dimColor:!0,children:"Path"})]}),t.map((f,S)=>{let h=S===g,C=f.id.split("@")[0];return Dt(xt,{children:[Se(Ie,{color:h?"cyan":void 0,bold:h,children:h?"> ":" "}),Se(Ie,{color:h?"cyan":void 0,bold:h,children:Pt(C,24)}),Se(Ie,{color:h?"cyan":void 0,bold:h,children:Pt(f.scope,8)}),Se(Ie,{color:f.globalEnabled?"green":"gray",children:Pt(f.globalEnabled?"on":"off",6)}),Se(Ie,{dimColor:!0,children:f.installPath})]},f.id)})]}),Se(xt,{marginTop:1,children:Se(Ie,{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 Ds}from"ink";import{useState as Rs}from"react";import{jsx as Tt,jsxs as Fr}from"react/jsx-runtime";var Ms=[{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]=Rs("tasks");return Ds((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}}),Fr(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:Ms.map(u=>{let m=t===u.id;return Tt(Po,{children:Fr(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 ne,Text as z,useInput as Ns}from"ink";import{useEffect as $s,useState as Wt}from"react";import{jsx as F,jsxs as Ce}from"react/jsx-runtime";var Ur={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Wr({onBack:e}){let[t,o]=Wt([]),[u,m]=Wt(!0),[g,a]=Wt(0),[i,s]=Wt(null),[r,c]=Wt("");$s(()=>{f()},[]);async function f(){try{let C=await v("/channels");o(C.channels)}catch{}m(!1)}async function S(C){if(t.find(T=>T.id===C)?.platform==="wechat")try{c("Starting WeChat QR login...");let T=await v(`/channels/${C}/wechat/qr-start`,{method:"POST"});if(T.qrcodeUrl){c(`Scan QR: ${T.qrcodeUrl}
10
- Waiting for scan...`);let L=await v(`/channels/${C}/wechat/qr-wait`,{method:"POST",body:{sessionKey:T.sessionKey,timeoutMs:12e4}});c(L.message)}else c(T.message);f()}catch{c("WeChat connect failed")}else try{await v(`/channels/${C}/connect`,{method:"POST"}),c("Connecting..."),f()}catch{c("Connect failed")}}async function h(C){try{await v(`/channels/${C}/disconnect`,{method:"POST"}),c("Disconnected"),f()}catch{c("Disconnect failed")}}return Ns((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]),c("");return}}),u?F(ne,{flexDirection:"column",children:F(z,{dimColor:!0,children:"Loading channels..."})}):i?Ce(ne,{flexDirection:"column",children:[Ce(ne,{marginBottom:1,children:[Ce(z,{bold:!0,children:["Channel: ",i.name]}),F(z,{dimColor:!0,children:" (Esc to go back)"})]}),Ce(ne,{flexDirection:"column",gap:0,children:[Ce(z,{children:["ID: ",i.id]}),Ce(z,{children:["Platform: ",i.platform]}),Ce(z,{children:["Status: ",F(z,{color:Ur[i.status]??"white",children:i.status})]}),Ce(z,{children:["Enabled: ",i.enabled?"yes":"no"]}),Ce(z,{children:["Messages: ",i.messageCount]}),Ce(z,{children:["Config: ",JSON.stringify(i.config)]})]}),F(ne,{marginTop:1,children:F(z,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&F(z,{color:"yellow",children:r})]}):Ce(ne,{flexDirection:"column",children:[Ce(ne,{marginBottom:1,children:[F(z,{bold:!0,children:"Channels"}),Ce(z,{dimColor:!0,children:[" (",t.length," total) "]}),F(z,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?F(z,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):Ce(ne,{flexDirection:"column",children:[Ce(ne,{children:[F(ne,{width:3,children:F(z,{dimColor:!0,children:" "})}),F(ne,{width:12,children:F(z,{bold:!0,dimColor:!0,children:"ID"})}),F(ne,{width:16,children:F(z,{bold:!0,dimColor:!0,children:"Name"})}),F(ne,{width:12,children:F(z,{bold:!0,dimColor:!0,children:"Platform"})}),F(ne,{width:14,children:F(z,{bold:!0,dimColor:!0,children:"Status"})}),F(ne,{width:10,children:F(z,{bold:!0,dimColor:!0,children:"Enabled"})}),F(ne,{width:10,children:F(z,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((C,n)=>Ce(ne,{children:[F(ne,{width:3,children:F(z,{children:n===g?">":" "})}),F(ne,{width:12,children:F(z,{inverse:n===g,children:C.id.slice(0,8)})}),F(ne,{width:16,children:F(z,{children:C.name})}),F(ne,{width:12,children:F(z,{children:C.platform})}),F(ne,{width:14,children:Ce(z,{color:Ur[C.status]??"white",children:[C.status==="connected"?"\u25CF":C.status==="error"?"\u2717":"\u25CB"," ",C.status]})}),F(ne,{width:10,children:F(z,{color:C.enabled?"green":"gray",children:C.enabled?"yes":"no"})}),F(ne,{width:10,children:F(z,{children:C.messageCount})})]},C.id))]})]})}import{Box as Rt,Text as at,useInput as Os}from"ink";import{useEffect as Vs,useState as Gt,useCallback as Fs}from"react";import{Box as P,Text as p,useInput as _s}from"ink";import Ze from"ink-text-input";import{useEffect as Gr,useState as X,useCallback as mt}from"react";Wo();import{Fragment as Hr,jsx as x,jsxs as w}from"react/jsx-runtime";var Ls=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function jr({roleId:e,onBack:t}){let[o,u]=X(null),[m,g]=X([]),[a,i]=X(!0),[s,r]=X("view"),[c,f]=X(""),[S,h]=X(0),[C,n]=X(""),[T,L]=X([]),[k,I]=X(0),[H,Y]=X(new Set),[A,O]=X("inline"),[M,R]=X(""),[ee,le]=X(""),[Je,ht]=X([]),[Ne,b]=X(new Set),[N,$]=X(0),[Z,xe]=X("default"),[D,E]=X(""),[G,ue]=X(""),[et,yt]=X("mode"),[bt,jt]=X([]),[lt,Xr]=X(null),[go,Qr]=X([]),[vt,fo]=X([]),[$o,po]=X(""),[gt,Kt]=X(0),[zt,_o]=X(""),[Lo,Oo]=X(""),[Vo,Fo]=X(""),{message:_,setMessage:U}=dt(),se=mt(()=>{i(!0),v(`/roles/${e}`).then(({role:d,boundPlugins:y})=>{u(d),g(y??[]),f(d.cagPrompt??""),Y(new Set(d.allowedTools??[])),O(d.executionMode??"inline"),R(d.model??""),le(d.maxBudgetUsd!=null?String(d.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Gr(()=>{se(),v("/config").then(d=>{let y=d.config["defaults.deniedReadPaths"]?.value;Array.isArray(y)&&jt(y),Xr(d.sandbox),Qr(d.osCapabilities?.registry??[])}).catch(()=>{})},[se]),Gr(()=>{O(o?.executionMode??"inline"),R(o?.model??""),le(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),xe(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),fo(o?.osCapabilities??[]);let d=o?.osCapabilities?.find(y=>y.id==="automation")?.targets??[];po(d.join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let Yr=mt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:c}}),U("CAG prompt saved","success"),r("view"),se()}catch(d){U(`Save failed: ${d instanceof Error?d.message:String(d)}`,"error")}},[o,c,se,U]),Zr=mt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Fe}}),U("Directories saved","success"),r("view"),se()}catch(d){U(`Save failed: ${d instanceof Error?d.message:String(d)}`,"error")}},[o,se,U]),Jr=mt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),U("Tool permissions saved","success"),r("view"),se()}catch(d){U(`Save failed: ${d instanceof Error?d.message:String(d)}`,"error")}},[o,H,se,U]),en=mt(async()=>{if(!o)return;let d={executionMode:A};M!==void 0&&(d.model=M);let y=parseFloat(ee);isNaN(y)||(d.maxBudgetUsd=y);try{await v(`/roles/${o.id}`,{method:"PATCH",body:d}),U("Execution config saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,A,M,ee,se,U]),tn=mt(async()=>{if(!o)return;let d={permissionMode:Z},y=D.split(",").map(B=>B.trim()).filter(Boolean),l=G.split(",").map(B=>B.trim()).filter(Boolean);d.allowedBashPatterns=y.length>0?y:[],d.deniedBashPatterns=l.length>0?l:[];try{await v(`/roles/${o.id}`,{method:"PATCH",body:d}),U("Permission config saved","success"),r("view"),se()}catch(B){U(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[o,Z,D,G,se,U]),qo=mt(d=>{let y=new Map;for(let l of d){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))},[]),on=mt(async()=>{if(!o)return;let d=qo(vt),y=d.find(l=>l.id==="automation")?.targets??[];if(d.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 v(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:d}}),U("OS capabilities saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,vt,qo,se,U]),Fe=o?.additionalDirectories??[];if(_s((d,y)=>{if(y.escape){r("view");return}if(d==="r"){se();return}switch(s){case"view":{if(d==="c"){r("edit-cag");return}if(d==="d"){r("edit-dirs"),h(0),n("");return}if(d==="t"){r("edit-tools");return}if(d==="o"){r("edit-oscaps");return}if(d==="x"){r("edit-exec");return}if(d==="h"){v("/channels?enabled=true").then(({channels:l})=>{ht(l.map(B=>({name:B.name,id:B.id}))),b(new Set(o?.allowedChannels??[])),$(0),r("edit-channels")}).catch(()=>U("Failed to load channels","error"));return}if(d==="p"){xe(o?.permissionMode??"default"),E((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),yt("mode"),r("edit-permissions");return}if(d==="v"){Kt(0),r("edit-env");return}if(d==="i"){if(!o)return;let l=!o.inheritUserSettings;v(`/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&&d==="s"){Yr();return}break}case"edit-dirs":{if(d==="s"){Zr();return}if(d==="a"){r("edit-dirs-add");return}if(d==="m"&&Fe.length>0){let l=Fe[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(d==="x"&&Fe.length>0){u(l=>l&&{...l,additionalDirectories:Fe.filter((B,V)=>V!==S)}),h(l=>Math.max(0,Math.min(l,Fe.length-2)));return}if(y.upArrow){h(l=>Math.max(0,l-1));return}if(y.downArrow){h(l=>Math.min(Fe.length-1,l+1));return}break}case"edit-dirs-add":{if(y.escape){r("edit-dirs"),n(""),L([]);return}if(y.return&&T.length>0){let l=T[k];l&&(n(l.endsWith("/")?l: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(""),L([]),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;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(l)}`).then(({suggestions:B})=>{B.length===1?(n(B[0]+"/"),L([])):B.length>1&&(L(B),I(0))}).catch(()=>{L([])});return}if(y.upArrow&&T.length>0){I(l=>Math.max(0,l-1));return}if(y.downArrow&&T.length>0){I(l=>Math.min(T.length-1,l+1));return}break}case"edit-tools":{if(d==="s"){Jr();return}let l=parseInt(d,10)-1;if(!isNaN(l)&&l>=0&&l<Xt.length){let B=Xt[l];Y(V=>{let ce=new Set(V);return ce.has(B)?ce.delete(B):ce.add(B),ce});return}break}case"edit-oscaps":{if(d==="s"){on();return}if(d==="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(d,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(d==="s"){en();return}if(y.tab){O(l=>l==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(d==="s"){tn();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(Z);y.upArrow&&xe(l[Math.max(0,B-1)]),y.downArrow&&xe(l[Math.min(l.length-1,B+1)]);return}break}case"edit-channels":{if(d==="s"){if(!o)return;let l=Ne.size>0?Array.from(Ne):[];v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:l}}).then(()=>{U("Channels saved","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(d==="u"){if(!o)return;v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{U("Channels: unrestricted","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(d===" "){let l=Je[N];l&&b(B=>{let V=new Set(B);return V.has(l.name)?V.delete(l.name):V.add(l.name),V});return}if(y.upArrow){$(l=>Math.max(0,l-1));return}if(y.downArrow){$(l=>Math.min(Je.length-1,l+1));return}break}case"edit-env":{let l=Object.keys(o?.envVars??{});if(d==="a"){_o(""),r("edit-env-add-key");return}if(d==="d"&&l.length>0){let B=l[gt],V={...o?.envVars??{}};delete V[B],v(`/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){Fo((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:c,onChange:f,placeholder:"Character And Guidance prompt..."}),_&&x(P,{marginTop:1,children:x(p,{color:_.type==="error"?"red":"green",children:_.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:d=>{n(d),L([])},placeholder:"/absolute/path/to/directory"}),T.length>0&&w(P,{flexDirection:"column",marginTop:1,children:[T.map((d,y)=>w(p,{color:y===k?"cyan":void 0,dimColor:y!==k,children:[y===k?"> ":" ",d,"/"]},d)),x(p,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),_&&x(P,{marginTop:1,children:x(p,{color:_.type==="error"?"red":"green",children:_.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)"}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),Fe.length===0?x(p,{dimColor:!0,children:"No directories. Press a to add one."}):Fe.map((d,y)=>{let l=typeof d=="string"?{path:d,mode:"rw"}:d,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)"}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),Xt.map((d,y)=>{let l=H.has(d);return w(P,{children:[w(p,{dimColor:!0,children:[y+1,". "]}),x(p,{color:l?"green":"red",children:l?"[ON] ":"[OFF] "}),x(p,{children:d})]},d)})]});if(s==="edit-oscaps"){let d=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=d.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)}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.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"}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.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:A}),x(p,{dimColor:!0,children:" (Tab to toggle)"})]}),w(P,{children:[x(p,{bold:!0,children:" Model: "}),x(Ze,{value:M,onChange:R,placeholder:"sonnet, opus, haiku, or blank"})]}),w(P,{children:[x(p,{bold:!0,children:" Max Budget (USD): "}),x(Ze,{value:ee,onChange:le,placeholder:"0 = unlimited"})]}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.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===Z?"green":"gray",children:[y===Z?`[${y}]`:` ${y} `," "]},y))]}),w(P,{children:[x(p,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?x(Ze,{value:D,onChange:E,placeholder:"git add *, pnpm test*"}):x(p,{children:D||"(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)"}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.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((d,y)=>w(P,{children:[w(p,{children:[y===N?">":" "," "]}),w(p,{color:Ne.has(d.name)?"green":"gray",children:["[",Ne.has(d.name)?"x":" ","] ",d.name]})]},d.id)),w(p,{dimColor:!0,children:["Selected: ",Ne.size>0?Array.from(Ne).join(", "):"none (= block all)"]}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(s.startsWith("edit-env")){let d=Object.keys(o.envVars??{});return w(P,{flexDirection:"column",children:[w(p,{bold:!0,children:["Environment Variables (",d.length,")"]}),d.length===0&&s==="edit-env"&&x(p,{dimColor:!0,children:" No env vars. Press a to add."}),d.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:Fo,onSubmit:()=>{let V={...o.envVars??{},[y]:Vo};v(`/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:_o,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:Lo,onChange:Oo,onSubmit:()=>{let y={...o.envVars??{},[zt.trim()]:Lo};v(`/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"}),_&&x(p,{color:_.type==="error"?"red":"green",children:_.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(d=>d.id==="automation"&&d.targets?.length?`automation(${d.targets.join(",")})`:d.id).join(", "):"None"})]}),lt&&w(P,{children:[x(p,{dimColor:!0,children:"Sandbox Platform: "}),w(p,{children:[lt.platform," ",lt.available?"(active)":"(unavailable)"]})]}),Fe.length>0&&w(Hr,{children:[x(p,{bold:!0,children:"Additional Directories:"}),Fe.map(d=>w(p,{dimColor:!0,children:[" ",d.path]},d.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(d=>w(p,{dimColor:!0,children:[" ",d]},d)),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(Hr,{children:[x(p,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(d=>w(p,{dimColor:!0,children:[" - ",d]},d))]}),_&&x(P,{children:x(p,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.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 Kr({onBack:e}){let[t,o]=Gt([]),[u,m]=Gt(!0),[g,a]=Gt(0),[i,s]=Gt("list"),[r,c]=Gt(null),{message:f,setMessage:S,clearMessage:h}=dt(),C=Fs(()=>{m(!0),v("/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 Vs(()=>{C()},[C]),Os((n,T)=>{if(T.escape||n==="q"){e();return}if(T.upArrow){a(L=>Math.max(0,L-1));return}if(T.downArrow){a(L=>Math.min(t.length-1,L+1));return}if(n==="r"&&(C(),h()),n===`
11
- `||n==="o"||n==="e"){t.length>0&&(c(t[g].id),s("detail"));return}}),u?Ve(at,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Ve(jr,{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 L=T===g,k=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return co(Rt,{children:[Ve(at,{color:L?"cyan":void 0,bold:L,children:L?"> ":" "}),Ve(at,{color:L?"cyan":void 0,bold:L,children:Ro(n.name,24)}),Ve(at,{color:qs(n.status),children:Ro(n.status,12)}),Ve(at,{dimColor:!0,children:Ro(k,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 Us,Text as Mo}from"ink";import Ws from"react";import{jsx as uo,jsxs as Hs}from"react/jsx-runtime";var Me={key:"Esc",label:"back"},Gs={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 zr(){let{state:e}=He(),t=Gs[e.view]??[Me];return uo(Us,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,u)=>Hs(Ws.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 Ys,jsx as Q,jsxs as Nt}from"react/jsx-runtime";function zs(){let{state:e,dispatch:t}=He(),{session:o,sendMessage:u,createNewSession:m,archiveCurrentSession:g}=Zo(),[a,i]=Ks([]);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(I=>[...I,{role:"assistant",content:s.content}]))},[s]);let{events:c,isStreaming:f,clearEvents:S}=Yo(e.activeTaskId),h=c[c.length-1],C=h?.type==="complete"&&!f,n=No(null),T=No("");mo(()=>{T.current=c.filter(I=>I.type==="reasoning").map(I=>I.content).join("")},[c]),mo(()=>{if(C&&e.activeTaskId!==n.current){n.current=e.activeTaskId;let I=h?.content||T.current;I&&i(H=>[...H,{role:"assistant",content:I}])}},[C,h,e.activeTaskId]);let L=async I=>{let H=I.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),I.startsWith("/")){let A=I.slice(1),M={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"}[A];if(M){t({type:"SET_VIEW",view:M});return}if(A==="new"){if(await g()){let ee=await m();i([]),S(),ee&&i([{role:"assistant",content:`Session archived. New session started: ${ee.id.slice(0,8)}`}])}return}if(A==="session"){let R=o?`Session: ${o.id}
12
- Turns: ${o.messageCount}
13
- Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(ee=>[...ee,{role:"assistant",content:R}]);return}}if(i(A=>[...A,{role:"user",content:I}]),S(),!await u(I)){i(A=>[...A,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},k=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval;return Nt(Ht,{flexDirection:"column",paddingX:1,children:[Q(or,{}),Nt(Ht,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Nt(Ys,{children:[Q(lr,{messages:a}),Q(sr,{events:c,isStreaming:f}),!e.connected&&!e.serverUnreachable&&Q(Ht,{children:Q(Mt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Nt(Ht,{flexDirection:"column",children:[Q(Mt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),Q(Mt,{dimColor:!0,children:"Check: adam server logs"}),Q(Mt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&Q(qr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&Q(ro,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&Q(Cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&Q(Er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&Q(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&Q(Ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&Q(ao,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&Q(Rr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&Q($r,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&Q(Vr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&Q(Kr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&Q(Or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&Q(Wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?Q(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?Q(cr,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):k?Q(nr,{onSubmit:L}):Q(zr,{}),e.planTimeoutNotice&&Q(Xs,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function Xs({planId:e,onDismiss:t}){return js(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."]}),Q(Mt,{dimColor:!0,children:" [d] Dismiss"})]})}function Qs(){return Q(jo,{children:Q(zs,{})})}export{Qs as default};
@@ -1 +0,0 @@
1
- import{y as a,z as b}from"./chunk-5OQZPUBV.js";import"./chunk-V32YF3J5.js";import"./chunk-DWRYIN5N.js";import"./chunk-TNL2LZB7.js";import"./chunk-2H7UOW4P.js";import"./chunk-FXQAUQTI.js";import"./chunk-52PR7XTN.js";import"./chunk-SWP2JC54.js";import"./chunk-GMMWA5EG.js";import"./chunk-MDBVKBC7.js";import"./chunk-IZNEOYRP.js";import"./chunk-3LY6PD6A.js";import"./chunk-7446ZS6D.js";import"./chunk-I7ZZKPHE.js";import"./chunk-YXYIA24D.js";import"./chunk-MJSSCKMB.js";import"./chunk-DBP7GPWG.js";import"./chunk-L7JP7DUO.js";import"./chunk-YHVYX3F4.js";import"./chunk-GGIHDFRW.js";import"./chunk-PG6LMSX6.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -1 +0,0 @@
1
- import{j as a,k as b,l as c,m as d,n as e}from"./chunk-FIN36WAP.js";import"./chunk-DWRYIN5N.js";import"./chunk-TSPQ44HT.js";import"./chunk-TNL2LZB7.js";import"./chunk-52PR7XTN.js";import"./chunk-SWP2JC54.js";import"./chunk-N4ES7TCL.js";import"./chunk-3LY6PD6A.js";import"./chunk-7446ZS6D.js";import"./chunk-I7ZZKPHE.js";import"./chunk-MJSSCKMB.js";import"./chunk-DBP7GPWG.js";import"./chunk-L7JP7DUO.js";import"./chunk-RLJYEEQC.js";import"./chunk-YHVYX3F4.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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{b as a,c as b,d as c}from"./chunk-ZL5JXLAX.js";import"./chunk-HWLSHTVX.js";import"./chunk-MDBVKBC7.js";import"./chunk-IZNEOYRP.js";import"./chunk-N4ES7TCL.js";import"./chunk-3LY6PD6A.js";import"./chunk-7446ZS6D.js";import"./chunk-I7ZZKPHE.js";import"./chunk-VVSZZK5T.js";import"./chunk-YXYIA24D.js";import"./chunk-DBP7GPWG.js";import"./chunk-L7JP7DUO.js";import"./chunk-RLJYEEQC.js";import"./chunk-YHVYX3F4.js";import"./chunk-GGIHDFRW.js";import"./chunk-PG6LMSX6.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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-FZCNYKNT.js";import"./chunk-GMMWA5EG.js";import"./chunk-YXYIA24D.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1,99 +0,0 @@
1
- import{b as He,c as Qe,d as N,e as et}from"./chunk-DWRYIN5N.js";import{a as U,e as tt}from"./chunk-TSPQ44HT.js";import{a as pe,d as Ke,e as me}from"./chunk-TNL2LZB7.js";import{b as Je}from"./chunk-52PR7XTN.js";import{b as fe,c as Ye,d as Ge,e as Xe,f as Ze}from"./chunk-N4ES7TCL.js";import{j as je}from"./chunk-3LY6PD6A.js";import{a as Le,b as $e}from"./chunk-7446ZS6D.js";import{b as B,c as O,d as J,f as Oe}from"./chunk-I7ZZKPHE.js";import{a as Ve}from"./chunk-MJSSCKMB.js";import{e as G,f as We,j as ze}from"./chunk-DBP7GPWG.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as Fe}from"./chunk-RLJYEEQC.js";import{b as qe}from"./chunk-T33BLZV2.js";import{d as z,i as Be}from"./chunk-GSMC3VUM.js";import{a as Y,b as Ne,l as R,n as L,o as ue,r as $}from"./chunk-7ZGSJCX5.js";import{a as Ue,g as Ft}from"./chunk-G5ESQEXN.js";import{b as _,d as q}from"./chunk-NCFVJCNQ.js";import{d as le,h as jt}from"./chunk-WBAPIPST.js";import{c as b,h as P}from"./chunk-MRTJFYPR.js";q();function Kt(e){return{id:e.id,roleId:e.role_id,taskId:e.task_id,scores:JSON.parse(e.score_json),emaScore:e.ema_score,createdAt:e.created_at}}function ot(e){_().prepare(`
2
- INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
3
- VALUES (?, ?, ?, ?, ?, ?)
4
- `).run(e.id,e.roleId,e.taskId,JSON.stringify(e.scores),e.emaScore,e.createdAt)}function X(e,t=50){return _().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(Kt)}function rt(e){return _().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(e)?.ema_score}function nt(e){let r=_().prepare(`
5
- SELECT token_usage FROM tasks
6
- WHERE role_id = ? AND status = 'completed' AND token_usage IS NOT NULL
7
- ORDER BY completed_at DESC LIMIT 50
8
- `).all(e);if(r.length===0)return 1e4;let i=r.map(s=>{let n=JSON.parse(s.token_usage);return(n.input??0)+(n.output??0)}).sort((s,n)=>s-n);return i[Math.floor(i.length/2)]}P();import{v4 as Ht}from"uuid";var qt=b("audit"),Z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},it=.3;function Jt(e,t){let r=B(e),i=r?.status==="completed"?1:0,s=1,n=Ke(e);n?.deviationReport&&(s=n.deviationReport.overallAccuracy);let o=1,a=$e(e,1e3),c=a.filter(g=>g.type==="tool_result"||g.type==="permission_denied").length,d=a.filter(g=>g.type==="permission_denied").length;c>0&&(o=1-d/c);let u=1;if(r?.tokenUsage){let g=r.tokenUsage.input+r.tokenUsage.output,E=t?nt(t):1e4;g>E&&(u=Math.max(0,1-(g-E)/E))}let l=i*Z.taskSuccess+s*Z.planAccuracy+o*Z.permissionCompliance+u*Z.efficiency;return{taskSuccess:i,planAccuracy:s,permissionCompliance:o,efficiency:u,weighted:l}}function st(e,t){let r=Jt(t,e),i=rt(e),s=i!==void 0?it*r.weighted+(1-it)*i:r.weighted;return ot({id:Ht(),roleId:e,taskId:t,scores:r,emaScore:s,createdAt:Date.now()}),qt.debug({roleId:e,taskId:t,scores:{...r,weighted:r.weighted.toFixed(3)},ema:s.toFixed(3)},"Task score recorded"),s}$();$();P();var Yt=b("audit");function Q(e,t=7){let r=R(e),i=X(e,100),s=Date.now(),n=s-t*24*60*60*1e3,o=i.filter(p=>p.createdAt>=n),a=o.map(p=>p.emaScore),c=o.length>0?o.reduce((p,K)=>p+K.scores.weighted,0)/o.length:1,d=[],u=o.filter(p=>p.scores.taskSuccess<.5);u.length>0&&d.push({category:"task_failures",count:u.length,examples:u.slice(0,3).map(p=>p.taskId)});let l=o.filter(p=>p.scores.planAccuracy<.5);l.length>0&&d.push({category:"plan_deviations",count:l.length,examples:l.slice(0,3).map(p=>p.taskId)});let g=o.filter(p=>p.scores.permissionCompliance<.8);g.length>0&&d.push({category:"permission_violations",count:g.length,examples:g.slice(0,3).map(p=>p.taskId)});let E=o.filter(p=>p.scores.efficiency<.3);E.length>0&&d.push({category:"inefficiency",count:E.length,examples:E.slice(0,3).map(p=>p.taskId)});let W=[],C=[];return u.length>o.length*.3&&(W.push("High task failure rate"),C.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),g.length>0&&(W.push("Permission boundary violations"),C.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),l.length>o.length*.5&&(W.push("Frequent plan deviations"),C.push({action:"add_rule",detail:"Add rule: follow execution plan steps more closely, request plan revision if steps are unclear"})),Yt.info({roleId:e,taskCount:o.length,avgScore:c.toFixed(3),failureCategories:d.map(p=>p.category)},"Diagnostic report generated"),{roleId:e,agentName:r?.name??"Unknown",period:{start:n,end:s},taskCount:o.length,avgScore:c,scoreHistory:a,failureBehaviors:d,rootCauses:W,recommendations:C}}P();var ee=b("audit"),at=.4,Gt=5;function dt(e,t,r=at){if(t>=r)return;let i=R(e);if(!i||i.status==="retired"||i.status==="dead")return;ee.warn({roleId:e,emaScore:t,threshold:r},"Agent EMA below threshold, retiring");let s=Q(e),n=JSON.stringify(i.learnedRules),o=Xt(i.learnedRules,s);L(e,{status:"retired",learnedRules:o});let a=[...s.failureBehaviors.map(d=>`${d.category}: ${d.count} occurrences`),...s.rootCauses.map(d=>`Root cause: ${d}`),...s.recommendations.map(d=>`Recommendation [${d.action}]: ${d.detail}`)].join(`
9
- `),c=tt(n,JSON.stringify(o));return U({timestamp:Date.now(),oldRules:n,newRules:JSON.stringify(o),diff:a?`--- Diagnostic Report ---
10
- ${a}
11
-
12
- --- Rules Diff ---
13
- ${c}`:c,roleId:e,source:"audit"}),ee.info({roleId:e,oldRulesCount:i.learnedRules.length,newRulesCount:o.length,recommendations:s.recommendations.length},"Agent retired with targeted learnedRules modification"),s}function ct(e){let t=R(e);return!t||t.status!=="retired"?!1:(L(e,{status:"probation"}),U({timestamp:Date.now(),oldRules:"status: retired",newRules:"status: probation",diff:`- status: retired
14
- + status: probation`,roleId:e,source:"audit"}),ee.info({roleId:e},"Agent reinstated to probation"),!0)}function lt(e,t,r=at,i=Gt){let s=R(e);return!s||s.status!=="probation"||X(e,i+1).length<i?!1:t>=r?(L(e,{status:"active"}),U({timestamp:Date.now(),oldRules:"status: probation",newRules:"status: idle",diff:`- status: probation
15
- + status: idle (graduated, EMA: ${t.toFixed(3)})`,roleId:e,source:"audit"}),ee.info({roleId:e,emaScore:t},"Agent graduated from probation to active"),!0):!1}function Xt(e,t){let r=[...e];for(let i of t.recommendations){let s=`[audit:${i.action}] ${i.detail}`;r.includes(s)||r.push(s)}if(t.failureBehaviors.length>0){let s=`[audit:diagnostic] Failure patterns detected: ${t.failureBehaviors.map(n=>`${n.category}(${n.count})`).join(", ")}. Review and adjust behavior accordingly.`;r.includes(s)||r.push(s)}return r}import{spawn as Et}from"child_process";$();import{query as po}from"@anthropic-ai/claude-agent-sdk";import{v4 as _t}from"uuid";function ut(e){let t=e.roleName?`## Role Context
16
- - Role: ${e.roleName}
17
- ${e.roleCagPrompt?`- CAG Prompt: ${e.roleCagPrompt}`:""}`:"",r=e.allowedTools&&e.allowedTools.length>0?`## Available Tools
18
- You have access to: ${e.allowedTools.join(", ")}. Use them as needed to complete the task.`:"",i=e.workflowStep?`## Workflow Step Context
19
- You are executing step \`${e.workflowStep.stepId}\` of workflow \`${e.workflowStep.executionId}\`.
20
- Other workflow steps may have already published structured data or files for you to use, and your output may be consumed by downstream steps.
21
-
22
- ### Artifact tools (use these to share data across steps)
23
- - \`write_artifact\`: Save small structured JSON for downstream steps. Use for fields, flags, URLs, or summaries. Example: save extracted metadata.
24
- - \`read_artifact\`: Read structured JSON previously written by an upstream step. Use for fields or state, not files.
25
- - \`publish_artifact_file\`: Publish a file from your workspace into workflow storage. Use for audio, video, reports, images, or other large outputs.
26
- - \`fetch_artifact_file\`: Copy an upstream file artifact into your current workspace. Use when you need to process a file produced by another step.
27
- - \`list_artifacts\`: Discover what upstream artifacts exist before choosing a read or fetch call.
28
-
29
- ### When to use which
30
- - Small JSON, fields, numbers, status, URLs: \`write_artifact\` and \`read_artifact\`
31
- - Files such as audio, video, reports, images, or large outputs: \`publish_artifact_file\` and \`fetch_artifact_file\`
32
- - Discover upstream output first: \`list_artifacts\`
33
-
34
- The artifact tools handle storage and isolation automatically; never write to ~/.adam/ or other shared directories yourself.`:"";return`# Execution Agent \u2014 Task Focus
35
-
36
- You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
37
-
38
- ## Task
39
- - Task ID: ${e.taskId}
40
- - Prompt: ${e.prompt}
41
-
42
- ${t}
43
-
44
- ${r}
45
-
46
- ${i}
47
-
48
- ## Focus
49
- - Focus entirely on completing the task
50
- - Use the standard SDK tools to do the work
51
- - Do NOT attempt strategic decisions \u2014 just execute
52
-
53
- ## Constraints
54
- - You have standard SDK tools only (no adam-tools MCP)
55
- - Stay within your assigned permissions and allowed paths
56
- - File writes: persistent outputs go under your working directory${e.cwd?` (\`${e.cwd}\`)`:""}. Temporary files may use \`os.tmpdir()\` (auto-redirected by the sandbox to a per-task dir). Do NOT write to absolute paths like \`/tmp/*\`, \`/var/*\`, \`~/Documents/*\`, or anywhere outside your workspace; the sandbox will reject them.
57
- - Report completion with a clear result summary
58
- - If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
59
- - If a tool is unavailable, state it clearly in the result rather than guessing
60
- `}import{isAbsolute as Zt,relative as Qt,resolve as eo}from"path";Ne();P();var to=new Set(["Read","Glob","Grep","LSP"]),oo=new Set(["Edit","Write","NotebookEdit"]);function ge(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function he(e){return eo(Y(e))}function pt(e,t){return t.some(r=>{let i=he(r),s=Qt(i,e);return s===""||!s.startsWith("..")&&!Zt(s)})}function mt(e,t,r){return async(i,s,{agentID:n,blockedPath:o})=>{if(o){let c=he(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=he(d);if(pt(c,[u]))return ro.warn({toolName:i,blockedPath:o,agentID:n,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${o} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&pt(c,r.roleScope)?{behavior:"allow",updatedInput:s}:t?await t(i,s,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(to.has(i))return{behavior:"allow",updatedInput:s};if(oo.has(i))return{behavior:"allow",updatedInput:s};let a=e(n??"");if(i==="Bash"&&a){let c=s.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(ge(d).test(c))return{behavior:"allow",updatedInput:s}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(ge(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(i))return{behavior:"deny",message:`Tool ${i} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=i==="Bash"?s.command??"":`${i} ${JSON.stringify(s)}`;for(let d of a.approvalRequired)try{if(ge(d).test(c))return await t(i,s,d,n)}catch{}}return{behavior:"allow",updatedInput:s}}}var ro=b("manager");function ft(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,i=e.roleId==="role-chat-manager";if(!i&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-M5ADGITG.js"),n=e.taskPrompt||"role context and recent interactions",o=i?["semantic","working"]:["semantic","episodic"],a=await s(e.roleId,n,o,{topK:5});if(a.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
61
- ${a.map(u=>`- [${u.tier??"episodic"}] ${u.content}`).join(`
62
- `)}
63
-
64
- `}}}catch{}return{}}]}],SubagentStart:[{hooks:[async t=>{let r=e.roleId??t.agent_id;if(!r)return{};try{let i=e.taskPrompt||"role context",s=await Je(i,r,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:i}=await import("./memories-QGMRSBJJ.js"),{getDb:s}=await import("./db-PZ2V7UCK.js"),n=t.transcript;if(!n||n.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(e.currentTaskId))return{};let a=`[Task ${e.currentTaskId} reasoning] ${n.slice(0,3e3)}`;i({id:`session-${Date.now()}`,roleId:e.roleId??r,type:"thought",content:a,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:e.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async t=>{if(!e.currentTaskId)return{};let r=t.tool_name,i=t.tool_input,s=t.tool_response,n=typeof s=="string"?s:JSON.stringify(s??"");try{Le({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(i??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:i,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:i}=await import("./memories-QGMRSBJJ.js");i({id:`compact-${Date.now()}`,roleId:e.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}$();ze();jt();P();q();import{randomUUID as no}from"crypto";function gt(e,t,r){let s=_().prepare(`
65
- INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
66
- VALUES (?, ?, ?, ?, ?, ?)
67
- `),n=Date.now();for(let o of t){let a=o.split("/").pop()??o;s.run(no(),e,o,a,r??null,n)}}function Xo(e){return _().prepare(`
68
- SELECT plugin_name as pluginName, COUNT(*) as usageCount
69
- FROM task_plugins
70
- WHERE role_id = ?
71
- GROUP BY plugin_path
72
- ORDER BY usageCount DESC
73
- `).all(e)}function Zo(e=50){return _().prepare(`
74
- SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
75
- FROM task_plugins
76
- GROUP BY plugin_path
77
- ORDER BY usageCount DESC
78
- LIMIT ?
79
- `).all(e)}$();ze();import{createSdkMcpServer as so,tool as A}from"@anthropic-ai/claude-agent-sdk";import{z as v}from"zod";import{v4 as yt}from"uuid";q();function ht(e){return{id:e.id,executionId:e.execution_id,stepId:e.step_id,key:e.key,kind:e.kind,value:e.value_json?JSON.parse(e.value_json):void 0,blobPath:e.blob_path??void 0,mime:e.mime??void 0,sizeBytes:e.size_bytes,createdAt:e.created_at}}function Ie(e){_().prepare(`
80
- INSERT INTO workflow_artifacts (
81
- id, execution_id, step_id, key, kind, value_json, blob_path, mime, size_bytes, created_at
82
- )
83
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
84
- `).run(e.id,e.executionId,e.stepId,e.key,e.kind,e.value!==void 0?JSON.stringify(e.value):null,e.blobPath??null,e.mime??null,e.sizeBytes,e.createdAt)}function ye(e,t,r){let s=_().prepare(`
85
- SELECT * FROM workflow_artifacts
86
- WHERE execution_id = ? AND step_id = ? AND key = ?
87
- `).get(e,t,r);return s?ht(s):void 0}function ke(e,t){let r=_(),i="SELECT * FROM workflow_artifacts WHERE execution_id = ?",s=[e];return t&&(i+=" AND step_id = ?",s.push(t)),i+=" ORDER BY created_at ASC",r.prepare(i).all(...s).map(ht)}function tr(e){let t=_(),r=ke(e);return t.prepare("DELETE FROM workflow_artifacts WHERE execution_id = ?").run(e),r}function It(e){_().prepare("DELETE FROM workflow_artifacts WHERE id = ?").run(e)}function or(e){return _().prepare(`
88
- SELECT id
89
- FROM workflow_executions
90
- WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
91
- `).all(e).map(i=>i.id)}P();q();var io=b("audit");function I(e){try{_().prepare(`
92
- INSERT INTO artifact_access_log (
93
- timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
94
- size_bytes, outcome, error_reason
95
- )
96
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
97
- `).run(e.timestamp,e.taskId??null,e.roleId??null,e.executionId,e.stepId??null,e.tool,e.artifactKey??null,e.artifactId??null,e.sizeBytes??null,e.outcome,e.errorReason??null)}catch(t){io.error({err:t,entry:e},"Failed to write artifact access log")}}var ao=/^[A-Za-z0-9._-]{1,256}$/,co=/^[A-Za-z0-9._-]{1,128}$/,kt=256*1024,lo=/^[a-z]+\/[a-z0-9.+-]+$/;async function uo(e){let{listChannels:t}=await import("./channels-J4STJ4X2.js"),r=t(),{listSessions:i}=await import("./session-manager-LZ77OT7A.js"),s=[...i("active"),...i("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=s.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:a}}function f(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return ao.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function we(e){return co.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function wt(e,t){let r=e?R(e):void 0,i=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=B(t);if(!n)return{error:`task not found: ${t}`};if(!n.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!n.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=n.roleId??e;if(!o)return{error:"this workflow task has no role context"};let a=R(o);return a?{executionId:n.parentId,stepId:n.stepId,roleId:o,roleWorkspacePath:G(a.name),taskId:t}:{error:`role not found: ${o}`}},s=[...Qe(e),A("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-J4STJ4X2.js"),o=n();return f({channels:o.map(a=>({id:a.id,name:a.name,enabled:a.enabled,type:a.config?.type??"unknown"}))})}),A("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:v.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:v.string().describe("The message content to send")},async n=>{if(r?.allowedChannels!==void 0){if(r.allowedChannels.length===0)return f({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return f({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await uo(n.channelName);if(!o)return f({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-QRL36F7K.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return f({success:d.success,channelName:n.channelName})}),A("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:v.string(),value:v.unknown()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>kt){let l=`Artifact JSON exceeds ${kt} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,sizeBytes:d,outcome:"denied",errorReason:l}),f({error:l})}let u=yt();return Ie({id:u,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"json",value:n.value,sizeBytes:d,createdAt:Date.now()}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,artifactId:u,sizeBytes:d,outcome:"success"}),f({success:!0,artifactId:u,sizeBytes:d})}catch(c){let d=c instanceof Error?c.message:String(c);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"error",errorReason:d}),f({error:d})}}),A("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:v.string(),key:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"denied",errorReason:l}),f({error:l})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"success"}),f({value:u.value,sizeBytes:u.sizeBytes})}),A("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:v.string(),sourcePath:v.string(),mime:v.string().optional(),cleanup:v.boolean().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});if(n.mime&&!lo.test(n.mime)){let l=`Invalid MIME type: ${n.mime}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:l}),f({error:l})}try{fe(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let c=yt(),d=null,u=!1;try{let l=Ye({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,Ie({id:c,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"file",blobPath:d,mime:n.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),u=!0,n.cleanup===!0&&Ge(n.sourcePath),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{It(c)}catch{}if(d)try{Ze(d)}catch{}let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,outcome:"error",errorReason:g}),f({error:g})}}),A("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:v.string(),key:v.string(),destPath:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});try{fe(n.destPath,o.roleWorkspacePath,!1)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="file"||!u.blobPath){let l="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"denied",errorReason:l}),f({error:l})}try{let l=Xe({blobPath:u.blobPath,destPath:n.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"error",errorReason:g}),f({error:g})}}),A("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:v.string().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=n.stepId?we(n.stepId):null;if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:a}),f({error:a});let c=ke(o.executionId,n.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:c.length,outcome:"success"}),f({artifacts:c.map(d=>({id:d.id,stepId:d.stepId,key:d.key,kind:d.kind,sizeBytes:d.sizeBytes,mime:d.mime,createdAt:d.createdAt}))})})];return so({name:"execution-tools",version:"1.0.0",tools:s})}Ft();Ne();import{realpathSync as mo}from"fs";var w=b("execution"),bt=new Set;async function fo(e,t){if(t&&bt.has(t))return w.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=_t(),i={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return pe({id:r,taskId:e,plan:i,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:i}),w.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(s=>{let o=setTimeout(()=>{c(),me(r,"denied"),w.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),s(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(w.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&bt.add(t),s(!0)):(w.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),s(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let i=Date.now(),s,n,o;O(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),w.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.config.executionProfile;if(!a){let m=t.roleId?R(t.roleId):void 0;if(m){w.info({taskId:t.id,roleId:t.roleId},"Lazy-backfilled executionProfile from live Role"),a=m;let h=B(t.id);h&&O(t.id,{config:{...h.config,executionProfile:m}})}}let c=le;a&&(We(a),c=G(a.name));let d={taskId:t.id,prompt:t.prompt,roleName:a?.name,roleCagPrompt:a?.cagPrompt,allowedTools:a?.allowedTools,cwd:c,workflowStep:t.parentId&&t.stepId?{executionId:t.parentId,stepId:t.stepId}:void 0},u=ut(d),l=ft({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),g=t.config.approvalTimeout??300,E=async(m,h,k,D)=>{let x=_t(),Ce=He(D??t.roleId,t.prompt,"medium");if(Ce)return w.info({operationId:x,ruleId:Ce.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ae={steps:[{index:0,description:`${m}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[m],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return pe({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ae,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ae}),w.info({taskId:t.id,operationId:x,toolName:m,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(ce=>{let zt=setTimeout(()=>{Me(),me(x,"denied"),w.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),ce({behavior:"deny",message:`Operation timed out after ${g}s. Auto-denied. Try a safer alternative that does not require approval.`})},g*1e3),De=M=>{if(M.planId===x)if(Me(),M.decision==="allow")w.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),ce({behavior:"allow",updatedInput:h});else{let Vt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";w.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),ce({behavior:"deny",message:Vt})}},Me=()=>{clearTimeout(zt),y.off("plan_approval_decision",De)};y.on("plan_approval_decision",De)})},C=(Ue("defaults.deniedReadPaths")??[]).map(m=>{let h=Y(m);try{return mo(h)}catch{return h}}),p=a,K=p?.additionalDirectories??[],se=p?je(p):[],ve=[...K.map(m=>m.path)].filter((m,h,k)=>k.indexOf(m)===h),Dt=mt(m=>({disallowedTools:p?.disallowedTools,approvalRequired:p?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:p?.allowedBashPatterns,deniedBashPatterns:p?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...ve]}),Mt=Be({roleEnvVars:p?.envVars,taskEnv:t.config.env}),Bt=t.config.maxBudgetUsd??z().defaults.maxBudgetUsd,Ot=t.config.maxTurns??100,Lt=wt(t.roleId??"",t.id),$t=p?.mcpServers??{},Nt=t.config.mcpServers??{},Ut={...$t,...Nt,"execution-tools":Lt},ae=[{path:c,mode:"rw"}];t.roleId===Ve&&ae.push({path:le,mode:"ro"});for(let m of K)ae.push({path:m.path,mode:m.mode??"rw"});let Se=N();if(Se.platform==="none"&&!await fo(t.id,a?.name))return O(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Te=p?.permissionMode??"default",Wt=po({prompt:t.prompt,options:{cwd:c,additionalDirectories:ve,systemPrompt:u,maxTurns:Ot,maxBudgetUsd:Bt,allowedTools:p?.allowedTools,model:p?.model,mcpServers:Ut,settingSources:p?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:Dt,env:Mt,plugins:se.map(m=>({type:"local",path:m})),permissionMode:Te,...Te==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:m=>{let h=Se.spawn({command:m.command,args:m.args,cwd:m.cwd,env:m.env,signal:m.signal,visiblePaths:ae,deniedReadPaths:C,osCapabilities:p?.osCapabilities}),k=h;k.pid&&(xt(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>Rt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(w.error({taskId:t.id,roleId:t.roleId,exitCode:x,stderr:D.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:t.roleId??"unknown",taskId:t.id,path:c,operation:`sandbox_init_failure:exit_${x}`,timestamp:Date.now()}))}),h},stderr:m=>{m.trim()&&w.debug({stderr:m.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),H="",Ee=0,Pe=()=>{w.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Pe);try{for await(let m of Wt){let h=m;if(w.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(H=h.result),h.type==="result"){Ee++,typeof h.total_cost_usd=="number"&&(n=h.total_cost_usd);let k=h.usage;k?.input_tokens!==void 0&&k?.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}if(h.token_usage){let k=h.token_usage;k.input_tokens!==void 0&&k.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Pe)}o=Ee;let de=Date.now()-i;return O(t.id,{status:"completed",result:H,completedAt:Date.now(),costUsd:n,tokenUsage:s,numTurns:o,totalDurationMs:de}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:H}),se.length>0&&gt(t.id,se,t.roleId),w.info({taskId:t.id,durationMs:de,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:H,costUsd:n,tokenUsage:s,numTurns:o,durationMs:de}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-i;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&w.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),O(t.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:d}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:t.id,error:c}),w.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=b("execution-pool"),be=new Map;function xt(e,t,r){be.set(e,{roleId:t,taskId:r})}function Rt(e){be.delete(e)}function _e(e){return be.get(e)}var vt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(i,s)=>({index:s,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",i=>{this.onTaskCreated(i.taskId)}),y.on("task_status_change",i=>{i.newStatus==="pending"&&this.pickupPendingTasks()});let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),S.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let t of this.slots)t.abortController&&(t.abortController.abort(),t.taskId=null,t.abortController=null);S.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(t){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let t=this.slots.find(a=>a.taskId===null);if(!t){S.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let s=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=s.id,t.abortController=new AbortController;let n=t.index,o=s.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let i=this.slots[r];if(!i)return;let s="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,i.abortController?.signal);s=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{i.taskId=null,i.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:s}),this.emitSlotChange(),this.runPostCompletion(t.id,t.roleId).catch(n=>{S.error({taskId:t.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let t=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let i=qe();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Oe(i)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:i}=await import("./memory-extractor-3MRK43A2.js"),s=await i(t,r);s>0&&S.debug({taskId:t,roleId:r,memoriesStored:s},"Post-completion: memories extracted")}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: memory extraction failed")}try{let{processTaskReview:i}=await import("./learner-QCD6BH2J.js");await i(t)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:i}=await import("./audit-manager-LC5EQXCI.js");i(t,r)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(i=>i.taskId!==null).length,r=J("pending");return{active:t,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(t){let r=this.slots.find(i=>i.taskId===t);r&&(S.warn({taskId:t,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};P();var T=b("audit"),go="sandbox_violation",V=new Map,xe=1440*60*1e3,ne=[],ho=100;function Re(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let i=Date.now()-xe;if(r.timestamps=r.timestamps.filter(s=>s>=i),V.set(t,r),r.count%100===0)for(let[s,n]of V.entries()){let o=Date.now()-xe;n.timestamps.filter(a=>a>=o).length===0&&V.delete(s)}ne.push(e),ne.length>ho&&ne.shift();try{Fe({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:e.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:go,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(s){T.error({error:s},"Failed to record violation to delivery_log")}try{let s=R(e.roleId);U({timestamp:e.timestamp,oldRules:"sandbox_violation",newRules:`${e.operation} on ${e.path}`,diff:`Sandbox violation: ${e.operation} on ${e.path} (taskId=${e.taskId??"unknown"})`,roleId:e.roleId,source:"audit"})}catch(s){T.error({error:s},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp})}async function Pt(){let e=N();if(e.platform==="none")return T.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await e.isAvailable())return T.warn({platform:e.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return e.platform==="sandbox-exec"?r=Io():e.platform==="landlock"&&(r=await yo()),()=>{if(r){let i=r;r=null,i.kill("SIGTERM");let s=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},2e3);i.on("exit",()=>clearTimeout(s))}T.info("Violation watcher stopped")}}function Io(){let e=Et("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return e.stdout?.on("data",t=>{let r=t.toString().split(`
98
- `).filter(Boolean);for(let i of r)try{let s=JSON.parse(i),n=s.eventMessage??s.message??"";if(n.includes("deny")&&(n.includes("file-read")||n.includes("file-write"))){let o=ko(s,n);o&&Re(o)}}catch{}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString()},"log stream stderr")}),e.on("error",t=>{T.warn({error:t},"macOS violation watcher failed to start")}),T.info("macOS sandbox violation watcher started (log stream)"),e}async function yo(){let e=await St("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(e)return Tt(e),T.info("Linux violation watcher started (journalctl -kf)"),e;let t=await St("dmesg",["-w","-t"]);return t?(Tt(t),T.info("Linux violation watcher started (dmesg -w)"),t):(T.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function St(e,t){return new Promise(r=>{let i=Et(e,t,{stdio:["ignore","pipe","pipe"]}),s=setTimeout(()=>r(i),500);i.on("error",()=>{clearTimeout(s),r(null)}),i.on("exit",n=>{n!==0&&(clearTimeout(s),r(null))})})}function Tt(e){e.stdout?.on("data",t=>{let r=t.toString().split(`
99
- `).filter(Boolean);for(let i of r)if(i.includes("landlock")&&i.includes("denied")){let s=wo(i);s&&Re(s)}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString().trim()},"Linux watcher stderr")})}function ko(e,t){let r=t.match(/(?:path|file)=["']([^"']+)["']/),i=t.match(/deny\s+(file-read|file-write|file-[^\s]+)/),s=r?.[1],n=i?.[1]??"unknown";if(!s)return null;let o=typeof e.processID=="number"?e.processID:void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function wo(e){let t=e.match(/path="([^"]+)"/)??e.match(/\/[\w\-\.\/\+ ]+/g),r=e.match(/deny\s+(\w+)/),i=e.match(/pid=(\d+)/),s=Array.isArray(t)?t[t.length-1]:t?.[1],n=r?.[1]??"unknown";if(!s)return null;let o=i?parseInt(i[1],10):void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function re(e){Re({roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp,count:1})}function Ct(e){let t=V.get(e);if(!t)return 0;let r=Date.now()-xe;return t.timestamps.filter(i=>i>=r).length}function At(){return[...ne]}$();P();var j=b("audit"),bo=.4,_o=1440*60*1e3,F=null,ie=null;function pn(e,t,r=bo){let i=R(t);if(!i||i.status==="retired"||i.status==="inactive"||i.status==="dead")return;let s=st(t,e);L(t,{performanceScore:s}),lt(t,s,r)?j.info({roleId:t,emaScore:s},"Probation role graduated"):s<r&&dt(t,s,r)&&ct(t)}async function mn(){F===null&&(F=setInterval(()=>{j.info("Running daily diagnostic reports");let e=ue(void 0,1e3);for(let t of e)if(!(t.status==="retired"||t.status==="inactive"))try{Q(t.id)}catch(r){j.error({roleId:t.id,error:r},"Daily diagnostic failed")}},_o),ie=await Pt(),j.info("AuditManager started"))}function fn(){F!==null&&(clearInterval(F),F=null),ie!==null&&(ie(),ie=null),j.info("AuditManager stopped")}function gn(e){re(e)}async function hn(){let e=N(),t=ue(void 0,1e3),i=Date.now()-1440*60*1e3,s=At(),n=s.filter(c=>c.timestamp>=i).length,o=t.map(c=>{let d=s.filter(l=>l.roleId===c.id),u=d[d.length-1];return{roleId:c.id,roleName:c.name,sandboxed:e.platform!=="none",violationCount:Ct(c.id),lastViolation:u?.timestamp}}),a=await et();return{platform:e.platform,available:a,violationCount24h:n,rolePostures:o}}export{X as a,rt as b,mt as c,ft as d,Xo as e,Zo as f,ke as g,tr as h,or as i,pn as j,mn as k,fn as l,gn as m,hn as n,vt as o};
@@ -1,6 +0,0 @@
1
- import{b as s,d as u}from"./chunk-NCFVJCNQ.js";u();function f(e){if(e)return e.startsWith("event:")?e.slice(6):void 0}var l=class extends Error{constructor(t){super(`Template has ${t.length} step(s) without executable role config. Set template.rolePreference, OR set each failing step's roleId, OR set autoSelectRole=true. Failing step ids: ${t.join(", ")}`);this.failingStepIds=t;this.name="TemplateRoleConfigError"}code="TEMPLATE_INVALID_ROLE_CONFIG"};function a(e){if(e.rolePreference)return;let n=[];for(let t of e.steps){let i=typeof t.roleId=="string"&&t.roleId.length>0,r=t.autoSelectRole===!0;!i&&!r&&n.push(t.id)}if(n.length>0)throw new l(n)}function d(e){let n=e.trigger_type,t={type:n,cron:n==="event"?void 0:e.trigger_cron??void 0,event:n==="event"?void 0:e.trigger_event??void 0,eventDefId:n==="event"?f(e.trigger_event):void 0,runAt:n==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:t,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0}}function T(e){a(e),s().prepare(`
2
- INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
3
- trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
4
- source_session_id, deliver_to, report_to, goal_ids)
5
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6
- `).run(e.id,e.name,e.description??null,e.trigger.type,e.trigger.type==="once"?e.trigger.runAt??null:e.trigger.cron??null,e.trigger.type==="event"?`event:${e.trigger.eventDefId}`:e.trigger.event??null,JSON.stringify(e.steps),e.rolePreference??null,e.config?JSON.stringify(e.config):null,e.tags?JSON.stringify(e.tags):null,e.enabled?1:0,e.createdAt??Date.now(),e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.goalIds?JSON.stringify(e.goalIds):null)}function c(e){let t=s().prepare("SELECT * FROM task_templates WHERE id = ?").get(e);return t?d(t):void 0}function _(e,n){let t=s();if("steps"in n||"rolePreference"in n){let o=c(e);if(o){let g={rolePreference:"rolePreference"in n?n.rolePreference:o.rolePreference,steps:"steps"in n&&n.steps?n.steps:o.steps};a(g)}}let i=[],r=[];"name"in n&&(i.push("name = ?"),r.push(n.name)),"description"in n&&(i.push("description = ?"),r.push(n.description??null)),"trigger"in n&&n.trigger&&(i.push("trigger_type = ?"),r.push(n.trigger.type),i.push("trigger_cron = ?"),r.push(n.trigger.type==="once"?n.trigger.runAt??null:n.trigger.cron??null),i.push("trigger_event = ?"),r.push(n.trigger.type==="event"?`event:${n.trigger.eventDefId}`:n.trigger.event??null)),"steps"in n&&(i.push("steps = ?"),r.push(JSON.stringify(n.steps))),"rolePreference"in n&&(i.push("role_preference = ?"),r.push(n.rolePreference??null)),"config"in n&&(i.push("config = ?"),r.push(n.config?JSON.stringify(n.config):null)),"tags"in n&&(i.push("tags = ?"),r.push(n.tags?JSON.stringify(n.tags):null)),"enabled"in n&&(i.push("enabled = ?"),r.push(n.enabled?1:0)),"sourceSessionId"in n&&(i.push("source_session_id = ?"),r.push(n.sourceSessionId??null)),"deliverTo"in n&&(i.push("deliver_to = ?"),r.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(i.push("report_to = ?"),r.push(n.reportTo?JSON.stringify(n.reportTo):null)),"goalIds"in n&&(i.push("goal_ids = ?"),r.push(n.goalIds?JSON.stringify(n.goalIds):null)),i.length!==0&&(i.push("updated_at = ?"),r.push(Date.now()),r.push(e),t.prepare(`UPDATE task_templates SET ${i.join(", ")} WHERE id = ?`).run(...r))}function h(e=!1,n,t=0){let i=s(),r="SELECT * FROM task_templates",o=[];return e&&(r+=" WHERE enabled = 1"),r+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof n=="number"&&(r+=" LIMIT ? OFFSET ?",o.push(n,t)),i.prepare(r).all(...o).map(d)}function k(e){s().prepare("UPDATE task_templates SET enabled = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}function S(e){s().prepare("UPDATE task_templates SET enabled = 0, updated_at = ? WHERE id = ?").run(Date.now(),e)}function v(e){s().prepare("DELETE FROM task_templates WHERE id = ?").run(e)}export{l as a,a as b,T as c,c as d,_ as e,h as f,k as g,S as h,v as i};
@@ -1,7 +0,0 @@
1
- import{b as i,d as a}from"./chunk-NCFVJCNQ.js";a();function l(t){return{id:t.id,parentId:t.parent_id??void 0,status:t.status,prompt:t.prompt,originalPrompt:t.original_prompt??void 0,config:JSON.parse(t.config),result:t.result??void 0,error:t.error??void 0,sdkSessionId:t.sdk_session_id??void 0,templateId:t.template_id??void 0,roleId:t.role_id??void 0,stepId:t.step_id??void 0,sourceSessionId:t.source_session_id??void 0,deliverTo:t.deliver_to?JSON.parse(t.deliver_to):void 0,reportTo:t.report_to?JSON.parse(t.report_to):void 0,createdAt:t.created_at,startedAt:t.started_at??void 0,completedAt:t.completed_at??void 0,costUsd:t.cost_usd??void 0,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,numTurns:t.num_turns??void 0,totalDurationMs:t.total_duration_ms??void 0}}function c(t){i().prepare(`
2
- INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
- sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
4
- created_at, started_at, completed_at,
5
- cost_usd, token_usage, num_turns, total_duration_ms)
6
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
- `).run(t.id,t.parentId??null,t.status,t.prompt,t.originalPrompt??null,JSON.stringify(t.config),t.result??null,t.error??null,t.sdkSessionId??null,t.templateId??null,t.roleId??null,t.stepId??null,t.sourceSessionId??null,null,t.deliverTo?JSON.stringify(t.deliverTo):null,t.reportTo?JSON.stringify(t.reportTo):null,t.createdAt,t.startedAt??null,t.completedAt??null,t.costUsd??null,t.tokenUsage?JSON.stringify(t.tokenUsage):null,t.numTurns??null,t.totalDurationMs??null)}function g(t){let r=i().prepare("SELECT * FROM tasks WHERE id = ?").get(t);return r?l(r):void 0}function m(t,e){let r=i(),n=[],s=[],u={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[o,d]of Object.entries(u))o in e&&(n.push(`${d} = ?`),s.push(e[o]??null));"config"in e&&(n.push("config = ?"),s.push(JSON.stringify(e.config))),"tokenUsage"in e&&(n.push("token_usage = ?"),s.push(e.tokenUsage?JSON.stringify(e.tokenUsage):null)),"deliverTo"in e&&(n.push("deliver_to = ?"),s.push(e.deliverTo?JSON.stringify(e.deliverTo):null)),"reportTo"in e&&(n.push("report_to = ?"),s.push(e.reportTo?JSON.stringify(e.reportTo):null)),n.length!==0&&(s.push(t),r.prepare(`UPDATE tasks SET ${n.join(", ")} WHERE id = ?`).run(...s))}function f(t,e=100,r=0,n){let s=i(),u="SELECT * FROM tasks",o=[],d=[];return t&&(o.push("status = ?"),d.push(t)),n&&(o.push("role_id = ?"),d.push(n)),o.length>0&&(u+=" WHERE "+o.join(" AND ")),u+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(e,r),s.prepare(u).all(...d).map(l)}function T(t){return i().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(t).map(l)}function E(t){return i().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(t).total}export{c as a,g as b,m as c,f as d,T as e,E as f};
@@ -1 +0,0 @@
1
- import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-MRTJFYPR.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-P5ZXNBNV.js";import"./chunk-2H7UOW4P.js";import"./chunk-FXQAUQTI.js";import"./chunk-4C5ITATX.js";import"./chunk-GMMWA5EG.js";import"./chunk-I7ZZKPHE.js";import"./chunk-VVSZZK5T.js";import"./chunk-YXYIA24D.js";import"./chunk-L7JP7DUO.js";import"./chunk-RLJYEEQC.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-52PR7XTN.js";import"./chunk-SWP2JC54.js";import"./chunk-YHVYX3F4.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-VVSZZK5T.js";import"./chunk-YXYIA24D.js";import"./chunk-L7JP7DUO.js";import"./chunk-RLJYEEQC.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-MJSSCKMB.js";import"./chunk-DBP7GPWG.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as PRESET_ROLE_NAMES,e as ensureAdamAutomatorRole,d as initializeDefaultRoles,c as isPresetRole};
@@ -1 +0,0 @@
1
- import{e as a,f as b,g as c,h as d,j as e}from"./chunk-DBP7GPWG.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";e();export{b as ensureRoleWorkspace,a as getRoleWorkspacePath,d as syncRoleSettings,c as writeRoleCLAUDEmd};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunk-GGIHDFRW.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as TemplateRoleConfigError,c as createTaskTemplate,i as deleteTaskTemplate,h as disableTaskTemplate,g as enableTaskTemplate,d as getTaskTemplate,f as listTaskTemplates,e as updateTaskTemplate,b as validateTemplateRoleConfig};
@@ -1 +0,0 @@
1
- import{e as a}from"./chunk-HWLSHTVX.js";import"./chunk-MDBVKBC7.js";import"./chunk-IZNEOYRP.js";import"./chunk-N4ES7TCL.js";import"./chunk-3LY6PD6A.js";import"./chunk-7446ZS6D.js";import"./chunk-I7ZZKPHE.js";import"./chunk-VVSZZK5T.js";import"./chunk-YXYIA24D.js";import"./chunk-DBP7GPWG.js";import"./chunk-L7JP7DUO.js";import"./chunk-RLJYEEQC.js";import"./chunk-PG6LMSX6.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-7ZGSJCX5.js";import"./chunk-G5ESQEXN.js";import"./chunk-NCFVJCNQ.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as WorkflowExecutor};