adam-agent-server 1.8.1 → 1.10.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 (150) hide show
  1. package/README.md +8 -0
  2. package/dist/App-5QZKMPRM.js +13 -0
  3. package/dist/adam-tools-UJKLRMNR.js +1 -0
  4. package/dist/approval-handler-J6RUTICJ.js +1 -0
  5. package/dist/audit-manager-PFX36RMN.js +1 -0
  6. package/dist/bree-engine-445HR6VH.js +1 -0
  7. package/dist/channels-OOIM62BX.js +1 -0
  8. package/dist/{channels-ULFUCUUZ.js → channels-WFC26TED.js} +1 -1
  9. package/dist/{chunk-6KF7OO2B.js → chunk-2VBGTGDK.js} +8 -8
  10. package/dist/{chunk-PG6LMSX6.js → chunk-5AUQIK3Q.js} +1 -1
  11. package/dist/chunk-6JBSBSCL.js +1 -0
  12. package/dist/{chunk-NUITL62I.js → chunk-7T4B2MZ7.js} +1 -1
  13. package/dist/{chunk-M4YI4WVX.js → chunk-AMHO3ALG.js} +1 -1
  14. package/dist/{chunk-5EPG2US5.js → chunk-AQO6IIHV.js} +45 -16
  15. package/dist/chunk-AVM3O74V.js +5 -0
  16. package/dist/{chunk-FPZEZYUB.js → chunk-B44X7JAJ.js} +1 -1
  17. package/dist/{chunk-RI3V72RP.js → chunk-B544JOZM.js} +2 -2
  18. package/dist/chunk-D5LZGIJU.js +6 -0
  19. package/dist/chunk-ETK722ZZ.js +27 -0
  20. package/dist/chunk-ETOTUZPB.js +77 -0
  21. package/dist/{chunk-2YTDCR6A.js → chunk-FUWPDXXG.js} +1 -1
  22. package/dist/{chunk-T33BLZV2.js → chunk-HSEP6LNQ.js} +1 -1
  23. package/dist/chunk-JRQQLKLU.js +145 -0
  24. package/dist/chunk-JYHOGBCP.js +12 -0
  25. package/dist/{chunk-NASJH4NT.js → chunk-MQWYGDNT.js} +1 -1
  26. package/dist/{chunk-5QZXYKMS.js → chunk-NPIXYK5G.js} +1 -1
  27. package/dist/chunk-O7XQSONJ.js +5 -0
  28. package/dist/chunk-OFTIPZTH.js +1 -0
  29. package/dist/{chunk-NWMOV23A.js → chunk-Q2ISNOBQ.js} +1 -1
  30. package/dist/chunk-QMW7VEPC.js +0 -0
  31. package/dist/{chunk-JJH2RCVC.js → chunk-QYRI4HYA.js} +1 -1
  32. package/dist/chunk-R2WB5BKF.js +7 -0
  33. package/dist/{chunk-WMB7P64J.js → chunk-RMGBR3XZ.js} +1 -1
  34. package/dist/chunk-S6OV7Z6K.js +1 -0
  35. package/dist/{chunk-BQ3ZAYHC.js → chunk-SC2DDRYB.js} +1 -1
  36. package/dist/chunk-SZBWLHP6.js +80 -0
  37. package/dist/{chunk-HQRUJQN7.js → chunk-U2LBBBWO.js} +4 -4
  38. package/dist/chunk-UXDTFTG5.js +10 -0
  39. package/dist/chunk-WQFNB2MQ.js +32 -0
  40. package/dist/chunk-X5V4VMET.js +26 -0
  41. package/dist/{chunk-GSFLLRS7.js → chunk-Y5FFL6UO.js} +1 -1
  42. package/dist/{chunk-UQJZU3R5.js → chunk-YVVKUPGL.js} +1 -1
  43. package/dist/chunk-Z434UGTC.js +50 -0
  44. package/dist/{chunk-EQZFOBAJ.js → chunk-ZFDULJGB.js} +1 -1
  45. package/dist/chunk-ZQ4PNKMQ.js +10 -0
  46. package/dist/cli.js +2 -2
  47. package/dist/{config-HBQPBIWL.js → config-GKVOAMY2.js} +1 -1
  48. package/dist/config-W2OD7PXZ.js +1 -0
  49. package/dist/{db-QEWTZGU3.js → db-FACSMWEY.js} +1 -1
  50. package/dist/delivery-log-JIQMHBJ5.js +1 -0
  51. package/dist/engine-OHYWUUMJ.js +1 -0
  52. package/dist/evolution-audit-M7FSYRQR.js +1 -0
  53. package/dist/{external-api-V74YTLBY.js → external-api-QKRNGSYS.js} +1 -1
  54. package/dist/index.js +29 -17
  55. package/dist/learner-OUNQSWN7.js +1 -0
  56. package/dist/{memories-VMOGFVPU.js → memories-ABE7PMQL.js} +1 -1
  57. package/dist/memory-extractor-ZX2NJIBV.js +6 -0
  58. package/dist/memory-service-UWER3T2S.js +1 -0
  59. package/dist/outbound-gateway-XDCGAXXW.js +1 -0
  60. package/dist/presets-R3D4E6SK.js +1 -0
  61. package/dist/role-presets-7JIX34HF.js +1 -0
  62. package/dist/role-workspace-ISGPO25D.js +1 -0
  63. package/dist/{roles-ZYCFQMAY.js → roles-WNKRM6FD.js} +1 -1
  64. package/dist/{runtime-VDBZZ4KG.js → runtime-YPBWWMXW.js} +1 -1
  65. package/dist/session-manager-MTO4OGLM.js +1 -0
  66. package/dist/{task-templates-4KCZOUN5.js → task-templates-SNKZJ3DI.js} +1 -1
  67. package/dist/workflow-executor-3OCSVMM5.js +1 -0
  68. package/package.json +2 -1
  69. package/web/dist/assets/{AlertDialog-B1zj0Qs3.js → AlertDialog-DhA65f_0.js} +1 -1
  70. package/web/dist/assets/{Button-BehrGSvy.js → Button-CYDgoTTo.js} +1 -1
  71. package/web/dist/assets/{Card-B5E56u94.js → Card-DDGXsHus.js} +1 -1
  72. package/web/dist/assets/{ChannelDetail-CH1_E5eJ.js → ChannelDetail-Bb8P8It_.js} +1 -1
  73. package/web/dist/assets/{Channels-zp0S8sCC.js → Channels-8j28oydE.js} +2 -2
  74. package/web/dist/assets/{Chat-BZpf1DSF.js → Chat-BZwLDoYO.js} +2 -2
  75. package/web/dist/assets/{Dashboard-sTpDhdNJ.js → Dashboard-Cv0AtO-o.js} +1 -1
  76. package/web/dist/assets/{EmptyState-tTclFq_B.js → EmptyState-EuQHAv5Y.js} +1 -1
  77. package/web/dist/assets/{EnvVarEditor-ZHeyPSe1.js → EnvVarEditor-r-l-u4V7.js} +1 -1
  78. package/web/dist/assets/{EventDefDetail-C91lkfDi.js → EventDefDetail-asUFrbQE.js} +1 -1
  79. package/web/dist/assets/Events-DtkHL-r2.js +1 -0
  80. package/web/dist/assets/{Evolution-BtPy3Vgk.js → Evolution-DIqYOSb8.js} +1 -1
  81. package/web/dist/assets/FeatureRequests-BxPqLR1x.js +1 -0
  82. package/web/dist/assets/{GoalDetail-WsCAu4BR.js → GoalDetail-Bkvgg6uI.js} +1 -1
  83. package/web/dist/assets/Goals-CkKJDCiU.js +1 -0
  84. package/web/dist/assets/{Logs-DivMVgny.js → Logs-DnaaHV0Y.js} +1 -1
  85. package/web/dist/assets/{Memories-Dvs4gh22.js → Memories-Dq9S-Tsi.js} +1 -1
  86. package/web/dist/assets/Mistakes-D5lW31Co.js +1 -0
  87. package/web/dist/assets/{NotFound-D-OII_Lp.js → NotFound-gJVrOtER.js} +1 -1
  88. package/web/dist/assets/{PageHeader-B2CgcZ-t.js → PageHeader-CugYeCci.js} +1 -1
  89. package/web/dist/assets/Plugins-CoRmK2UG.js +1 -0
  90. package/web/dist/assets/{RoleDetail-D9nwUaoB.js → RoleDetail-BHJA_PAn.js} +2 -2
  91. package/web/dist/assets/Roles-EBUueS_P.js +1 -0
  92. package/web/dist/assets/{SectionHeader-CmXz6PM3.js → SectionHeader-DihC0CnO.js} +1 -1
  93. package/web/dist/assets/Settings-DZHAGazz.js +1 -0
  94. package/web/dist/assets/{Strategies-BL3By49Q.js → Strategies-3IV9eueQ.js} +1 -1
  95. package/web/dist/assets/{Switch-B1V9n5dB.js → Switch-B3w5KMMc.js} +1 -1
  96. package/web/dist/assets/{Table-CXAcZ8Ru.js → Table-Cf6m8zLu.js} +1 -1
  97. package/web/dist/assets/{TaskDetail-BGIVc4hi.js → TaskDetail-BmXaH3sx.js} +2 -2
  98. package/web/dist/assets/Work-CvQrOKtL.js +1 -0
  99. package/web/dist/assets/api-D-UzHSDq.js +1 -0
  100. package/web/dist/assets/index-BsKlGx3x.js +2 -0
  101. package/web/dist/assets/index-EqsPGp9a.css +2 -0
  102. package/web/dist/assets/{useIsMobileLayout-dYzXP1EC.js → useIsMobileLayout-2GbB90oO.js} +1 -1
  103. package/web/dist/assets/{vendor-icons-Dk0hMuJz.js → vendor-icons-PF9RcPJx.js} +1 -1
  104. package/web/dist/assets/{vendor-react-C6faO6LO.js → vendor-react-Cxy4EVtR.js} +1 -1
  105. package/web/dist/assets/{vendor-state-DahK0J-G.js → vendor-state-aQJ7d4tA.js} +1 -1
  106. package/web/dist/index.html +8 -8
  107. package/dist/App-ZRCRM7WR.js +0 -13
  108. package/dist/adam-automator-skills-EZGBICHT.js +0 -18
  109. package/dist/adam-tools-VRGMBVKL.js +0 -1
  110. package/dist/approval-handler-PB7PSLUS.js +0 -1
  111. package/dist/audit-manager-BSBBDUER.js +0 -1
  112. package/dist/bree-engine-7S33CWS7.js +0 -1
  113. package/dist/channels-SITUUC4J.js +0 -1
  114. package/dist/chunk-2L2347UQ.js +0 -5
  115. package/dist/chunk-4PQHGLZH.js +0 -99
  116. package/dist/chunk-5XOTPEAK.js +0 -6
  117. package/dist/chunk-A5OCDYTW.js +0 -29
  118. package/dist/chunk-AQ3ASS4B.js +0 -12
  119. package/dist/chunk-B6LOT5CG.js +0 -10
  120. package/dist/chunk-BCH2HAIM.js +0 -23
  121. package/dist/chunk-DVN3BFPP.js +0 -26
  122. package/dist/chunk-GSMC3VUM.js +0 -1
  123. package/dist/chunk-IKPYPZ64.js +0 -10
  124. package/dist/chunk-IZNEOYRP.js +0 -1
  125. package/dist/chunk-K4C43YDD.js +0 -7
  126. package/dist/chunk-OB2UQOBG.js +0 -79
  127. package/dist/chunk-QGYDGZSC.js +0 -49
  128. package/dist/chunk-RZ7LCZVK.js +0 -5
  129. package/dist/chunk-ULTK7RD6.js +0 -27
  130. package/dist/config-ZBNGRASI.js +0 -1
  131. package/dist/delivery-log-AC476GX7.js +0 -1
  132. package/dist/engine-6K4RG644.js +0 -1
  133. package/dist/evolution-audit-XMBDUN3T.js +0 -1
  134. package/dist/learner-VCS3Q7BR.js +0 -1
  135. package/dist/memory-extractor-4WJNHYWR.js +0 -6
  136. package/dist/memory-service-ZS6MBUIC.js +0 -1
  137. package/dist/outbound-gateway-H7RFG6D2.js +0 -1
  138. package/dist/role-presets-XAEOYEAW.js +0 -1
  139. package/dist/role-workspace-NKGAH6J6.js +0 -1
  140. package/dist/session-manager-COLCNIB7.js +0 -1
  141. package/dist/workflow-executor-Z7JFMR56.js +0 -1
  142. package/web/dist/assets/Events-QnTwC2ul.js +0 -1
  143. package/web/dist/assets/Goals-DndYDSwn.js +0 -1
  144. package/web/dist/assets/Plugins-B0Eg_ELU.js +0 -1
  145. package/web/dist/assets/Roles-CihcHqKx.js +0 -1
  146. package/web/dist/assets/Settings-CftLrCHX.js +0 -1
  147. package/web/dist/assets/Work-BzNrHYxu.js +0 -1
  148. package/web/dist/assets/api-Bux34u4-.js +0 -1
  149. package/web/dist/assets/index-Cu5neZGw.css +0 -2
  150. package/web/dist/assets/index-TFQC0SLN.js +0 -2
package/README.md CHANGED
@@ -469,3 +469,11 @@ curl -X POST http://localhost:7100/tasks \
469
469
  | FS | 1 个 | 文件操作 |
470
470
  | 健康检查 | 3 个 | 存活、就绪、指标 |
471
471
  | WebSocket | 3 个 | 任务流 + 全局事件 + Chat 流 |
472
+
473
+ ---
474
+
475
+ ## Contact
476
+
477
+ - X (Twitter): [@norvynzhang](https://x.com/norvynzhang)
478
+ - GitHub: [n0rvyn](https://github.com/n0rvyn)
479
+ - Email: [norvynzhang@gmail.com](mailto:norvynzhang@gmail.com)
@@ -0,0 +1,13 @@
1
+ import{b as v,d as so,e as er}from"./chunk-PHT24MOV.js";import{a as no,f as Zo,h as Jo}from"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";import{Box as to,Text as Ut,useInput as di}from"ink";import{useState as ui,useEffect as Co,useRef as Go}from"react";import{createContext as xn,useContext as Tn,useReducer as hn}from"react";import{jsx as vn}from"react/jsx-runtime";var yn={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 bn(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 tr=xn(null);function or({children:e}){let[t,o]=hn(bn,yn);return vn(tr.Provider,{value:{state:t,dispatch:o},children:e})}function Je(){let e=Tn(tr);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as rr,useRef as nr}from"react";var Cn=15e3;function sr(){let{state:e,dispatch:t}=Je(),o=nr(null),x=nr(null);rr(()=>{x.current=e.session?.id??null},[e.session?.id]),rr(()=>{let m=!0,u=null,l=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{l(),o.current=setTimeout(()=>{m&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Cn)};return(()=>{try{u=new so("/events"),u.on("task_status_change",()=>{}),u.on("approval_request",n=>{if(!m)return;let d=n;t({type:"SET_PENDING_APPROVAL",approval:{taskId:d.taskId,approvalId:d.approvalId,toolName:d.toolName,toolInput:d.toolInput,matchedPattern:d.matchedPattern}})}),u.on("plan_approval_request",n=>{if(!m)return;let d=n;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:d.taskId,planId:d.planId,roleId:d.roleId,plan:d.plan}})}),u.on("plan_approval_decision",()=>{m&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),u.on("config_changed",()=>{m&&t({type:"CONFIG_CHANGED"})}),u.on("execution_task_start",n=>{if(!m)return;let d=n,g=x.current;g&&(async()=>{try{let k=await v(`/tasks/${d.taskId}`);m&&k.sourceSessionId===g&&t({type:"SET_ACTIVE_TASK",taskId:d.taskId})}catch{}})()}),u.on("stats_update",n=>{if(!m)return;let d=n;t({type:"UPDATE_STATS",activeTasks:d.activeTasks,queuedTasks:d.queuedTasks,costToday:d.totalCostToday})}),u.connect().then(async()=>{if(m){l(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let n=await v("/version");t({type:"SET_VERSION",version:n.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,l(),u?.close()}},[t])}import{useEffect as wn,useRef as Sn,useState as ir,useCallback as kn}from"react";function ar(e){let[t,o]=ir([]),[x,m]=ir(!1),u=Sn(null),l=kn(()=>{o([]),m(!1)},[]);return wn(()=>{if(!e)return;let i=!0;o([]),m(!0);try{let a=new er(e);return u.current=a,a.on("reasoning",n=>{if(!i)return;let g=n.content??"";o(k=>{let T=k[k.length-1];if(T?.type==="reasoning"){let S=[...k];return S[S.length-1]={...T,content:T.content+g},S}return[...k,{type:"reasoning",content:g,timestamp:Date.now()}]})}),a.on("tool_call",n=>{if(!i)return;let d=n;o(g=>[...g,{type:"tool_call",content:d.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:d.toolName}}])}),a.on("tool_result",n=>{if(!i)return;let d=n;o(g=>[...g,{type:"tool_result",content:d.content??"",timestamp:Date.now()}])}),a.on("error",n=>{if(!i)return;let d=n;o(g=>[...g,{type:"error",content:d.error??"unknown error",timestamp:Date.now()}])}),a.on("complete",n=>{if(!i)return;let d=n;o(g=>[...g,{type:"complete",content:d.result??"",timestamp:Date.now(),metadata:{cost:d.costUsd,turns:d.numTurns,duration:d.totalDurationMs}}]),m(!1)}),a.connect().catch(()=>{i&&(o(n=>[...n,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),m(!1))}),()=>{i=!1,a.close()}}catch{m(!1)}},[e]),{events:t,isStreaming:x,clearEvents:l}}import{useState as Bo,useEffect as Bn,useCallback as Ht}from"react";function Eo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function lr(){let[e,t]=Bo(null),[o,x]=Bo(!0),[m,u]=Bo(null),l=Ht(async()=>{try{let k=(await v("/chat/sessions?status=active")).sessions.find(T=>T.source.type==="tui");return k?Eo(k):null}catch{return null}},[]),i=Ht(async()=>{try{let g=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),k=Eo(g.session);return t(k),k}catch{return u("Failed to create session"),null}},[]),a=Ht(async g=>{try{let k=await v("/chat/messages",{method:"POST",body:{content:g,source:{type:"tui"}}});return t(T=>T&&{...T,messageCount:T.messageCount+1,lastActiveAt:Date.now()}),k}catch{return null}},[]),n=Ht(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),d=Ht(async()=>{if(e)try{let g=await v(`/chat/sessions/${e.id}`);t(Eo(g.session))}catch{t(null)}},[e]);return Bn(()=>{let g=!1;async function k(){x(!0);let T=await l();g||(T?t(T):await i(),g||x(!1))}return k(),()=>{g=!0}},[]),{session:e,loading:o,error:m,sendMessage:a,createNewSession:i,archiveCurrentSession:n,refreshSession:d,setSession:t}}import{useEffect as cr,useRef as En,useState as In}from"react";function dr(e){let[t,o]=In(null),x=En(new Set);return cr(()=>{if(!e)return;let m=!0,u=null;try{u=new so("/chat/stream"),u.on("chat_message",l=>{if(!m)return;let a=l.message;a&&a.sessionId===e&&a.role==="assistant"&&(x.current.has(a.id)||(x.current.add(a.id),o(a)))}),u.connect().catch(()=>{})}catch{}return()=>{m=!1,u?.close()}},[e]),cr(()=>{x.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as Io,Text as De}from"ink";import{Fragment as io,jsx as pe,jsxs as Pt}from"react/jsx-runtime";var An=90;function ur({children:e}){return pe(Io,{children:e})}function mr(){let{state:e}=Je(),t=e.session,x=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,m=e.connected?"up":"down",u=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),l=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,a=(process.stdout.columns??100)<An,n=Pt(io,{children:[pe(De,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),pe(De,{dimColor:!0,children:" | "}),pe(De,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),pe(De,{children:` ${m}`}),pe(De,{dimColor:!0,children:" | "}),pe(De,{children:u.toLowerCase()})]}),d=Pt(io,{children:[pe(De,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),pe(De,{dimColor:!0,children:" | "}),pe(De,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&Pt(io,{children:[pe(De,{dimColor:!0,children:" | "}),pe(De,{children:l}),x&&Pt(io,{children:[pe(De,{dimColor:!0,children:" | "}),pe(De,{color:"yellow",children:"timeout"})]})]})]});return a?Pt(Io,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[pe(ur,{children:n}),pe(ur,{children:d})]}):Pt(Io,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[n,pe(De,{dimColor:!0,children:" | "}),d]})}import{Box as ao,Text as lo,useInput as Dn}from"ink";import{useState as Po,useMemo as Rn}from"react";import Mn from"ink-text-input";var Pn=[{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 Ao(e){let t=e.toLowerCase();return Pn.filter(o=>o.name.startsWith(t))}function gr(e){let t=Ao(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as co,jsxs as jt}from"react/jsx-runtime";function fr({onSubmit:e}){let[t,o]=Po(""),[x,m]=Po(0),[u,l]=Po(!1),i=t.startsWith("/")&&t.length>=1,a=t.slice(1),n=Rn(()=>i?Ao(a):[],[i,a]),d=T=>{o(T),T.startsWith("/")?(l(!0),m(0)):l(!1)},g=()=>{let T=t.trim();if(T){if(T.startsWith("/")){let S=T.slice(1),r=gr(S);e(r?`/${r.name}`:T)}else e(T);o(""),l(!1)}},k=T=>{e(`/${T.name}`),o(""),l(!1)};return Dn((T,S)=>{if(!(!u||!i||n.length===0)){if(S.upArrow){m(r=>r<=0?n.length-1:r-1);return}if(S.downArrow){m(r=>r>=n.length-1?0:r+1);return}if(S.tab){let r=n[x];r&&k(r);return}if(S.escape){l(!1),o("");return}}},{isActive:u&&i&&n.length>0}),jt(ao,{flexDirection:"column",children:[u&&i&&n.length>0&&co(ao,{flexDirection:"column",marginBottom:0,paddingX:1,children:n.map((T,S)=>{let r=S===x;return jt(ao,{children:[co(lo,{color:r?"cyan":"gray",bold:r,children:r?"\u25B8 ":" "}),jt(lo,{color:r?"cyan":"white",bold:r,children:["/",T.name]}),jt(lo,{dimColor:!0,children:[" \u2014 ",T.description]})]},T.name)})}),jt(ao,{borderStyle:"round",borderDimColor:!0,children:[co(lo,{bold:!0,children:"\u25B8 "}),co(Mn,{value:t,onChange:d,onSubmit:g,placeholder:"Type a message or / for commands..."})]})]})}import{Box as Dt,Text as Be,useInput as $n}from"ink";import{useState as Nn}from"react";import{jsx as Le,jsxs as et}from"react/jsx-runtime";function _n({content:e,expanded:t}){let o=e.split(`
2
+ `);return o.length<=5?Le(Be,{color:"green",children:e}):t?Le(Be,{color:"green",children:e}):et(Be,{color:"green",children:[o.slice(0,3).join(`
3
+ `),`
4
+ `,et(Be,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function Ln({event:e,expanded:t}){switch(e.type){case"reasoning":return Le(Dt,{children:Le(Be,{color:"gray",children:e.content})});case"tool_call":return Le(Dt,{children:et(Be,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return et(Dt,{flexDirection:"column",children:[Le(Be,{color:"blue",dimColor:!0,children:"[result]"}),Le(_n,{content:e.content,expanded:t})]});case"error":return Le(Dt,{children:et(Be,{color:"red",children:["[error] ",e.content]})});case"complete":return et(Dt,{flexDirection:"column",marginTop:1,children:[e.content&&Le(Be,{children:e.content}),Le(Be,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&et(Be,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&et(Be,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&et(Be,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function pr({events:e,isStreaming:t}){let[o,x]=Nn(!1),m=e.some(u=>u.type==="tool_result"&&u.content.split(`
5
+ `).length>5);return $n((u,l)=>{l.ctrl&&u==="o"&&x(i=>!i)},{isActive:m}),e.length===0&&!t?null:et(Dt,{flexDirection:"column",children:[t&&e.length===0&&Le(Be,{dimColor:!0,children:"Waiting for response..."}),e.map((u,l)=>Le(Ln,{event:u,expanded:o},l)),m&&Le(Be,{dimColor:!0,children:o?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as xr,Text as Tr}from"ink";import{jsx as Do,jsxs as On}from"react/jsx-runtime";function hr({messages:e}){return e.length===0?null:Do(xr,{flexDirection:"column",children:e.map((t,o)=>On(xr,{flexDirection:"column",marginBottom:1,children:[Do(Tr,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),Do(Tr,{children:t.content})]},o))})}import{Box as Kt,Text as tt,useInput as Vn}from"ink";import{jsx as ot,jsxs as zt}from"react/jsx-runtime";function yr({approval:e,onResolved:t}){return Vn(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())}),zt(Kt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[ot(tt,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),zt(Kt,{marginTop:1,children:[ot(tt,{children:"Tool: "}),ot(tt,{bold:!0,children:e.toolName})]}),zt(Kt,{children:[ot(tt,{children:"Input: "}),ot(tt,{children:JSON.stringify(e.toolInput)})]}),zt(Kt,{children:[ot(tt,{children:"Pattern: "}),ot(tt,{dimColor:!0,children:e.matchedPattern})]}),zt(Kt,{marginTop:1,children:[ot(tt,{color:"green",children:"[a] Approve"}),ot(tt,{children:" "}),ot(tt,{color:"red",children:"[r] Reject"})]})]})}import{Box as Xt,Text as Ee,useInput as qn}from"ink";import{useState as Fn,useEffect as Un}from"react";import{jsx as ct,jsxs as ze}from"react/jsx-runtime";var Wn=300;function br({approval:e,onResolved:t,onTimeout:o}){let[x,m]=Fn(Wn);Un(()=>{let l=setInterval(()=>{m(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),qn(l=>{l==="a"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let u=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return ze(Xt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ct(Ee,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),ze(Ee,{dimColor:!0,children:["Plan ID: ",e.planId]}),ze(Ee,{dimColor:!0,children:["Time remaining: ",x,"s"]}),ze(Xt,{marginTop:1,children:[ct(Ee,{children:"Overall Risk: "}),ct(Ee,{bold:!0,color:u,children:e.plan.overallRisk.toUpperCase()})]}),ze(Ee,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return ze(Xt,{paddingLeft:2,children:[ze(Ee,{children:["[",l.index,"] "]}),ct(Ee,{children:l.description}),ze(Ee,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),ze(Ee,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),ze(Xt,{marginTop:1,children:[ct(Ee,{dimColor:!0,children:"Permissions: "}),ct(Ee,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),ze(Xt,{marginTop:1,children:[ct(Ee,{color:"green",children:"[a] Allow once "}),ct(Ee,{color:"green",children:"[p] Allow permanent "}),ct(Ee,{color:"red",children:"[r] Deny"})]})]})}import{Box as xe,Text as j,useInput as Zn}from"ink";import{useEffect as Jn,useState as ht,useCallback as Br}from"react";import{Box as ge,Text as F,useInput as Gn}from"ink";import{useEffect as Hn,useState as Rt}from"react";import{jsx as ie,jsxs as G}from"react/jsx-runtime";var vr={plan:!0,result:!1,routing:!0,error:!0},jn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function kr({taskId:e,onBack:t}){let[o,x]=Rt(null),[m,u]=Rt([]),[l,i]=Rt([]),[a,n]=Rt(null),[d,g]=Rt(vr),[k,T]=Rt(!1);Hn(()=>{let h=!1;return x(null),u([]),i([]),n(null),g(vr),T(!1),v(`/tasks/${e}`).then(({task:B})=>{h||x(B)}).catch(B=>{h||n(B instanceof Error?B.message:String(B))}),v(`/tasks/${e}/plan`).then(({plans:B})=>{h||u(B)}).catch(()=>{h||u([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:B})=>{h||i(B)}).catch(()=>{h||i([])}),()=>{h=!0}},[e]);let S=h=>{g(B=>({...B,[h]:!B[h]}))};if(Gn((h,B)=>{if(h==="b"||B.escape){t();return}h==="1"&&S("plan"),h==="2"&&S("result"),h==="3"&&S("routing"),h==="4"&&S("error"),h==="5"&&T(H=>!H)}),a)return G(ge,{flexDirection:"column",children:[G(F,{color:"red",children:["Task detail failed: ",a]}),ie(F,{dimColor:!0,children:"[b] Back"})]});if(!o)return G(F,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let r=m[0],s=Qn(o.deliverTo,o.reportTo),E=l.length>0?`${l.length} delivery event${l.length===1?"":"s"}`:"No delivery events";return G(ge,{flexDirection:"column",children:[G(ge,{children:[G(F,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ie(F,{dimColor:!0,children:" \u2022 "}),ie(F,{color:jn[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),G(F,{dimColor:!0,children:[o.roleId?`role ${o.roleId}`:"no role"," \u2022 ",Sr(o.createdAt)," \u2022 ",Xn(o.totalDurationMs)]}),G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{bold:!0,children:"Summary"}),ie(F,{children:k?o.prompt:Kn(o.prompt,240)}),o.prompt.length>240&&G(F,{dimColor:!0,children:["[5] ",k?"collapse prompt":"expand prompt"]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{dimColor:!0,children:["Cost: ",zn(o.costUsd)]}),G(F,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),G(F,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),G(F,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[1] Plan ",d.plan?"hide":"show"]}),ie(F,{dimColor:!0,children:r?`${r.plan.steps.length} planned step${r.plan.steps.length===1?"":"s"} \u2022 ${r.plan.overallRisk} risk \u2022 ${r.status}`:"No execution plan"}),d.plan&&r&&G(ge,{marginTop:1,flexDirection:"column",children:[r.plan.steps.map(h=>G(ge,{flexDirection:"column",marginBottom:1,children:[G(F,{children:[h.index,". ",h.description]}),G(F,{dimColor:!0,children:[h.riskLevel," risk \u2022 ",h.toolsNeeded.join(", ")||"no tools listed"]}),h.expectedOutput?G(F,{dimColor:!0,children:["Expected: ",h.expectedOutput]}):null]},h.index)),r.learnedRules&&r.learnedRules.length>0&&G(ge,{flexDirection:"column",children:[ie(F,{color:"blue",bold:!0,children:"Learned Rules"}),r.learnedRules.map((h,B)=>G(F,{dimColor:!0,children:["\u2022 ",h]},B))]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[2] Result ",d.result?"hide":"show"]}),ie(F,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),d.result&&ie(ge,{marginTop:1,children:ie(F,{children:o.result?wr(o.result,18):"No result yet."})})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[3] Routing ",d.routing?"hide":"show"]}),G(F,{dimColor:!0,children:[s," \u2022 ",E]}),d.routing&&G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Deliver To"}),Cr(o.deliverTo),ie(F,{color:"cyan",children:"Report To"}),Cr(o.reportTo),l.length>0&&G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Recent Delivery"}),l.map(h=>G(F,{dimColor:!0,children:[h.status," \u2022 ",Yn(h)," \u2022 ",Sr(h.createdAt)]},h.id))]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[4] Error ",d.error?"hide":"show"]}),ie(F,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),d.error&&o.error&&ie(ge,{marginTop:1,children:ie(F,{color:"red",children:wr(o.error,16)})})]}),ie(ge,{marginTop:1,children:ie(F,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function Cr(e){return!e||e.length===0?ie(F,{dimColor:!0,children:" none"}):ie(ge,{flexDirection:"column",children:e.map((t,o)=>ie(F,{dimColor:!0,children:t.type==="channel"?` channel ${t.channelId.slice(0,8)}${t.chatId?` / ${t.chatId.slice(0,8)}`:""}`:` session ${t.sessionId.slice(0,8)}`},`${t.type}-${o}`))})}function wr(e,t){let o=e.split(`
6
+ `);return o.length<=t?e:`${o.slice(0,t).join(`
7
+ `)}
8
+ \u2026`}function Kn(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function zn(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Xn(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),x=t%60;return x===0?`${o}m`:`${o}m ${x}s`}function Sr(e){return new Date(e).toLocaleString()}function Qn(e,t){let o=e?.length??0,x=t?.length??0;return o===0&&x===0?"No delivery targets":`${o} output target${o===1?"":"s"} \u2022 ${x} report target${x===1?"":"s"}`}function Yn(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 ts,jsx as ee,jsxs as te}from"react/jsx-runtime";var Er={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},uo=["all","pending","queued","running","completed","failed","cancelled","blocked"],Ro=15;function go({onBack:e}){let[t,o]=ht([]),[x,m]=ht(!0),[u,l]=ht("list"),[i,a]=ht(0),[n,d]=ht("all"),[g,k]=ht(0),[T,S]=ht(0),[r,s]=ht(null),E=Br(async()=>{m(!0);try{let D=new URLSearchParams({limit:"100"});n!=="all"&&D.set("status",n);let L=await v(`/tasks?${D}`);o(L.tasks)}catch{o([])}finally{m(!1)}},[n]);Jn(()=>{E()},[E]);let h=Math.max(1,Math.ceil(t.length/Ro)),B=t.slice(T*Ro,(T+1)*Ro),H=Br(async()=>{let D=B[i];if(D)try{await v(`/tasks/${D.id}/cancel`,{method:"POST"}),s(`Cancelled: ${D.id.slice(0,8)}`),l("list"),E()}catch(L){s(`Failed: ${L instanceof Error?L.message:String(L)}`),l("list")}},[B,i,E]);if(Zn((D,L)=>{if(u==="detail"){(L.escape||L.return||D==="q")&&l("list");return}if(u==="cancelling"){D==="y"?H():l("list");return}if(u==="filter"){if(L.escape){l("list");return}L.upArrow&&g>0&&k(N=>N-1),L.downArrow&&g<uo.length-1&&k(N=>N+1),L.return&&(d(uo[g]),S(0),a(0),l("list"));return}if(L.escape||D==="q"){e();return}if(L.upArrow&&i>0&&a(N=>N-1),L.downArrow&&i<B.length-1&&a(N=>N+1),L.return&&B[i]&&l("detail"),D==="x"&&B[i]){let N=B[i];["running","pending","queued","paused"].includes(N.status)?(l("cancelling"),s(null)):s(`Cannot cancel task in status: ${N.status}`)}D==="f"&&(k(uo.indexOf(n)),l("filter")),D==="r"&&E(),(L.pageDown||D==="n")&&T<h-1&&(S(N=>N+1),a(0)),(L.pageUp||D==="p")&&T>0&&(S(N=>N-1),a(0))}),x)return ee(j,{dimColor:!0,children:"Loading tasks..."});if(u==="filter")return te(xe,{flexDirection:"column",children:[ee(j,{bold:!0,children:"Filter by status:"}),uo.map((D,L)=>ee(xe,{children:te(j,{color:L===g?"cyan":"white",children:[L===g?"> ":" ",D,D===n?" (current)":""]})},D)),ee(j,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(u==="detail"&&B[i])return ee(kr,{taskId:B[i].id,onBack:()=>l("list")});if(u==="cancelling"&&B[i])return te(xe,{flexDirection:"column",children:[te(j,{color:"red",children:['Cancel task "',B[i].id.slice(0,8),'"? (y/n)']}),r&&ee(j,{color:"red",children:r})]});let Y=B[i]??null;return te(xe,{flexDirection:"column",children:[te(xe,{children:[te(j,{bold:!0,children:["Tasks (",t.length,")"]}),n!=="all"&&te(j,{dimColor:!0,children:[" [filter: ",n,"]"]}),te(j,{dimColor:!0,children:[" \u2022 Page ",T+1,"/",h]})]}),r&&ee(j,{color:r.startsWith("Failed")||r.startsWith("Cannot")?"red":"green",children:r}),t.length===0?te(j,{dimColor:!0,children:["No tasks found",n!=="all"?` with status "${n}"`:"","."]}):te(xe,{marginTop:1,flexDirection:"row",gap:2,children:[ee(xe,{flexDirection:"column",flexGrow:3,children:B.map((D,L)=>{let N=L===i,M=Er[D.status]??"white";return te(xe,{flexDirection:"column",marginBottom:1,children:[te(xe,{children:[ee(j,{color:N?"cyan":"gray",bold:N,children:N?"\u276F ":" "}),ee(j,{color:M,bold:!0,children:D.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${D.id.slice(0,8)}`})]}),ee(xe,{paddingLeft:2,children:ee(j,{color:N?"white":void 0,children:mo(D.prompt,N?72:56)})}),ee(xe,{paddingLeft:2,children:te(j,{dimColor:!0,children:[Pr(D.createdAt)," \u2022 ",Ir(D)," \u2022 ",Ar(D.costUsd)]})})]},D.id)})}),ee(xe,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?te(ts,{children:[ee(j,{bold:!0,children:"Preview"}),te(xe,{marginTop:1,children:[ee(j,{color:Er[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),ee(j,{children:mo(Y.prompt,220)}),te(xe,{marginTop:1,flexDirection:"column",children:[te(j,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),te(j,{dimColor:!0,children:["Created: ",Pr(Y.createdAt)]}),te(j,{dimColor:!0,children:["Duration: ",Ir(Y)]}),te(j,{dimColor:!0,children:["Cost: ",Ar(Y.costUsd)]}),te(j,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?te(xe,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"red",bold:!0,children:"Error"}),ee(j,{color:"red",children:mo(Y.error,180)})]}):Y.result?te(xe,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"green",bold:!0,children:"Latest Result"}),ee(j,{children:mo(Y.result,180)})]}):null,ee(xe,{marginTop:1,children:ee(j,{dimColor:!0,children:"Enter opens full detail"})})]}):ee(j,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function es(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function mo(e,t){return es(e.replace(/\s+/g," ").trim(),t)}function Ir(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 x=Math.floor(o/60),m=o%60;return m===0?`${x}m`:`${x}m ${m}s`}function Ar(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function Pr(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 x=Math.floor(o/60);return x<24?`${x}h ago`:`${Math.floor(x/24)}d ago`}Jo();import{Box as St,Text as Re,useInput as os}from"ink";import{useEffect as rs,useState as Dr}from"react";import{readFileSync as ns,existsSync as ss}from"fs";import{parse as is}from"yaml";import{Fragment as ls,jsx as Ie,jsxs as Oe}from"react/jsx-runtime";function Rr({onBack:e}){let[t,o]=Dr(null),[x,m]=Dr(null);return os((u,l)=>{(l.escape||u==="q")&&e()}),rs(()=>{try{let u=Zo;if(!ss(u)){m(`Config file not found: ${u}`);return}let l=ns(u,"utf-8");o(is(l))}catch(u){m(u.message)}},[]),x?Oe(St,{flexDirection:"column",children:[Ie(Re,{color:"red",children:x}),Ie(Re,{dimColor:!0,children:"Press Esc to go back"})]}):t?Oe(St,{flexDirection:"column",children:[Ie(Re,{bold:!0,children:"Configuration (Esc to go back)"}),Ie(St,{marginTop:1,flexDirection:"column",children:Ie(Mo,{obj:t,indent:0})})]}):Ie(Re,{dimColor:!0,children:"Loading config..."})}function Mo({obj:e,indent:t}){let o=" ".repeat(t);return Ie(ls,{children:Object.entries(e).map(([x,m])=>Ie(as,{label:x,value:m,indent:t,parentKey:x},x))})}function as({label:e,value:t,indent:o,parentKey:x}){let m=" ".repeat(o);return Array.isArray(t)?Oe(St,{flexDirection:"column",children:[Oe(Re,{children:[m,Ie(Re,{color:"cyan",children:e}),":"]}),t.length===0?Oe(Re,{dimColor:!0,children:[m," []"]}):t.map((u,l)=>Ie(Mr,{value:u,indent:o+1,parentKey:x,index:l},`${e}-${l}`))]}):t&&typeof t=="object"?Oe(St,{flexDirection:"column",children:[Oe(Re,{children:[m,Ie(Re,{color:"cyan",children:e}),":"]}),Ie(Mo,{obj:t,indent:o+1})]}):Oe(Re,{children:[m,Ie(Re,{color:"cyan",children:e}),": ",$r(x,Nr(t))]})}function Mr({value:e,indent:t,parentKey:o,index:x}){let m=" ".repeat(t);return Array.isArray(e)?Oe(St,{flexDirection:"column",children:[Oe(Re,{children:[m,"- [",x,"]"]}),e.map((u,l)=>Ie(Mr,{value:u,indent:t+1,parentKey:o,index:l},`${x}-${l}`))]}):e&&typeof e=="object"?Oe(St,{flexDirection:"column",children:[Oe(Re,{children:[m,"-"]}),Ie(Mo,{obj:e,indent:t+1})]}):Oe(Re,{children:[m,"- ",$r(o,Nr(e))]})}function $r(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 Nr(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as fo,Text as Xe,useInput as cs}from"ink";import{useEffect as ds,useState as $o}from"react";import{jsx as Qt,jsxs as rt}from"react/jsx-runtime";function _r({onBack:e}){let[t,o]=$o([]),[x,m]=$o(!0),[u,l]=$o(null);return cs((i,a)=>{(a.escape||i==="q")&&e()}),ds(()=>{v("/evolution-audit?limit=20").then(i=>{o(i),m(!1)}).catch(i=>{l(i.message),m(!1)})},[]),x?Qt(Xe,{dimColor:!0,children:"Loading evolution log..."}):u?rt(fo,{flexDirection:"column",children:[Qt(Xe,{color:"red",children:u}),Qt(Xe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?rt(fo,{flexDirection:"column",children:[Qt(Xe,{dimColor:!0,children:"No evolution records yet"}),Qt(Xe,{dimColor:!0,children:"Press Esc to go back"})]}):rt(fo,{flexDirection:"column",children:[rt(Xe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>rt(fo,{flexDirection:"column",marginTop:1,children:[rt(Xe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&rt(Xe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
9
+ `).map((a,n)=>a.startsWith("+")?rt(Xe,{color:"green",children:[" ",a]},n):a.startsWith("-")?rt(Xe,{color:"red",children:[" ",a]},n):rt(Xe,{dimColor:!0,children:[" ",a]},n))]},i.id))]})}import{Box as dt,Text as ae,useInput as us}from"ink";import ms from"ink-text-input";import{useEffect as gs,useState as Mt}from"react";import{jsx as Me,jsxs as Te}from"react/jsx-runtime";var fs={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function ps(e,t=20){let o=Math.round(e*t),x=t-o;return"\u2588".repeat(o)+"\u2591".repeat(x)}function xs(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function po({onBack:e}){let[t,o]=Mt([]),[x,m]=Mt(null),[u,l]=Mt("list"),[i,a]=Mt(""),[n,d]=Mt(!1),[g,k]=Mt(null);us((r,s)=>{if(u==="create"){s.escape&&(l("list"),a(""),k(null));return}(s.escape||r==="q")&&e(),r==="c"&&(l("create"),k(null)),r==="r"&&T()});let T=()=>{v("/goals?limit=20").then(({goals:r})=>o(r)).catch(r=>m(r.message))};gs(()=>{T()},[]);let S=async r=>{if(r.trim()){d(!0),k(null);try{let s=await v("/goals",{method:"POST",body:{input:r.trim()}});k(`Goal created: ${s.goal.name}`),a(""),l("list"),T()}catch(s){k(`Failed: ${s instanceof Error?s.message:String(s)}`)}finally{d(!1)}}};return x?Te(dt,{flexDirection:"column",children:[Te(ae,{color:"red",children:["Failed to load goals: ",x]}),Me(ae,{dimColor:!0,children:"Press Esc or q to return"})]}):u==="create"?Te(dt,{flexDirection:"column",children:[Me(ae,{bold:!0,children:"Create Goal"}),Me(ae,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Te(dt,{marginTop:1,children:[Me(ae,{color:"cyan",children:"> "}),Me(ms,{value:i,onChange:a,onSubmit:S})]}),n&&Me(ae,{color:"yellow",children:"Creating goal..."}),g&&Me(ae,{color:g.startsWith("Failed")?"red":"green",children:g}),Me(ae,{dimColor:!0,children:"Press Esc to cancel"})]}):Te(dt,{flexDirection:"column",children:[Te(ae,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Me(ae,{dimColor:!0,children:"No goals found. Press c to create one."}):Me(dt,{marginTop:1,flexDirection:"column",children:t.map(r=>{let s=r.targetValue>0?r.currentValue/r.targetValue:0,E=fs[r.status]??"white";return Te(dt,{marginBottom:1,flexDirection:"column",children:[Te(dt,{children:[Me(ae,{bold:!0,color:E,children:r.name}),Te(ae,{dimColor:!0,children:[" (",r.role,")"]}),Me(ae,{dimColor:!0,children:" \u2014 "}),Me(ae,{color:E,children:r.status})]}),Te(dt,{children:[Te(ae,{dimColor:!0,children:[" ",ps(s)," "]}),Te(ae,{color:s>=1?"green":"white",children:[Math.round(s*100),"%"]}),Te(ae,{dimColor:!0,children:[" (",r.currentValue,"/",r.targetValue," ",r.metricType,")"]})]}),Te(dt,{children:[Te(ae,{dimColor:!0,children:[" \u23F0 ",xs(r.deadline)," left"]}),Te(ae,{dimColor:!0,children:[" | \u{1F4B0} $",r.budgetUsd]}),Te(ae,{dimColor:!0,children:[" | ID: ",r.id.slice(0,8)]})]})]},r.id)})}),Me(ae,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as $t,Text as Fe,useInput as Ts}from"ink";import{useEffect as hs,useState as Lr}from"react";import{jsx as mt,jsxs as ut}from"react/jsx-runtime";function ys(e,t,o=15){let x=e/(e+t),m=Math.round(x*o);return"\u2593".repeat(m)+"\u2591".repeat(o-m)}function Or({onBack:e}){let[t,o]=Lr([]),[x,m]=Lr(null);if(Ts((l,i)=>{(i.escape||l==="q")&&e()}),hs(()=>{v("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>m(l.message))},[]),x)return ut($t,{flexDirection:"column",children:[ut(Fe,{color:"red",children:["Failed to load strategies: ",x]}),mt(Fe,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return ut($t,{flexDirection:"column",children:[mt(Fe,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),mt(Fe,{dimColor:!0,children:"Press Esc or q to return"})]});let u=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,a=u.get(i)??[];a.push(l),u.set(i,a)}return ut($t,{flexDirection:"column",children:[mt(Fe,{bold:!0,children:"Strategy Lab"}),mt(Fe,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),mt($t,{marginTop:1,flexDirection:"column",children:Array.from(u.entries()).map(([l,i])=>ut($t,{marginBottom:1,flexDirection:"column",children:[mt(Fe,{bold:!0,color:"cyan",children:l}),i.sort((a,n)=>{let d=a.alpha/(a.alpha+a.beta);return n.alpha/(n.alpha+n.beta)-d}).map(a=>{let n=a.alpha/(a.alpha+a.beta);return ut($t,{children:[mt(Fe,{dimColor:!0,children:" "}),ut(Fe,{children:[ys(a.alpha,a.beta)," "]}),ut(Fe,{color:n>.6?"green":n>.4?"yellow":"red",children:[(n*100).toFixed(0),"%"]}),ut(Fe,{dimColor:!0,children:[" ",a.name," (\u03B1=",a.alpha.toFixed(1)," \u03B2=",a.beta.toFixed(1)," trials=",a.totalTrials,")"]})]},a.id)})]},l))}),mt(Fe,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as he,Text as K,useInput as Ss}from"ink";import No from"ink-text-input";import{useEffect as ks,useState as We,useCallback as yt}from"react";import{CronExpressionParser as Bs}from"cron-parser";import{useState as bs,useEffect as vs,useCallback as Vr,useRef as Cs}from"react";var ws=3e3;function Ue(){let[e,t]=bs(null),o=Cs(null),x=Vr(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),m=Vr((u,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:u,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},ws))},[]);return vs(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:m,clearMessage:x}}import{jsx as J,jsxs as oe}from"react/jsx-runtime";var _o=["manual","cron","once","template_complete"],qr=["cron","once","template_complete"],xo={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function Es(e){try{return Bs.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function To({onBack:e}){let[t,o]=We([]),[x,m]=We(!0),[u,l]=We(0),[i,a]=We("list"),[n,d]=We({...xo}),[g,k]=We("name"),[T,S]=We(null),{message:r,setMessage:s,clearMessage:E}=Ue(),[h,B]=We(!1),[H,Y]=We(!1),[D,L]=We({}),[N,M]=We(null),[Z,se]=We(!1),Se=yt(()=>{m(!0),v("/task-templates").then(({templates:f})=>{o(f),new Set(f.flatMap(P=>P.steps?.map(U=>U.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:P})=>{if(!Array.isArray(P)){L({});return}L(Object.fromEntries(P.map(U=>[U.id,U.name])))}).catch(()=>L({})):L({}),m(!1)}).catch(()=>m(!1))},[]);ks(()=>{Se()},[Se]);let Ct=i==="create"||i==="edit",_e=yt(async()=>{let f=t[u];if(!(!f||h)){B(!0),s(`Triggering ${f.name}...`,"loading");try{let C=await v(`/task-templates/${f.id}/run`,{method:"POST"});s(`Triggered: ${f.name} (${C.executionId})`,"success")}catch(C){s(`Trigger failed: ${C instanceof Error?C.message:String(C)}`,"error")}finally{B(!1)}}},[t,u,h,s]),ve=yt(async()=>{let f=t[u];if(!f||H)return;if(!qr.includes(f.trigger?.type??"manual")){s("Toggle not applicable for manual triggers","error");return}let C=!f.enabled;Y(!0),s(`${f.name} \u2192 ${C?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${f.id}`,{method:"PATCH",body:{enabled:C}}),o(P=>P.map(U=>U.id===f.id?{...U,enabled:C}:U)),s(`${f.name} ${C?"enabled":"disabled"}`,"success")}catch(P){s(`Toggle failed: ${P instanceof Error?P.message:String(P)}`,"error")}finally{Y(!1)}},[t,u,H,s]),It=yt(async()=>{if(Z)return;let f=t[u];if(f){se(!0);try{let C=await v(`/task-templates/${f.id}/dependents`,{method:"GET"});M({templateId:f.id,templateName:f.name,executionCount:C.dependents.executionCount,taskCount:C.dependents.taskCount}),C.dependents.taskCount===0&&C.dependents.executionCount===0?s(`Delete "${f.name}"? Press d to confirm, Esc to cancel.`,"loading"):s(`"${f.name}" has ${C.dependents.executionCount} execution${C.dependents.executionCount===1?"":"s"}, ${C.dependents.taskCount} task${C.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(C){s(`Failed to inspect dependents: ${C instanceof Error?C.message:String(C)}`,"error")}finally{se(!1)}}},[t,u,s,Z]),Ce=yt(async f=>{let C=N;if(C){M(null);try{let P=await v(`/task-templates/${C.templateId}?mode=${f}`,{method:"DELETE"}),U=[];P.deletedCounts.workflowExecutions>0&&U.push(`${P.deletedCounts.workflowExecutions} exec`),P.deletedCounts.tasks>0&&U.push(`${P.deletedCounts.tasks} task${P.deletedCounts.tasks===1?"":"s"}`);let de=U.length?` (+${U.join(", ")})`:"";s(`Deleted: ${C.templateName}${de}`,"success"),Se(),l(ke=>Math.max(0,Math.min(ke,t.length-2)))}catch(P){s(`Delete failed: ${P instanceof Error?P.message:String(P)}`,"error")}}},[N,Se,s,t.length]),je=yt(()=>{M(null),E()},[E]),Tt=yt(()=>{let f=t[u];f&&(S(f.id),d({name:f.name,triggerType:f.trigger?.type==="workflow_complete"?"template_complete":f.trigger?.type??"manual",cron:f.trigger?.cron??"",targetTemplateId:f.trigger?.type==="template_complete"||f.trigger?.type==="workflow_complete"?f.trigger.event?.split(":")[1]??"":"",stepPrompt:f.steps?.[0]?.prompt??""}),k("name"),a("edit"))},[t,u]),$=yt(async()=>{let f={name:n.name,trigger:{type:n.triggerType,...n.triggerType==="cron"?{cron:n.cron}:{},...n.triggerType==="template_complete"&&n.targetTemplateId?{event:`template_complete:${n.targetTemplateId}`}:{}},steps:[{id:"step-1",prompt:n.stepPrompt}],enabled:!0};try{i==="create"?(await v("/task-templates",{method:"POST",body:f}),s(`Created: ${n.name}`,"success")):i==="edit"&&T&&(await v(`/task-templates/${T}`,{method:"PATCH",body:f}),s(`Updated: ${n.name}`,"success"))}catch(C){s(`Save failed: ${C instanceof Error?C.message:String(C)}`,"error")}a("list"),d({...xo}),S(null),Se()},[n,i,T,Se]);return Ss((f,C)=>{if(Ct){if(C.escape){a("list"),d({...xo}),S(null);return}if(C.return){let P=["name","triggerType","cron","stepPrompt"],de=n.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:P.filter(W=>W!=="targetTemplateId"),ke=de.indexOf(g);if(ke<de.length-1){let W=ke+1;if(de[W]==="cron"&&n.triggerType!=="cron"&&W++,W<de.length){k(de[W]);return}}$();return}if(C.tab&&g==="triggerType"){d(P=>{let U=_o.indexOf(P.triggerType);return{...P,triggerType:_o[(U+1)%_o.length]}});return}if(C.tab&&g==="targetTemplateId"){d(P=>{let U=t.filter(W=>W.id!==T),de=U.findIndex(W=>W.id===P.targetTemplateId),ke=U[(de+1)%U.length];return{...P,targetTemplateId:ke?.id??""}});return}return}if(N){if(C.escape){je();return}if(f==="D"&&C.shift){Ce("with_tasks");return}if(f==="d"&&!C.shift){Ce("template_only");return}return}if(C.escape||f==="q"){e();return}if(C.upArrow){l(P=>Math.max(0,P-1));return}if(C.downArrow){l(P=>Math.min(t.length-1,P+1));return}if(f==="t"){_e();return}if(f==="d"&&!C.shift){It();return}if(f==="e"){Tt();return}if(f==="c"){d({...xo}),k("name"),a("create");return}if(f==="s"||f===" "){ve();return}f==="r"&&(Se(),E())}),x?J(K,{dimColor:!0,children:"Loading templates..."}):Ct?oe(he,{flexDirection:"column",children:[oe(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),oe(he,{marginTop:1,flexDirection:"column",children:[oe(he,{children:[oe(K,{bold:g==="name",color:g==="name"?"cyan":void 0,children:["Name:"," "]}),g==="name"?J(No,{value:n.name,onChange:f=>d(C=>({...C,name:f})),placeholder:"template name"}):J(K,{children:n.name||"(empty)"})]}),oe(he,{children:[oe(K,{bold:g==="triggerType",color:g==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),J(K,{children:n.triggerType}),g==="triggerType"&&J(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),n.triggerType==="cron"&&oe(he,{children:[oe(K,{bold:g==="cron",color:g==="cron"?"cyan":void 0,children:["Cron:"," "]}),g==="cron"?J(No,{value:n.cron,onChange:f=>d(C=>({...C,cron:f})),placeholder:"*/5 * * * *"}):J(K,{children:n.cron||"(empty)"})]}),(n.triggerType==="template_complete"||n.triggerType==="workflow_complete")&&oe(he,{children:[oe(K,{bold:g==="targetTemplateId",color:g==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),J(K,{children:(()=>{let f=t.find(C=>C.id===n.targetTemplateId);return f?f.name:n.targetTemplateId?`(id: ${n.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),g==="targetTemplateId"&&J(K,{dimColor:!0,children:" (Tab to cycle)"})]}),oe(he,{children:[oe(K,{bold:g==="stepPrompt",color:g==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),g==="stepPrompt"?J(No,{value:n.stepPrompt,onChange:f=>d(C=>({...C,stepPrompt:f})),placeholder:"What should this template do?"}):J(K,{children:n.stepPrompt||"(empty)"})]})]}),J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):oe(he,{flexDirection:"column",children:[oe(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),r&&J(he,{marginTop:1,children:oe(K,{color:r.type==="success"?"green":r.type==="error"?"red":"gray",children:[r.type==="success"?"\u2713 ":r.type==="error"?"\u2717 ":"\u2192 ",r.text]})}),t.length===0?J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):J(he,{marginTop:1,flexDirection:"column",children:t.map((f,C)=>{let P=C===u,U=f.trigger?.type==="cron"&&f.trigger?.cron?Es(f.trigger.cron):"",de=new Set(f.steps?.filter(W=>W.roleId).map(W=>W.roleId)),ke=f.steps?.length>1?`${f.steps.length} steps${de.size>0?` / ${de.size} roles`:""}`:`${f.steps?.length??0} step`;return oe(he,{flexDirection:"column",children:[oe(he,{children:[J(K,{color:P?"cyan":void 0,bold:P,children:P?"> ":" "}),J(K,{color:P?"cyan":void 0,bold:P,children:Yt(f.name,24)}),J(K,{dimColor:!0,children:Yt(f.trigger?.type,10)}),qr.includes(f.trigger?.type??"manual")?J(K,{color:f.enabled?"green":"gray",children:Yt(f.enabled?"on":"off",6)}):J(K,{dimColor:!0,children:Yt("\u2014",6)}),J(K,{dimColor:!0,children:Yt(ke,18)}),U&&oe(K,{dimColor:!0,children:["next: ",U]})]}),P&&f.steps?.length>1&&J(he,{flexDirection:"column",marginLeft:4,marginTop:0,children:f.steps.map((W,Ze)=>oe(he,{children:[oe(K,{dimColor:!0,children:[" ",Ze+1,". "]}),J(K,{dimColor:!0,children:W.id}),W.roleId&&oe(K,{color:"yellow",children:[" @",D[W.roleId]??W.roleId]}),W.dependsOn&&W.dependsOn.length>0&&oe(K,{dimColor:!0,children:[" (after: ",W.dependsOn.join(", "),")"]}),W.config&&oe(K,{dimColor:!0,children:[" ","[",[W.config.timeout!==void 0?`timeout:${W.config.timeout}s`:"",W.config.maxTurns!==void 0?`turns:${W.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},W.id))})]},f.id)})}),J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Yt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as bt,Text as Ve,useInput as Is}from"ink";import As from"ink-text-input";import{useEffect as Ps,useState as Nt,useCallback as Fr}from"react";import{jsx as Ae,jsxs as kt}from"react/jsx-runtime";function Ur({onBack:e}){let[t,o]=Nt([]),[x,m]=Nt(""),[u,l]=Nt(!0),[i,a]=Nt(!1),[n,d]=Nt(""),[g,k]=Nt(null),T=Fr(()=>{l(!0),v("/webhooks").then(({webhooks:r,auth:s})=>{o(r),m(s),l(!1)}).catch(()=>l(!1))},[]);Ps(()=>{T()},[T]);let S=Fr(async r=>{if(r.trim())try{let s=await v(`/webhooks/${encodeURIComponent(r.trim())}`,{method:"POST"});k(`Triggered: ${s.executionId}`)}catch(s){k(`Trigger failed: ${s instanceof Error?s.message:String(s)}`)}},[]);return Is((r,s)=>{if(i){if(s.escape){a(!1),d("");return}if(s.return){S(n),a(!1),d("");return}return}if(s.escape||r==="q"){e();return}if(r==="t"){a(!0),d(""),k(null);return}r==="r"&&(T(),k(null))}),u?Ae(Ve,{dimColor:!0,children:"Loading webhooks..."}):kt(bt,{flexDirection:"column",children:[kt(Ve,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),kt(Ve,{dimColor:!0,children:["Auth: ",x]}),g&&Ae(bt,{marginTop:1,children:Ae(Ve,{color:"yellow",children:g})}),i&&kt(bt,{marginTop:1,children:[Ae(Ve,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Ae(As,{value:n,onChange:d,placeholder:"webhook name or ID"}),Ae(Ve,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Ae(bt,{marginTop:1,children:Ae(Ve,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):kt(bt,{marginTop:1,flexDirection:"column",children:[Ae(bt,{children:kt(Ve,{bold:!0,children:[_t("NAME",24),_t("DESCRIPTION",36),_t("TRIGGER",28),"TAGS"]})}),t.map(r=>kt(bt,{children:[Ae(Ve,{children:_t(r.displayName,24)}),Ae(Ve,{dimColor:!0,children:_t(Ds(r.description??"",34),36)}),Ae(Ve,{dimColor:!0,children:_t(r.trigger,28)}),Ae(Ve,{dimColor:!0,children:r.tags?.join(", ")??""})]},r.name))]}),Ae(bt,{marginTop:1,children:Ae(Ve,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function _t(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Ds(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as nt,Text as ue,useInput as Rs}from"ink";import Ms from"ink-text-input";import{useEffect as Wr,useState as gt,useCallback as Lo}from"react";import{jsx as me,jsxs as Qe}from"react/jsx-runtime";function $s(e){return e>=4?"red":e===3?"yellow":"gray"}function Ns(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function _s(e){return new Date(e).toLocaleDateString()}function Hr({onBack:e}){let[t,o]=gt([]),[x,m]=gt(0),[u,l]=gt([]),[i,a]=gt(!0),[n,d]=gt(!1),[g,k]=gt(""),[T,S]=gt("all"),[r,s]=gt(null),[E,h]=gt(!1),B=Lo(()=>{v("/agents").then(({agents:M})=>{o(M),a(!1)}).catch(()=>a(!1))},[]);Wr(()=>{B()},[B]);let H=t[x],Y=Lo(()=>{H&&(h(!1),v(`/memories/${H.id}`).then(({memories:M})=>{l(M),s(null)}).catch(M=>s(`Failed: ${M instanceof Error?M.message:String(M)}`)))},[H]);Wr(()=>{H&&Y()},[H,Y]);let D=Lo(async M=>{if(!(!H||!M.trim()))try{let Z=await v("/memories/query",{method:"POST",body:{agentId:H.id,prompt:M.trim()}});l(Z.memories),h(!0),s(`Search: ${Z.count} results`)}catch(Z){s(`Search failed: ${Z instanceof Error?Z.message:String(Z)}`)}},[H]),L=n,N=u.filter(M=>T==="all"?!0:T==="high"?M.importance>3:T==="medium"?M.importance===3:M.importance<3);return Rs((M,Z)=>{if(L){if(Z.escape){d(!1),k("");return}if(Z.return){D(g),d(!1),k("");return}return}if(Z.escape||M==="q"){e();return}if(M==="a"){m(se=>(se+1)%Math.max(1,t.length));return}if(Z.leftArrow){m(se=>(se-1+t.length)%Math.max(1,t.length));return}if(Z.rightArrow){m(se=>(se+1)%Math.max(1,t.length));return}if(M==="s"){d(!0),k(""),s(null);return}if(M==="h"){S(se=>se==="high"?"all":"high");return}if(M==="m"){S(se=>se==="medium"?"all":"medium");return}if(M==="l"){S(se=>se==="low"?"all":"low");return}M==="r"&&Y()}),i?me(ue,{dimColor:!0,children:"Loading agents..."}):t.length===0?Qe(nt,{flexDirection:"column",children:[me(ue,{dimColor:!0,children:"No agents found"}),me(ue,{dimColor:!0,children:"Press Esc to go back"})]}):Qe(nt,{flexDirection:"column",children:[me(ue,{bold:!0,children:"Memories (Esc to go back)"}),Qe(nt,{marginTop:1,children:[me(ue,{children:"Agent: "}),me(ue,{bold:!0,color:"cyan",children:H?.name??"?"}),Qe(ue,{dimColor:!0,children:[" (",x+1,"/",t.length,") [a/arrows to switch]"]})]}),me(nt,{children:Qe(ue,{dimColor:!0,children:["Filter: ",T==="all"?"all":T," | ",E?"search results":"all memories"," (",N.length,")"]})}),r&&me(nt,{children:me(ue,{color:"yellow",children:r})}),n&&Qe(nt,{marginTop:1,children:[me(ue,{bold:!0,color:"cyan",children:"Search: "}),me(Ms,{value:g,onChange:k,placeholder:"search query..."}),me(ue,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),N.length===0?me(nt,{marginTop:1,children:Qe(ue,{dimColor:!0,children:["No memories",T!=="all"?` matching filter '${T}'`:""]})}):me(nt,{marginTop:1,flexDirection:"column",children:N.map(M=>Qe(nt,{marginBottom:0,children:[Qe(ue,{color:$s(M.importance),bold:!0,children:[Ns(M.importance)," "]}),me(ue,{dimColor:!0,children:Gr(M.type??"?",12)}),me(ue,{dimColor:!0,children:Gr(`\xD7${M.retrievedCount??0}`,5)}),Qe(ue,{children:[Ls(M.content,55)," "]}),me(ue,{dimColor:!0,children:_s(M.createdAt)}),M.score!==void 0&&Qe(ue,{dimColor:!0,children:[" (",M.score.toFixed(2),")"]})]},M.id))}),me(nt,{marginTop:1,children:me(ue,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Gr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Ls(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ye,Text as ce,useInput as Os}from"ink";import ho from"ink-text-input";import{useState as $e,useEffect as jr,useCallback as Oo}from"react";import{jsx as ye,jsxs as fe}from"react/jsx-runtime";var Kr={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"]},Vs={"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 zr({onBack:e}){let{state:t}=Je(),[o,x]=$e({}),[m,u]=$e([]),[l,i]=$e(null),[a,n]=$e("view"),[d,g]=$e(0),[k,T]=$e(""),[S,r]=$e(null),[s,E]=$e(!1),[h,B]=$e([]),[H,Y]=$e({}),[D,L]=$e(0),[N,M]=$e(""),[Z,se]=$e(""),[Se,Ct]=$e(""),_e=Object.values(Kr).flat(),ve=Oo(()=>{v("/config").then($=>{x($.config),u($.mutable)}).catch($=>i($.message)),v("/config/env-diff").then($=>{B($.diffs)}).catch(()=>{}),v("/config/env").then($=>Y($.env??{})).catch(()=>{})},[]);jr(()=>{ve()},[ve]),jr(()=>{t.configVersion>0&&ve()},[t.configVersion,ve]);let It=Oo(async()=>{let $=_e[d];if($){E(!0),r(null);try{let f=k,C=o[$];if(C&&typeof C.value=="number"&&(f=Number(k),isNaN(f))){r("Invalid number"),E(!1);return}let P=await v("/config",{method:"PATCH",body:{[$]:f}});P.updated.length>0&&(r(`Updated: ${$}`),ve()),P.errors.length>0&&r(P.errors[0]),n("view")}catch(f){r(`Failed: ${f instanceof Error?f.message:String(f)}`)}finally{E(!1)}}},[_e,d,k,o,ve]),Ce=Object.keys(H),je=Oo(async $=>{try{await v("/config/env",{method:"PUT",body:$}),r("Env vars saved"),ve()}catch(f){r(`Failed: ${f instanceof Error?f.message:String(f)}`)}},[ve]);if(Os(($,f)=>{if(a==="edit"){if(f.escape){n("view");return}return}if(a==="env-list"){if(f.escape){n("view");return}if(f.upArrow&&D>0&&L(C=>C-1),f.downArrow&&D<Ce.length-1&&L(C=>C+1),$==="a"){M(""),n("env-add-key");return}if($==="d"&&Ce.length>0){let C=Ce[D],P={...H};delete P[C],je(P),D>=Ce.length-1&&D>0&&L(U=>U-1);return}if(f.return&&Ce.length>0){Ct(H[Ce[D]]??""),n("env-edit-value");return}return}if(a==="env-add-key"){if(f.escape){n("env-list");return}return}if(a==="env-add-value"){if(f.escape){n("env-list");return}return}if(a==="env-edit-value"){if(f.escape){n("env-list");return}return}if(f.escape||$==="q"){e();return}if(f.upArrow&&d>0&&g(C=>C-1),f.downArrow&&d<_e.length-1&&g(C=>C+1),f.return||$==="e"){let C=_e[d],P=o[C];P&&P.mutable?(T(String(P.value??"")),n("edit"),r(null)):P&&!P.mutable&&r("This setting requires a restart to change")}$==="v"&&(L(0),n("env-list"),r(null)),$==="r"&&(ve(),r("Refreshed")),$==="s"&&h.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{r("Synced to .env"),B([]),ve()}),$==="l"&&h.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{r("Loaded from .env"),ve()})}),l)return fe(Ye,{flexDirection:"column",children:[fe(ce,{color:"red",children:["Failed to load config: ",l]}),ye(ce,{dimColor:!0,children:"Press Esc or q to return"})]});let Tt=0;return fe(Ye,{flexDirection:"column",children:[ye(ce,{bold:!0,children:"Settings"}),S&&ye(ce,{color:S.startsWith("Failed")||S.startsWith("This setting")?"yellow":"green",children:S}),h&&h.length>0&&fe(Ye,{flexDirection:"column",marginBottom:1,children:[fe(ce,{color:"yellow",children:[".env differs from DB (",h.length," key(s)): ",h.map($=>$.envKey).join(", ")]}),ye(ce,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ye(Ye,{marginTop:1,flexDirection:"column",children:Object.entries(Kr).map(([$,f])=>fe(Ye,{marginBottom:1,flexDirection:"column",children:[ye(ce,{bold:!0,color:"cyan",children:$}),f.map(C=>{let P=o[C],de=Tt++===d,ke=m.includes(C),W=Vs[C]??C,Ze=P?String(P.value??""):"...";return a==="edit"&&de?fe(Ye,{children:[fe(ce,{color:"cyan",children:["> ",W,": "]}),ye(ho,{value:k,onChange:T,onSubmit:()=>{It()}}),s&&ye(ce,{color:"yellow",children:" saving..."})]},C):fe(Ye,{children:[fe(ce,{color:de?"cyan":"white",children:[de?"> ":" ",ke?" ":"\u{1F512} ",W,": "," "]}),ye(ce,{color:ke?"white":"gray",children:Ze}),!ke&&ye(ce,{dimColor:!0,children:" (restart required)"})]},C)})]},$))}),ye(ce,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),a.startsWith("env")&&fe(Ye,{flexDirection:"column",marginTop:1,children:[fe(ce,{bold:!0,color:"cyan",children:["Environment Variables (",Ce.length,")"]}),Ce.length===0&&a==="env-list"&&ye(ce,{dimColor:!0,children:" No env vars. Press a to add."}),Ce.map(($,f)=>{let C=f===D;return a==="env-edit-value"&&C?fe(Ye,{children:[fe(ce,{color:"cyan",children:["> ",$," = "]}),ye(ho,{value:Se,onChange:Ct,onSubmit:()=>{je({...H,[$]:Se}),n("env-list")}})]},$):fe(ce,{color:C&&a==="env-list"?"cyan":"white",children:[C&&a==="env-list"?"> ":" ",$," = ",H[$]]},$)}),a==="env-add-key"&&fe(Ye,{children:[ye(ce,{color:"green",children:" New key: "}),ye(ho,{value:N,onChange:M,onSubmit:()=>{N.trim()&&(se(""),n("env-add-value"))}})]}),a==="env-add-value"&&fe(Ye,{children:[fe(ce,{color:"green",children:[" ",N," = "]}),ye(ho,{value:Z,onChange:se,onSubmit:()=>{je({...H,[N.trim()]:Z}),n("env-list")}})]}),ye(ce,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as Bt,Text as Pe,useInput as qs}from"ink";import{useEffect as Fs,useState as Vo,useCallback as Us}from"react";import{jsx as we,jsxs as Ot}from"react/jsx-runtime";function Xr({onBack:e}){let[t,o]=Vo([]),[x,m]=Vo(!0),[u,l]=Vo(0),{message:i,setMessage:a,clearMessage:n}=Ue(),d=Us(()=>{m(!0),v("/plugins").then(({plugins:g})=>{o(g),m(!1)}).catch(()=>m(!1))},[]);return Fs(()=>{d()},[d]),qs((g,k)=>{if(k.escape||g==="q"){e();return}if(k.upArrow){l(T=>Math.max(0,T-1));return}if(k.downArrow){l(T=>Math.min(t.length-1,T+1));return}g==="r"&&(d(),n())}),x?we(Pe,{dimColor:!0,children:"Loading plugins..."}):Ot(Bt,{flexDirection:"column",children:[Ot(Pe,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&we(Bt,{marginTop:1,children:Ot(Pe,{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?we(Bt,{marginTop:1,children:we(Pe,{dimColor:!0,children:"No plugins installed."})}):Ot(Bt,{marginTop:1,flexDirection:"column",children:[Ot(Bt,{children:[we(Pe,{dimColor:!0,children:" "}),we(Pe,{dimColor:!0,children:Lt("Name",24)}),we(Pe,{dimColor:!0,children:Lt("Scope",8)}),we(Pe,{dimColor:!0,children:Lt("User",6)}),we(Pe,{dimColor:!0,children:"Path"})]}),t.map((g,k)=>{let T=k===u,S=g.id.split("@")[0];return Ot(Bt,{children:[we(Pe,{color:T?"cyan":void 0,bold:T,children:T?"> ":" "}),we(Pe,{color:T?"cyan":void 0,bold:T,children:Lt(S,24)}),we(Pe,{color:T?"cyan":void 0,bold:T,children:Lt(g.scope,8)}),we(Pe,{color:g.globalEnabled?"green":"gray",children:Lt(g.globalEnabled?"on":"off",6)}),we(Pe,{dimColor:!0,children:g.installPath})]},g.id)})]}),we(Bt,{marginTop:1,children:we(Pe,{dimColor:!0,children:"r:refresh"})})]})}function Lt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as qo,Text as Fo,useInput as Ws}from"ink";import{useState as Gs}from"react";import{jsx as Et,jsxs as Qr}from"react/jsx-runtime";var Hs=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function Yr({onBack:e}){let[t,o]=Gs("tasks");return Ws((x,m)=>{if(m.escape||x==="q"){e();return}if(x==="1"){o("tasks");return}if(x==="2"){o("automations");return}if(x==="3"){o("goals");return}}),Qr(qo,{flexDirection:"column",children:[Et(Fo,{bold:!0,children:"Work Surface"}),Et(Fo,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Et(qo,{gap:3,marginBottom:1,marginTop:1,children:Hs.map(x=>{let m=t===x.id;return Et(qo,{children:Qr(Fo,{color:m?"cyan":"gray",bold:m,children:[m?"\u25CF":"\u25CB"," ",x.key,". ",x.label]})},x.id)})}),t==="tasks"&&Et(go,{onBack:e}),t==="automations"&&Et(To,{onBack:e}),t==="goals"&&Et(po,{onBack:e})]})}import{Box as re,Text as X,useInput as js}from"ink";import{useEffect as Ks,useState as Zt}from"react";import{jsx as V,jsxs as be}from"react/jsx-runtime";var Zr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Jr({onBack:e}){let[t,o]=Zt([]),[x,m]=Zt(!0),[u,l]=Zt(0),[i,a]=Zt(null),[n,d]=Zt("");Ks(()=>{g()},[]);async function g(){try{let S=await v("/channels");o(S.channels)}catch{}m(!1)}async function k(S){if(t.find(s=>s.id===S)?.platform==="wechat")try{d("Starting WeChat QR login...");let s=await v(`/channels/${S}/wechat/qr-start`,{method:"POST"});if(s.qrcodeUrl){d(`Scan QR: ${s.qrcodeUrl}
10
+ Waiting for scan...`);let E=await v(`/channels/${S}/wechat/qr-wait`,{method:"POST",body:{sessionKey:s.sessionKey,timeoutMs:12e4}});d(E.message)}else d(s.message);g()}catch{d("WeChat connect failed")}else try{await v(`/channels/${S}/connect`,{method:"POST"}),d("Connecting..."),g()}catch{d("Connect failed")}}async function T(S){try{await v(`/channels/${S}/disconnect`,{method:"POST"}),d("Disconnected"),g()}catch{d("Disconnect failed")}}return js((S,r)=>{if(i){if(r.escape||S==="q"){a(null);return}if(S==="c"){k(i.id);return}if(S==="d"){T(i.id);return}return}if(r.escape){e();return}if(r.upArrow){l(s=>Math.max(0,s-1));return}if(r.downArrow){l(s=>Math.min(t.length-1,s+1));return}if(r.return&&t[u]){a(t[u]),d("");return}}),x?V(re,{flexDirection:"column",children:V(X,{dimColor:!0,children:"Loading channels..."})}):i?be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[be(X,{bold:!0,children:["Channel: ",i.name]}),V(X,{dimColor:!0,children:" (Esc to go back)"})]}),be(re,{flexDirection:"column",gap:0,children:[be(X,{children:["ID: ",i.id]}),be(X,{children:["Platform: ",i.platform]}),be(X,{children:["Status: ",V(X,{color:Zr[i.status]??"white",children:i.status})]}),be(X,{children:["Enabled: ",i.enabled?"yes":"no"]}),be(X,{children:["Messages: ",i.messageCount]}),be(X,{children:["Config: ",JSON.stringify(i.config)]})]}),V(re,{marginTop:1,children:V(X,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),n&&V(X,{color:"yellow",children:n})]}):be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[V(X,{bold:!0,children:"Channels"}),be(X,{dimColor:!0,children:[" (",t.length," total) "]}),V(X,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?V(X,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):be(re,{flexDirection:"column",children:[be(re,{children:[V(re,{width:3,children:V(X,{dimColor:!0,children:" "})}),V(re,{width:12,children:V(X,{bold:!0,dimColor:!0,children:"ID"})}),V(re,{width:16,children:V(X,{bold:!0,dimColor:!0,children:"Name"})}),V(re,{width:12,children:V(X,{bold:!0,dimColor:!0,children:"Platform"})}),V(re,{width:14,children:V(X,{bold:!0,dimColor:!0,children:"Status"})}),V(re,{width:10,children:V(X,{bold:!0,dimColor:!0,children:"Enabled"})}),V(re,{width:10,children:V(X,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((S,r)=>be(re,{children:[V(re,{width:3,children:V(X,{children:r===u?">":" "})}),V(re,{width:12,children:V(X,{inverse:r===u,children:S.id.slice(0,8)})}),V(re,{width:16,children:V(X,{children:S.name})}),V(re,{width:12,children:V(X,{children:S.platform})}),V(re,{width:14,children:be(X,{color:Zr[S.status]??"white",children:[S.status==="connected"?"\u25CF":S.status==="error"?"\u2717":"\u25CB"," ",S.status]})}),V(re,{width:10,children:V(X,{color:S.enabled?"green":"gray",children:S.enabled?"yes":"no"})}),V(re,{width:10,children:V(X,{children:S.messageCount})})]},S.id))]})]})}import{Box as Vt,Text as it,useInput as Qs}from"ink";import{useEffect as Ys,useState as Jt,useCallback as Zs}from"react";import{Box as R,Text as y,useInput as zs}from"ink";import st from"ink-text-input";import{useEffect as en,useState as Q,useCallback as vt}from"react";Jo();import{Fragment as tn,jsx as b,jsxs as I}from"react/jsx-runtime";var Xs=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function on({roleId:e,onBack:t}){let[o,x]=Q(null),[m,u]=Q([]),[l,i]=Q(!0),[a,n]=Q("view"),[d,g]=Q(""),[k,T]=Q(0),[S,r]=Q(""),[s,E]=Q([]),[h,B]=Q(0),[H,Y]=Q(new Set),[D,L]=Q("inline"),[N,M]=Q(""),[Z,se]=Q(""),[Se,Ct]=Q([]),[_e,ve]=Q(new Set),[It,Ce]=Q(0),[je,Tt]=Q("default"),[$,f]=Q(""),[C,P]=Q(""),[U,de]=Q("mode"),[ke,W]=Q([]),[Ze,ln]=Q(null),[wo,cn]=Q([]),[At,So]=Q([]),[Ho,ko]=Q(""),[wt,oo]=Q(0),[ro,jo]=Q(""),[Ko,zo]=Q(""),[Xo,Qo]=Q(""),{message:_,setMessage:q}=Ue(),ne=vt(()=>{i(!0),v(`/roles/${e}`).then(({role:p,boundPlugins:w})=>{x(p),u(w??[]),g(p.cagPrompt??""),Y(new Set(p.allowedTools??[])),L(p.executionMode??"inline"),M(p.model??""),se(p.maxBudgetUsd!=null?String(p.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);en(()=>{ne(),v("/config").then(p=>{let w=p.config["defaults.deniedReadPaths"]?.value;Array.isArray(w)&&W(w),ln(p.sandbox),cn(p.osCapabilities?.registry??[])}).catch(()=>{})},[ne]),en(()=>{L(o?.executionMode??"inline"),M(o?.model??""),se(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Tt(o?.permissionMode??"default"),f((o?.allowedBashPatterns??[]).join(", ")),P((o?.deniedBashPatterns??[]).join(", ")),So(o?.osCapabilities??[]);let p=o?.osCapabilities?.find(w=>w.id==="automation")?.targets??[];ko(p.join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let dn=vt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:d}}),q("CAG prompt saved","success"),n("view"),ne()}catch(p){q(`Save failed: ${p instanceof Error?p.message:String(p)}`,"error")}},[o,d,ne,q]),un=vt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Ke}}),q("Directories saved","success"),n("view"),ne()}catch(p){q(`Save failed: ${p instanceof Error?p.message:String(p)}`,"error")}},[o,ne,q]),mn=vt(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),q("Tool permissions saved","success"),n("view"),ne()}catch(p){q(`Save failed: ${p instanceof Error?p.message:String(p)}`,"error")}},[o,H,ne,q]),gn=vt(async()=>{if(!o)return;let p={executionMode:D};N!==void 0&&(p.model=N);let w=parseFloat(Z);isNaN(w)||(p.maxBudgetUsd=w);try{await v(`/roles/${o.id}`,{method:"PATCH",body:p}),q("Execution config saved","success"),n("view"),ne()}catch(c){q(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,D,N,Z,ne,q]),fn=vt(async()=>{if(!o)return;let p={permissionMode:je},w=$.split(",").map(A=>A.trim()).filter(Boolean),c=C.split(",").map(A=>A.trim()).filter(Boolean);p.allowedBashPatterns=w.length>0?w:[],p.deniedBashPatterns=c.length>0?c:[];try{await v(`/roles/${o.id}`,{method:"PATCH",body:p}),q("Permission config saved","success"),n("view"),ne()}catch(A){q(`Save failed: ${A instanceof Error?A.message:String(A)}`,"error")}},[o,je,$,C,ne,q]),Yo=vt(p=>{let w=new Map;for(let c of p){if(!c.id)continue;let A={id:c.id};c.targets?.length&&(A.targets=Array.from(new Set(c.targets.map(O=>O.trim()).filter(Boolean)))),w.set(c.id,A)}return Array.from(w.values()).sort((c,A)=>c.id.localeCompare(A.id))},[]),pn=vt(async()=>{if(!o)return;let p=Yo(At),w=p.find(c=>c.id==="automation")?.targets??[];if(p.some(c=>c.id==="automation")&&(w.length===0||w.some(c=>!Xs.test(c)))){q("Automation requires valid bundle id targets","error");return}try{await v(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:p}}),q("OS capabilities saved","success"),n("view"),ne()}catch(c){q(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,At,Yo,ne,q]),Ke=o?.additionalDirectories??[];if(zs((p,w)=>{if(w.escape){n("view");return}if(p==="r"){ne();return}switch(a){case"view":{if(p==="c"){n("edit-cag");return}if(p==="d"){n("edit-dirs"),T(0),r("");return}if(p==="t"){n("edit-tools");return}if(p==="o"){n("edit-oscaps");return}if(p==="x"){n("edit-exec");return}if(p==="h"){v("/channels?enabled=true").then(({channels:c})=>{Ct(c.map(A=>({name:A.name,id:A.id}))),ve(new Set(o?.allowedChannels??[])),Ce(0),n("edit-channels")}).catch(()=>q("Failed to load channels","error"));return}if(p==="p"){Tt(o?.permissionMode??"default"),f((o?.allowedBashPatterns??[]).join(", ")),P((o?.deniedBashPatterns??[]).join(", ")),de("mode"),n("edit-permissions");return}if(p==="v"){oo(0),n("edit-env");return}if(p==="i"){if(!o)return;let c=!o.inheritUserSettings;v(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:c}}).then(()=>{q(`Inherit user settings: ${c?"ON":"OFF"}`,"success"),ne()}).catch(()=>q("Failed to toggle","error"));return}if(p==="R"&&o?.presetId){v(`/presets/role/${o.presetId}/restore`,{method:"POST"}).then(()=>{q("Preset restored","success"),ne()}).catch(c=>q(`Restore failed: ${c instanceof Error?c.message:String(c)}`,"error"));return}break}case"edit-cag":{if(w.ctrl&&p==="s"){dn();return}break}case"edit-dirs":{if(p==="s"){un();return}if(p==="a"){n("edit-dirs-add");return}if(p==="m"&&Ke.length>0){let c=Ke[k];if(c){x(O=>O&&{...O,additionalDirectories:O.additionalDirectories?.map((le,lt)=>lt===k?{...typeof le=="string"?{path:le}:le,mode:le.mode==="ro"?"rw":"ro"}:le)});let A=c.mode==="ro"?"rw":"ro";q(`Mode set to ${A.toUpperCase()}`,"success")}return}if(p==="x"&&Ke.length>0){x(c=>c&&{...c,additionalDirectories:Ke.filter((A,O)=>O!==k)}),T(c=>Math.max(0,Math.min(c,Ke.length-2)));return}if(w.upArrow){T(c=>Math.max(0,c-1));return}if(w.downArrow){T(c=>Math.min(Ke.length-1,c+1));return}break}case"edit-dirs-add":{if(w.escape){n("edit-dirs"),r(""),E([]);return}if(w.return&&s.length>0){let c=s[h];c&&(r(c.endsWith("/")?c:c+"/"),E([]));return}if(w.return){let c=S.trim();c&&c.startsWith("/")?(x(A=>A&&{...A,additionalDirectories:[...A.additionalDirectories??[],{path:c,mode:"rw"}]}),r(""),E([]),n("edit-dirs")):q("Path must be absolute (must start with /)","error");return}if(w.tab){let c=S.trim();if(!c||!c.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(c)}`).then(({suggestions:A})=>{A.length===1?(r(A[0]+"/"),E([])):A.length>1&&(E(A),B(0))}).catch(()=>{E([])});return}if(w.upArrow&&s.length>0){B(c=>Math.max(0,c-1));return}if(w.downArrow&&s.length>0){B(c=>Math.min(s.length-1,c+1));return}break}case"edit-tools":{if(p==="s"){mn();return}let c=parseInt(p,10)-1;if(!isNaN(c)&&c>=0&&c<no.length){let A=no[c];Y(O=>{let le=new Set(O);return le.has(A)?le.delete(A):le.add(A),le});return}break}case"edit-oscaps":{if(p==="s"){pn();return}if(p==="a"&&At.some(O=>O.id==="automation")){let O=At.find(le=>le.id==="automation")?.targets??[];ko(O.join(", ")),n("edit-oscaps-targets");return}let c=wo.filter(O=>O.editable),A=parseInt(p,10)-1;if(!isNaN(A)&&A>=0&&A<c.length){let O=c[A];So(le=>le.some(Gt=>Gt.id===O.id)?le.filter(Gt=>Gt.id!==O.id):[...le,{id:O.id,targets:O.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(w.return){let c=Ho.split(",").map(A=>A.trim()).filter(Boolean);So(A=>A.map(O=>O.id==="automation"?{...O,targets:c}:O)),n("edit-oscaps");return}break}case"edit-exec":{if(p==="s"){gn();return}if(w.tab){L(c=>c==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(p==="s"){fn();return}if(w.tab){de(c=>c==="mode"?"allowed":c==="allowed"?"denied":"mode");return}if(U==="mode"&&(w.upArrow||w.downArrow)){let c=["default","acceptEdits","dontAsk","bypassPermissions"],A=c.indexOf(je);w.upArrow&&Tt(c[Math.max(0,A-1)]),w.downArrow&&Tt(c[Math.min(c.length-1,A+1)]);return}break}case"edit-channels":{if(p==="s"){if(!o)return;let c=_e.size>0?Array.from(_e):[];v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:c}}).then(()=>{q("Channels saved","success"),n("view"),ne()}).catch(()=>q("Save failed","error"));return}if(p==="u"){if(!o)return;v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{q("Channels: unrestricted","success"),n("view"),ne()}).catch(()=>q("Save failed","error"));return}if(p===" "){let c=Se[It];c&&ve(A=>{let O=new Set(A);return O.has(c.name)?O.delete(c.name):O.add(c.name),O});return}if(w.upArrow){Ce(c=>Math.max(0,c-1));return}if(w.downArrow){Ce(c=>Math.min(Se.length-1,c+1));return}break}case"edit-env":{let c=Object.keys(o?.envVars??{});if(p==="a"){jo(""),n("edit-env-add-key");return}if(p==="d"&&c.length>0){let A=c[wt],O={...o?.envVars??{}};delete O[A],v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{q("Deleted","success"),ne()}).catch(()=>q("Delete failed","error")),wt>=c.length-1&&wt>0&&oo(le=>le-1);return}if(w.return&&c.length>0){Qo((o?.envVars??{})[c[wt]]??""),n("edit-env-edit-value");return}w.upArrow&&wt>0&&oo(A=>A-1),w.downArrow&&wt<c.length-1&&oo(A=>A+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),l)return b(y,{dimColor:!0,children:"Loading role..."});if(!o)return b(y,{dimColor:!0,children:"Role not found."});if(a==="edit-cag")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),b(st,{value:d,onChange:g,placeholder:"Character And Guidance prompt..."}),_&&b(R,{marginTop:1,children:b(y,{color:_.type==="error"?"red":"green",children:_.text})})]});if(a==="edit-dirs-add")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),b(st,{value:S,onChange:p=>{r(p),E([])},placeholder:"/absolute/path/to/directory"}),s.length>0&&I(R,{flexDirection:"column",marginTop:1,children:[s.map((p,w)=>I(y,{color:w===h?"cyan":void 0,dimColor:w!==h,children:[w===h?"> ":" ",p,"/"]},p)),b(y,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),_&&b(R,{marginTop:1,children:b(y,{color:_.type==="error"?"red":"green",children:_.text})})]});if(a==="edit-dirs")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),Ke.length===0?b(y,{dimColor:!0,children:"No directories. Press a to add one."}):Ke.map((p,w)=>{let c=typeof p=="string"?{path:p,mode:"rw"}:p,A=c.mode!=="ro";return I(R,{children:[b(y,{color:w===k?"cyan":void 0,bold:w===k,children:w===k?"> ":" "}),I(y,{color:A?"green":"yellow",children:["[",A?"RW":"RO","]"," "]}),b(y,{color:w===k?"cyan":void 0,children:c.path})]},c.path)})]});if(a==="edit-tools")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),no.map((p,w)=>{let c=H.has(p);return I(R,{children:[I(y,{dimColor:!0,children:[w+1,". "]}),b(y,{color:c?"green":"red",children:c?"[ON] ":"[OFF] "}),b(y,{children:p})]},p)})]});if(a==="edit-oscaps"){let p=wo.filter(w=>w.editable);return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),Ze&&I(y,{dimColor:!0,children:["Platform: ",Ze.platform," ",Ze.available?"(sandbox active)":"(sandbox unavailable)"]}),wo.map(w=>{let c=p.findIndex(lt=>lt.id===w.id),A=At.some(lt=>lt.id===w.id),O=c>=0?`${c+1}.`:" -",le=w.id==="automation"?(()=>{let lt=At.find(Gt=>Gt.id===w.id)?.targets??[];return lt.length>0?` targets: ${lt.join(", ")}`:" targets: (none)"})():"";return I(R,{flexDirection:"column",marginBottom:1,children:[I(y,{color:A?"green":w.editable?"red":"gray",children:[O," ",A?"[ON]":"[OFF]"," ",w.label," [",w.availability,"]"]}),I(y,{dimColor:!0,children:[" ",w.description,le]}),w.effectiveDisabledReason&&!w.editable&&I(y,{dimColor:!0,children:[" ",w.effectiveDisabledReason]})]},w.id)}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]})}if(a==="edit-oscaps-targets")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),b(st,{value:Ho,onChange:ko,placeholder:"com.apple.mail, com.apple.systemevents"}),b(y,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(a==="edit-exec")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),I(R,{children:[b(y,{bold:!0,children:" Mode: "}),b(y,{color:"cyan",children:D}),b(y,{dimColor:!0,children:" (Tab to toggle)"})]}),I(R,{children:[b(y,{bold:!0,children:" Model: "}),b(st,{value:N,onChange:M,placeholder:"sonnet, opus, haiku, or blank"})]}),I(R,{children:[b(y,{bold:!0,children:" Max Budget (USD): "}),b(st,{value:Z,onChange:se,placeholder:"0 = unlimited"})]}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(a==="edit-permissions")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),I(R,{children:[b(y,{bold:!0,color:U==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(w=>I(y,{color:w===je?"green":"gray",children:[w===je?`[${w}]`:` ${w} `," "]},w))]}),I(R,{children:[b(y,{bold:!0,color:U==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),U==="allowed"?b(st,{value:$,onChange:f,placeholder:"git add *, pnpm test*"}):b(y,{children:$||"(none)"})]}),I(R,{children:[b(y,{bold:!0,color:U==="denied"?"cyan":void 0,children:" Denied Bash: "}),U==="denied"?b(st,{value:C,onChange:P,placeholder:"rm -rf *, ssh *"}):b(y,{children:C||"(none)"})]}),b(y,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(a==="edit-channels")return I(R,{flexDirection:"column",children:[b(y,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Se.length===0?b(y,{dimColor:!0,children:"No channels available"}):Se.map((p,w)=>I(R,{children:[I(y,{children:[w===It?">":" "," "]}),I(y,{color:_e.has(p.name)?"green":"gray",children:["[",_e.has(p.name)?"x":" ","] ",p.name]})]},p.id)),I(y,{dimColor:!0,children:["Selected: ",_e.size>0?Array.from(_e).join(", "):"none (= block all)"]}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(a.startsWith("edit-env")){let p=Object.keys(o.envVars??{});return I(R,{flexDirection:"column",children:[I(y,{bold:!0,children:["Environment Variables (",p.length,")"]}),p.length===0&&a==="edit-env"&&b(y,{dimColor:!0,children:" No env vars. Press a to add."}),p.map((w,c)=>{let A=c===wt;return a==="edit-env-edit-value"&&A?I(R,{children:[I(y,{color:"cyan",children:["> ",w," = "]}),b(st,{value:Xo,onChange:Qo,onSubmit:()=>{let O={...o.envVars??{},[w]:Xo};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{q("Saved","success"),ne(),n("edit-env")}).catch(()=>q("Save failed","error"))}})]},w):I(y,{color:A&&a==="edit-env"?"cyan":"white",children:[A&&a==="edit-env"?"> ":" ",w," = ",(o.envVars??{})[w]]},w)}),a==="edit-env-add-key"&&I(R,{children:[b(y,{color:"green",children:" New key: "}),b(st,{value:ro,onChange:jo,onSubmit:()=>{ro.trim()&&(zo(""),n("edit-env-add-value"))}})]}),a==="edit-env-add-value"&&I(R,{children:[I(y,{color:"green",children:[" ",ro," = "]}),b(st,{value:Ko,onChange:zo,onSubmit:()=>{let w={...o.envVars??{},[ro.trim()]:Ko};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:w}}).then(()=>{q("Added","success"),ne(),n("edit-env")}).catch(()=>q("Add failed","error"))}})]}),b(y,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),_&&b(y,{color:_.type==="error"?"red":"green",children:_.text})]})}return I(R,{flexDirection:"column",children:[I(y,{bold:!0,children:["Role: ",o.name]}),I(R,{children:[b(y,{dimColor:!0,children:"ID: "}),b(y,{children:o.id})]}),I(R,{children:[b(y,{dimColor:!0,children:"Status: "}),b(y,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&I(R,{children:[b(y,{dimColor:!0,children:"Score: "}),I(y,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),I(R,{children:[b(y,{dimColor:!0,children:"Created: "}),b(y,{children:new Date(o.createdAt).toLocaleString()})]}),I(R,{children:[b(y,{dimColor:!0,children:"Execution: "}),I(y,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),I(R,{children:[b(y,{dimColor:!0,children:"OS Capabilities: "}),b(y,{children:(o.osCapabilities?.length??0)>0?o.osCapabilities.map(p=>p.id==="automation"&&p.targets?.length?`automation(${p.targets.join(",")})`:p.id).join(", "):"None"})]}),Ze&&I(R,{children:[b(y,{dimColor:!0,children:"Sandbox Platform: "}),I(y,{children:[Ze.platform," ",Ze.available?"(active)":"(unavailable)"]})]}),Ke.length>0&&I(tn,{children:[b(y,{bold:!0,children:"Additional Directories:"}),Ke.map(p=>I(y,{dimColor:!0,children:[" ",p.path]},p.path))]}),I(R,{children:[b(y,{dimColor:!0,children:"Permission: "}),b(y,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&I(R,{children:[b(y,{dimColor:!0,children:" Bash Allow: "}),b(y,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&I(R,{children:[b(y,{dimColor:!0,children:" Bash Deny: "}),b(y,{children:o.deniedBashPatterns.join(", ")})]}),ke.length>0&&I(R,{flexDirection:"column",children:[b(y,{dimColor:!0,children:"Denied Read Paths (global):"}),ke.map(p=>I(y,{dimColor:!0,children:[" ",p]},p)),I(y,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),I(R,{children:[b(y,{dimColor:!0,children:"Channels: "}),b(y,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),I(R,{children:[b(y,{dimColor:!0,children:"Inherit User Settings: "}),b(y,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&I(tn,{children:[b(y,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(p=>I(y,{dimColor:!0,children:[" - ",p]},p))]}),_&&b(R,{children:b(y,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),b(R,{marginTop:1,children:I(y,{dimColor:!0,children:["c:CAG d:dirs t:tools o:oscaps x:exec p:perms h:channels v:env i:inherit"," ",o?.presetId?"R:restore-preset ":"","r:refresh Esc:back"]})})]})}import{jsx as Ge,jsxs as eo}from"react/jsx-runtime";function rn({onBack:e}){let[t,o]=Jt([]),[x,m]=Jt(!0),[u,l]=Jt(0),[i,a]=Jt("list"),[n,d]=Jt(null),{message:g,setMessage:k,clearMessage:T}=Ue(),S=Zs(()=>{m(!0),v("/roles").then(({roles:r})=>{o(r.map(s=>({id:s.id,name:s.name,status:s.status,performanceScore:s.performanceScore,createdAt:s.createdAt,presetId:s.presetId}))),m(!1)}).catch(()=>m(!1))},[]);return Ys(()=>{S()},[S]),Qs((r,s)=>{if(s.escape||r==="q"){e();return}if(s.upArrow){l(E=>Math.max(0,E-1));return}if(s.downArrow){l(E=>Math.min(t.length-1,E+1));return}if(r==="r"&&(S(),T()),r===`
11
+ `||r==="o"||r==="e"){t.length>0&&(d(t[u].id),a("detail"));return}}),x?Ge(it,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&n?Ge(on,{roleId:n,onBack:()=>a("list")}):eo(Vt,{flexDirection:"column",children:[eo(it,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),g&&Ge(Vt,{marginTop:1,children:eo(it,{color:g.type==="success"?"green":g.type==="error"?"red":"gray",children:[g.type==="success"?"\u2713 ":g.type==="error"?"\u2717 ":"\u2192 ",g.text]})}),t.length===0?Ge(Vt,{marginTop:1,children:Ge(it,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ge(Vt,{marginTop:1,flexDirection:"column",children:t.map((r,s)=>{let E=s===u,h=r.performanceScore!=null?`${(r.performanceScore*100).toFixed(0)}%`:"\u2014";return eo(Vt,{children:[Ge(it,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),Ge(it,{color:E?"cyan":void 0,bold:E,children:Uo(r.name,24)}),r.presetId&&eo(it,{dimColor:!0,children:["[",r.presetId,"]"]}),Ge(it,{color:Js(r.status),children:Uo(r.status,12)}),Ge(it,{dimColor:!0,children:Uo(h,8)})]},r.id)})}),Ge(Vt,{marginTop:1,children:Ge(it,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function Js(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Uo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ei,Text as Wo}from"ink";import ti from"react";import{jsx as yo,jsxs as ri}from"react/jsx-runtime";var Ne={key:"Esc",label:"back"},oi={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},Ne],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},Ne],config:[Ne],evolution:[Ne],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},Ne],strategies:[Ne],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"},Ne],webhooks:[Ne],memories:[Ne],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},Ne],roles:[Ne],settings:[Ne],channels:[Ne]};function nn(){let{state:e}=Je(),t=oi[e.view]??[Ne];return yo(ei,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,x)=>ri(ti.Fragment,{children:[x>0&&yo(Wo,{dimColor:!0,children:" "}),yo(Wo,{color:"cyan",children:o.key}),yo(Wo,{dimColor:!0,children:` ${o.label}`})]},`${o.key}-${o.label}`))})}import{Box as qt,Text as He,useInput as ni}from"ink";import{useEffect as si,useState as bo,useCallback as ii}from"react";import{jsx as pt,jsxs as ft}from"react/jsx-runtime";function sn({onBack:e}){let[t,o]=bo([]),[x,m]=bo(!0),[u,l]=bo(0),[i,a]=bo("all"),{message:n,setMessage:d}=Ue(),g=ii(()=>{m(!0);let s=i!=="all"?`?status=${i}`:"";v(`/feature-requests${s}`).then(({featureRequests:E})=>{o(E),l(0),m(!1)}).catch(()=>m(!1))},[i]);si(()=>{g()},[g]);let k=async(s,E)=>{try{await v(`/feature-requests/${s}/status`,{method:"PATCH",body:{status:E}}),d(`Marked as ${E}`,"success"),await g()}catch(h){d(`Failed: ${h instanceof Error?h.message:String(h)}`,"error")}},T=t;ni((s,E)=>{if(E.escape||s==="q"){e();return}if(E.upArrow){l(B=>Math.max(0,B-1));return}if(E.downArrow){l(B=>Math.min(T.length-1,B+1));return}if(s==="r"){g();return}let h={0:"all",1:"new",2:"reviewed",3:"dismissed",4:"converted"};if(h[s]){a(h[s]);return}if(s==="s"&&T.length>0){let B=T[u];if(B&&B.status==="new"){k(B.id,"reviewed");return}}if(s==="d"&&T.length>0){let B=T[u];if(B){k(B.id,"dismissed");return}}if(s==="c"&&T.length>0){let B=T[u];if(B){k(B.id,"converted");return}}});let S=s=>s==="new"?"cyan":s==="reviewed"?"green":s==="dismissed"?"gray":s==="converted"?"yellow":"white",r=s=>{let E=Date.now()-s;if(Math.floor(E/6e4)<1)return"now";let B=Math.floor(E/36e5);return B<24?`${B}h ago`:`${Math.floor(B/24)}d ago`};return ft(qt,{flexDirection:"column",children:[ft(He,{bold:!0,children:["Feature Requests (",T.length,") (Esc:back q:quit r:refresh)"]}),n&&pt(qt,{marginTop:1,children:ft(He,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),pt(He,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),pt(He,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),x?pt(He,{dimColor:!0,children:"Loading..."}):T.length===0?pt(He,{dimColor:!0,children:"No feature requests found."}):pt(qt,{marginTop:1,flexDirection:"column",children:T.map((s,E)=>{let h=E===u,B=s.content.length>80?s.content.slice(0,80)+"...":s.content;return ft(qt,{flexDirection:"column",children:[ft(qt,{children:[pt(He,{color:h?"cyan":void 0,bold:h,children:h?"> ":" "}),ft(He,{color:S(s.status),children:["[",s.status,"]"]}),ft(He,{dimColor:!0,children:[" ",r(s.extractedAt)]}),s.tags&&s.tags.length>0&&ft(He,{dimColor:!0,children:[" ",s.tags.slice(0,3).join(", ")]})]}),ft(qt,{paddingLeft:4,flexDirection:"column",children:[s.summary&&pt(He,{color:h?"cyan":"white",children:s.summary}),pt(He,{dimColor:!0,children:B})]})]},s.id)})})]})}import{Box as Ft,Text as qe,useInput as ai}from"ink";import{useEffect as li,useState as vo,useCallback as ci}from"react";import{jsx as xt,jsxs as at}from"react/jsx-runtime";function an({onBack:e}){let[t,o]=vo([]),[x,m]=vo(!0),[u,l]=vo(0),[i,a]=vo("all"),{message:n,setMessage:d}=Ue(),g=ci(()=>{m(!0);let r=i!=="all"?`?status=${i}`:"";v(`/mistake-patterns${r}`).then(({mistakePatterns:s})=>{o(s),l(0),m(!1)}).catch(()=>m(!1))},[i]);li(()=>{g()},[g]);let k=async(r,s)=>{try{await v(`/mistake-patterns/${r}`,{method:"PATCH",body:{status:s}}),d(`Marked as ${s}`,"success"),await g()}catch(E){d(`Failed: ${E instanceof Error?E.message:String(E)}`,"error")}};ai((r,s)=>{if(s.escape||r==="q"){e();return}if(s.upArrow){l(h=>Math.max(0,h-1));return}if(s.downArrow){l(h=>Math.min(t.length-1,h+1));return}if(r==="r"){g();return}let E={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(E[r]){a(E[r]);return}if(r==="a"&&t.length>0){let h=t[u];if(h&&h.status!=="acknowledged"){k(h.id,"acknowledged");return}}if(r==="d"&&t.length>0){let h=t[u];if(h&&h.status!=="dismissed"){k(h.id,"dismissed");return}}if(r==="n"&&t.length>0){let h=t[u];if(h&&h.status!=="new"){k(h.id,"new");return}}});let T=r=>r==="new"?"cyan":r==="acknowledged"?"green":r==="dismissed"?"gray":"white",S=r=>{let s=Date.now()-r;if(Math.floor(s/6e4)<1)return"now";let h=Math.floor(s/36e5);return h<24?`${h}h ago`:`${Math.floor(h/24)}d ago`};return at(Ft,{flexDirection:"column",children:[at(qe,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),n&&xt(Ft,{marginTop:1,children:at(qe,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),xt(qe,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),xt(qe,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),x?xt(qe,{dimColor:!0,children:"Loading..."}):t.length===0?xt(qe,{dimColor:!0,children:"No mistake patterns found."}):xt(Ft,{marginTop:1,flexDirection:"column",children:t.map((r,s)=>{let E=s===u,h=r.dimensionValue.length>80?r.dimensionValue.slice(0,80)+"...":r.dimensionValue;return at(Ft,{flexDirection:"column",children:[at(Ft,{children:[xt(qe,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),at(qe,{color:T(r.status),children:["[",r.status,"]"]}),at(qe,{dimColor:!0,children:[" ",S(r.lastSeen)]}),at(qe,{dimColor:!0,children:[" [",r.dimensionType,"]"]}),at(qe,{dimColor:!0,children:[" ",r.roleIds.length," role(s)"]}),at(qe,{dimColor:!0,children:[" x",r.count]})]}),xt(Ft,{paddingLeft:4,flexDirection:"column",children:xt(qe,{color:E?"cyan":"white",children:h})})]},r.id)})})]})}import{Fragment as pi,jsx as z,jsxs as Wt}from"react/jsx-runtime";function mi(){let{state:e,dispatch:t}=Je(),{session:o,sendMessage:x,createNewSession:m,archiveCurrentSession:u}=lr(),[l,i]=ui([]);Co(()=>{t({type:"SET_SESSION",session:o})},[o,t]),sr();let{latestMessage:a}=dr(o?.id??null),n=Go(null);Co(()=>{a&&a.id!==n.current&&(n.current=a.id,i(B=>[...B,{role:"assistant",content:a.content}]))},[a]);let{events:d,isStreaming:g,clearEvents:k}=ar(e.activeTaskId),T=d[d.length-1],S=T?.type==="complete"&&!g,r=Go(null),s=Go("");Co(()=>{s.current=d.filter(B=>B.type==="reasoning").map(B=>B.content).join("")},[d]),Co(()=>{if(S&&e.activeTaskId!==r.current){r.current=e.activeTaskId;let B=T?.content||s.current;B&&i(H=>[...H,{role:"assistant",content:B}])}},[S,T,e.activeTaskId]);let E=async B=>{let H=B.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),B.startsWith("/")){let D=B.slice(1),N={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins","feature-requests":"featureRequests",mistakes:"mistakes",back:"chat"}[D];if(N){t({type:"SET_VIEW",view:N});return}if(D==="new"){if(await u()){let Z=await m();i([]),k(),Z&&i([{role:"assistant",content:`Session archived. New session started: ${Z.id.slice(0,8)}`}])}return}if(D==="session"){let M=o?`Session: ${o.id}
12
+ Turns: ${o.messageCount}
13
+ Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(Z=>[...Z,{role:"assistant",content:M}]);return}}if(i(D=>[...D,{role:"user",content:B}]),k(),!await x(B)){i(D=>[...D,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},h=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval;return Wt(to,{flexDirection:"column",paddingX:1,children:[z(mr,{}),Wt(to,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Wt(pi,{children:[z(hr,{messages:l}),z(pr,{events:d,isStreaming:g}),!e.connected&&!e.serverUnreachable&&z(to,{children:z(Ut,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Wt(to,{flexDirection:"column",children:[z(Ut,{color:"red",bold:!0,children:"Server unreachable after 15s."}),z(Ut,{dimColor:!0,children:"Check: adam server logs"}),z(Ut,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&z(Yr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&z(go,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&z(Rr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&z(_r,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&z(po,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&z(Or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&z(To,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&z(Ur,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&z(Hr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&z(Xr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&z(rn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&z(sn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&z(an,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&z(zr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&z(Jr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?z(br,{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?z(yr,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):h?z(fr,{onSubmit:E}):z(nn,{}),e.planTimeoutNotice&&z(gi,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function gi({planId:e,onDismiss:t}){return di(o=>{o==="d"&&t()}),Wt(to,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Wt(Ut,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),z(Ut,{dimColor:!0,children:" [d] Dismiss"})]})}function fi(){return z(or,{children:z(mi,{})})}export{fi as default};
@@ -0,0 +1 @@
1
+ import{B as a,C as b,D as c}from"./chunk-SZBWLHP6.js";import"./chunk-AMHO3ALG.js";import"./chunk-JYHOGBCP.js";import"./chunk-7T4B2MZ7.js";import"./chunk-NPIXYK5G.js";import"./chunk-UXDTFTG5.js";import"./chunk-SWP2JC54.js";import"./chunk-FUWPDXXG.js";import"./chunk-X5V4VMET.js";import"./chunk-ZQ4PNKMQ.js";import"./chunk-2VBGTGDK.js";import"./chunk-Q2ISNOBQ.js";import"./chunk-S6OV7Z6K.js";import"./chunk-AVM3O74V.js";import"./chunk-R2WB5BKF.js";import"./chunk-Y5FFL6UO.js";import"./chunk-QMW7VEPC.js";import"./chunk-ETOTUZPB.js";import"./chunk-RMGBR3XZ.js";import"./chunk-L7JP7DUO.js";import"./chunk-6JBSBSCL.js";import"./chunk-D5LZGIJU.js";import"./chunk-5AUQIK3Q.js";import"./chunk-YVVKUPGL.js";import"./chunk-7IFLU3CY.js";import"./chunk-OFTIPZTH.js";import"./chunk-U2LBBBWO.js";import"./chunk-B44X7JAJ.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{c as createAdamTools,b as getToolsFingerprint,a as resolveDeliveryTargets};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-SC2DDRYB.js";import"./chunk-B544JOZM.js";import"./chunk-Y5FFL6UO.js";import"./chunk-L7JP7DUO.js";import"./chunk-O7XQSONJ.js";import"./chunk-6JBSBSCL.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
@@ -0,0 +1 @@
1
+ import{q as a,r as b,s as c,t as d,u as e}from"./chunk-JRQQLKLU.js";import"./chunk-JYHOGBCP.js";import"./chunk-WQFNB2MQ.js";import"./chunk-7T4B2MZ7.js";import"./chunk-UXDTFTG5.js";import"./chunk-SWP2JC54.js";import"./chunk-X5V4VMET.js";import"./chunk-ZQ4PNKMQ.js";import"./chunk-N4ES7TCL.js";import"./chunk-Q2ISNOBQ.js";import"./chunk-S6OV7Z6K.js";import"./chunk-AVM3O74V.js";import"./chunk-R2WB5BKF.js";import"./chunk-QMW7VEPC.js";import"./chunk-ETOTUZPB.js";import"./chunk-RMGBR3XZ.js";import"./chunk-L7JP7DUO.js";import"./chunk-O7XQSONJ.js";import"./chunk-6JBSBSCL.js";import"./chunk-HSEP6LNQ.js";import"./chunk-D5LZGIJU.js";import"./chunk-OFTIPZTH.js";import"./chunk-U2LBBBWO.js";import"./chunk-B44X7JAJ.js";import"./chunk-AQO6IIHV.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};
@@ -0,0 +1 @@
1
+ import{b as a,c as b,d as c}from"./chunk-Z434UGTC.js";import"./chunk-FUWPDXXG.js";import"./chunk-X5V4VMET.js";import"./chunk-ZQ4PNKMQ.js";import"./chunk-ETK722ZZ.js";import"./chunk-2VBGTGDK.js";import"./chunk-N4ES7TCL.js";import"./chunk-Q2ISNOBQ.js";import"./chunk-S6OV7Z6K.js";import"./chunk-AVM3O74V.js";import"./chunk-R2WB5BKF.js";import"./chunk-B544JOZM.js";import"./chunk-Y5FFL6UO.js";import"./chunk-RMGBR3XZ.js";import"./chunk-L7JP7DUO.js";import"./chunk-O7XQSONJ.js";import"./chunk-6JBSBSCL.js";import"./chunk-D5LZGIJU.js";import"./chunk-5AUQIK3Q.js";import"./chunk-YVVKUPGL.js";import"./chunk-7IFLU3CY.js";import"./chunk-OFTIPZTH.js";import"./chunk-U2LBBBWO.js";import"./chunk-B44X7JAJ.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c}from"./chunk-QYRI4HYA.js";import"./chunk-ZQ4PNKMQ.js";import"./chunk-Y5FFL6UO.js";import"./chunk-6JBSBSCL.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunk-GSFLLRS7.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
1
+ import{a,b,c,d,e,f}from"./chunk-Y5FFL6UO.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
@@ -1,8 +1,8 @@
1
- import{a as oe}from"./chunk-IZNEOYRP.js";import{k as F}from"./chunk-NWMOV23A.js";import{b as ee}from"./chunk-2L2347UQ.js";import{a as Z,b as h}from"./chunk-K4C43YDD.js";import{e as N,f as D,j as Ae}from"./chunk-WMB7P64J.js";import{a as Q}from"./chunk-UQJZU3R5.js";import{d as K}from"./chunk-GSMC3VUM.js";import{c as te,i as Ce,l as re,o as ne,r as xe}from"./chunk-HQRUJQN7.js";import{b as u,d as v}from"./chunk-5EPG2US5.js";import{a as z,h as Le}from"./chunk-WBAPIPST.js";import{c as k,h as X}from"./chunk-MRTJFYPR.js";Ce();import{homedir as Ie}from"os";import{resolve as j}from"path";import{z as g}from"zod";Le();function ie(){return[...z]}xe();Ae();var Oe=new Set(ie()),Pe=g.object({tools:g.array(g.string().refine(t=>Oe.has(t),{message:"Unknown tool"})).optional(),paths:g.array(g.object({path:g.string().refine(t=>t.startsWith("/")||t.startsWith("~"),{message:"path must be absolute or tilde-prefixed"}),access:g.enum(["ro","rw"])})).optional(),osCapabilities:g.array(g.object({id:g.enum(te),targets:g.array(g.string()).optional()})).optional(),network:g.boolean().optional(),plugins:g.array(g.string()).optional()});function ae(t){return t.startsWith("~")?t.replace(/^~/,Ie()):t}function Ne(t){let e=ae(t);return e.startsWith("/")?j(e):null}function ce(t,e){let n=[{path:j(e),access:"rw"}];for(let r of t.additionalDirectories??[])n.push({path:j(ae(r.path)),access:r.mode??"rw"});return n}function U(t,e){let n=Ne(t.path);if(!n)return!1;let r=e.filter(o=>n===o.path||n.startsWith(`${o.path}/`)).sort((o,s)=>s.path.length-o.path.length);if(r.length===0)return!1;let i=r[0];return t.access==="rw"?i.access==="rw":!0}function B(t,e){if(!t?.length)return[];let n=new Set(e??[]);return t.filter(r=>!n.has(r))}function G(t,e){if(!t?.length)return[];let n=new Set((e??[]).map(r=>r.id));return t.filter(r=>!n.has(r.id))}function W(t,e){if(!t?.length)return[];let n=new Set(e);return t.filter(r=>!n.has(r))}function H(t,e){return t?(e??[]).some(n=>n.id==="local-network"):!0}function le(t,e,n,r){let i=[];if(e.tools?.length){let o=B(e.tools,t.allowedTools).length;i.push((e.tools.length-o)/e.tools.length)}if(e.paths?.length){let o=e.paths.filter(s=>U(s,n)).length;i.push(o/e.paths.length)}if(e.osCapabilities?.length){let o=G(e.osCapabilities,t.osCapabilities).length;i.push((e.osCapabilities.length-o)/e.osCapabilities.length)}if(e.plugins?.length){let o=W(e.plugins,r).length;i.push((e.plugins.length-o)/e.plugins.length)}return e.network===!0&&i.push(H(e.network,t.osCapabilities)?1:0),i.length===0?1:i.reduce((o,s)=>o+s,0)/i.length}function De(t,e){if(!e.tools?.length||!t.approvalRequired?.length)return[];let n=new Set(t.approvalRequired),r=e.tools.filter(o=>n.has(o));if(!r.length)return[];let i=e.paths?.filter(o=>o.access==="rw").length??0;return[{code:"APPROVAL_WILL_TRIGGER",tools:r,expectedPromptCount:Math.max(r.length,i||r.length)}]}function Fe(t,e,n,r){let i=B(e.tools,t.allowedTools),o=(e.paths??[]).filter(d=>!U(d,n)),s=G(e.osCapabilities,t.osCapabilities),c=W(e.plugins,r),a={};return i.length&&(a.tools=i),o.length&&(a.paths=o),s.length&&(a.osCapabilities=s),c.length&&(a.plugins=c),e.network===!0&&!H(e.network,t.osCapabilities)&&(a.network=!0),a}function de(t,e){D(t);let n=N(t.name),r=ce(t,n),o=F(t).plugins.map(l=>l.name),s=B(e.tools,t.allowedTools);if(s.length)return{ok:!1,code:"ROLE_TOOL_MISMATCH",reason:`Missing tools: ${s.join(", ")}`,missing:{tools:s}};let c=(e.paths??[]).filter(l=>!U(l,r));if(c.length)return{ok:!1,code:"ROLE_PATH_SCOPE_MISMATCH",reason:`Missing path scope: ${c.map(l=>`${l.path} (${l.access})`).join(", ")}`,missing:{paths:c}};let a=G(e.osCapabilities,t.osCapabilities);if(a.length)return{ok:!1,code:"ROLE_OS_CAPABILITY_MISMATCH",reason:`Missing OS capabilities: ${a.map(l=>l.id).join(", ")}`,missing:{osCapabilities:a}};let d=W(e.plugins,o);return d.length?{ok:!1,code:"ROLE_PLUGIN_MISMATCH",reason:`Missing plugins: ${d.join(", ")}`,missing:{plugins:d}}:e.network===!0&&!H(e.network,t.osCapabilities)?{ok:!1,code:"ROLE_NETWORK_MISMATCH",reason:"Role lacks network capability (local-network)",missing:{network:!0}}:{ok:!0,roleId:t.id,executionProfile:t,fitScore:le(t,e,r,o),warnings:De(t,e)}}function se(t){return ne("active",100,0).filter(e=>e.source!=="system").map(e=>{D(e);let n=ce(e,N(e.name)),i=F(e).plugins.map(s=>s.name),o=de(e,t);return{role:e,evaluation:o,fitScore:le(e,t,n,i),missing:Fe(e,t,n,i)}}).sort((e,n)=>{let r=n.fitScore-e.fitScore;return r!==0?r:(n.role.performanceScore??0)-(e.role.performanceScore??0)})}async function ue(t){let{requirements:e,roleId:n,autoSelectRole:r}=t;if(!n&&!r)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"Must provide either roleId or autoSelectRole=true"};if(e){let l=Pe.safeParse(e);if(!l.success)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:g.prettifyError(l.error)}}if(r&&!e)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"autoSelectRole requires a requirements object"};let i=e??{};if(n&&!r){let l=re(n);if(!l||l.status!=="active")return{ok:!1,code:"ROLE_NOT_FOUND",reason:`Role not found or not active: ${n}`};let p=de(l,i);return p.ok?(p.auditCandidates=[{roleId:l.id,name:l.name,fitScore:p.fitScore,fits:!0}],p):(e&&(p.candidates=se(e).map(S=>({roleId:S.role.id,name:S.role.name,fitScore:S.fitScore,missing:S.missing}))),p)}let o=se(e),s=o.filter(l=>l.evaluation.ok);if(!s.length)return{ok:!1,code:"ROLE_SELECTION_AMBIGUOUS",reason:"No role covers the requirements",candidates:o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,missing:l.missing}))};let c=s[0],a=c.evaluation,d=s[1];return d&&d.fitScore===c.fitScore&&(a.tieBreakReason=`fitScore tie at ${c.fitScore}; chose ${c.role.name} by performanceScore`),a.auditCandidates=o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,fits:l.evaluation.ok})),a}v();function L(t){return{id:t.id,roleId:t.role_id,taskType:t.task_type,name:t.name,promptTemplate:t.prompt_template,alpha:t.alpha,beta:t.beta,totalTrials:t.total_trials,avgReward:t.avg_reward??void 0,createdAt:t.created_at,updatedAt:t.updated_at??void 0}}function pe(t){u().prepare(`
1
+ import{k as F}from"./chunk-Q2ISNOBQ.js";import{a as oe}from"./chunk-S6OV7Z6K.js";import{b as ee}from"./chunk-AVM3O74V.js";import{a as Z,b as h}from"./chunk-R2WB5BKF.js";import{e as N,f as D,j as Ie}from"./chunk-RMGBR3XZ.js";import{a as Q}from"./chunk-YVVKUPGL.js";import{d as K}from"./chunk-OFTIPZTH.js";import{c as te,i as Ce,l as re,o as ne,r as xe}from"./chunk-U2LBBBWO.js";import{b as u,d as v}from"./chunk-AQO6IIHV.js";import{a as z,h as Le}from"./chunk-WBAPIPST.js";import{c as k,h as X}from"./chunk-MRTJFYPR.js";Ce();import{homedir as Ae}from"os";import{resolve as j}from"path";import{z as g}from"zod";Le();function ie(){return[...z]}xe();Ie();var Oe=new Set(ie()),Pe=g.object({tools:g.array(g.string().refine(t=>Oe.has(t),{message:"Unknown tool"})).optional(),paths:g.array(g.object({path:g.string().refine(t=>t.startsWith("/")||t.startsWith("~"),{message:"path must be absolute or tilde-prefixed"}),access:g.enum(["ro","rw"])})).optional(),osCapabilities:g.array(g.object({id:g.enum(te),targets:g.array(g.string()).optional()})).optional(),network:g.boolean().optional(),plugins:g.array(g.string()).optional()});function ae(t){return t.startsWith("~")?t.replace(/^~/,Ae()):t}function Ne(t){let e=ae(t);return e.startsWith("/")?j(e):null}function ce(t,e){let n=[{path:j(e),access:"rw"}];for(let r of t.additionalDirectories??[])n.push({path:j(ae(r.path)),access:r.mode??"rw"});return n}function U(t,e){let n=Ne(t.path);if(!n)return!1;let r=e.filter(o=>n===o.path||n.startsWith(`${o.path}/`)).sort((o,s)=>s.path.length-o.path.length);if(r.length===0)return!1;let i=r[0];return t.access==="rw"?i.access==="rw":!0}function B(t,e){if(!t?.length)return[];let n=new Set(e??[]);return t.filter(r=>!n.has(r))}function G(t,e){if(!t?.length)return[];let n=new Set((e??[]).map(r=>r.id));return t.filter(r=>!n.has(r.id))}function W(t,e){if(!t?.length)return[];let n=new Set(e);return t.filter(r=>!n.has(r))}function H(t,e){return t?(e??[]).some(n=>n.id==="local-network"):!0}function le(t,e,n,r){let i=[];if(e.tools?.length){let o=B(e.tools,t.allowedTools).length;i.push((e.tools.length-o)/e.tools.length)}if(e.paths?.length){let o=e.paths.filter(s=>U(s,n)).length;i.push(o/e.paths.length)}if(e.osCapabilities?.length){let o=G(e.osCapabilities,t.osCapabilities).length;i.push((e.osCapabilities.length-o)/e.osCapabilities.length)}if(e.plugins?.length){let o=W(e.plugins,r).length;i.push((e.plugins.length-o)/e.plugins.length)}return e.network===!0&&i.push(H(e.network,t.osCapabilities)?1:0),i.length===0?1:i.reduce((o,s)=>o+s,0)/i.length}function De(t,e){if(!e.tools?.length||!t.approvalRequired?.length)return[];let n=new Set(t.approvalRequired),r=e.tools.filter(o=>n.has(o));if(!r.length)return[];let i=e.paths?.filter(o=>o.access==="rw").length??0;return[{code:"APPROVAL_WILL_TRIGGER",tools:r,expectedPromptCount:Math.max(r.length,i||r.length)}]}function Fe(t,e,n,r){let i=B(e.tools,t.allowedTools),o=(e.paths??[]).filter(d=>!U(d,n)),s=G(e.osCapabilities,t.osCapabilities),c=W(e.plugins,r),a={};return i.length&&(a.tools=i),o.length&&(a.paths=o),s.length&&(a.osCapabilities=s),c.length&&(a.plugins=c),e.network===!0&&!H(e.network,t.osCapabilities)&&(a.network=!0),a}function de(t,e){D(t);let n=N(t.name),r=ce(t,n),o=F(t).plugins.map(l=>l.name),s=B(e.tools,t.allowedTools);if(s.length)return{ok:!1,code:"ROLE_TOOL_MISMATCH",reason:`Missing tools: ${s.join(", ")}`,missing:{tools:s}};let c=(e.paths??[]).filter(l=>!U(l,r));if(c.length)return{ok:!1,code:"ROLE_PATH_SCOPE_MISMATCH",reason:`Missing path scope: ${c.map(l=>`${l.path} (${l.access})`).join(", ")}`,missing:{paths:c}};let a=G(e.osCapabilities,t.osCapabilities);if(a.length)return{ok:!1,code:"ROLE_OS_CAPABILITY_MISMATCH",reason:`Missing OS capabilities: ${a.map(l=>l.id).join(", ")}`,missing:{osCapabilities:a}};let d=W(e.plugins,o);return d.length?{ok:!1,code:"ROLE_PLUGIN_MISMATCH",reason:`Missing plugins: ${d.join(", ")}`,missing:{plugins:d}}:e.network===!0&&!H(e.network,t.osCapabilities)?{ok:!1,code:"ROLE_NETWORK_MISMATCH",reason:"Role lacks network capability (local-network)",missing:{network:!0}}:{ok:!0,roleId:t.id,executionProfile:t,fitScore:le(t,e,r,o),warnings:De(t,e)}}function se(t){return ne("active",100,0).filter(e=>e.source!=="system").map(e=>{D(e);let n=ce(e,N(e.name)),i=F(e).plugins.map(s=>s.name),o=de(e,t);return{role:e,evaluation:o,fitScore:le(e,t,n,i),missing:Fe(e,t,n,i)}}).sort((e,n)=>{let r=n.fitScore-e.fitScore;return r!==0?r:(n.role.performanceScore??0)-(e.role.performanceScore??0)})}async function ue(t){let{requirements:e,roleId:n,autoSelectRole:r}=t;if(!n&&!r)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"Must provide either roleId or autoSelectRole=true"};if(e){let l=Pe.safeParse(e);if(!l.success)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:g.prettifyError(l.error)}}if(r&&!e)return{ok:!1,code:"REQUIREMENTS_MISSING",reason:"autoSelectRole requires a requirements object"};let i=e??{};if(n&&!r){let l=re(n);if(!l||l.status!=="active")return{ok:!1,code:"ROLE_NOT_FOUND",reason:`Role not found or not active: ${n}`};let p=de(l,i);return p.ok?(p.auditCandidates=[{roleId:l.id,name:l.name,fitScore:p.fitScore,fits:!0}],p):(e&&(p.candidates=se(e).map(S=>({roleId:S.role.id,name:S.role.name,fitScore:S.fitScore,missing:S.missing}))),p)}let o=se(e),s=o.filter(l=>l.evaluation.ok);if(!s.length)return{ok:!1,code:"ROLE_SELECTION_AMBIGUOUS",reason:"No role covers the requirements",candidates:o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,missing:l.missing}))};let c=s[0],a=c.evaluation,d=s[1];return d&&d.fitScore===c.fitScore&&(a.tieBreakReason=`fitScore tie at ${c.fitScore}; chose ${c.role.name} by performanceScore`),a.auditCandidates=o.map(l=>({roleId:l.role.id,name:l.role.name,fitScore:l.fitScore,fits:l.evaluation.ok})),a}v();function L(t){return{id:t.id,roleId:t.role_id,taskType:t.task_type,name:t.name,promptTemplate:t.prompt_template,alpha:t.alpha,beta:t.beta,totalTrials:t.total_trials,avgReward:t.avg_reward??void 0,createdAt:t.created_at,updatedAt:t.updated_at??void 0}}function pe(t){u().prepare(`
2
2
  INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
3
3
  alpha, beta, total_trials, avg_reward, created_at, updated_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
- `).run(t.id,t.roleId,t.taskType,t.name,t.promptTemplate,t.alpha,t.beta,t.totalTrials,t.avgReward??null,t.createdAt,t.updatedAt??null)}function ge(t){let n=u().prepare("SELECT * FROM strategies WHERE id = ?").get(t);return n?L(n):void 0}function at(t=100){return u().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(t).map(L)}function ct(t){return u().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(t).map(L)}function b(t,e){return u().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(t,e).map(L)}function me(t,e){u().prepare(`
5
+ `).run(t.id,t.roleId,t.taskType,t.name,t.promptTemplate,t.alpha,t.beta,t.totalTrials,t.avgReward??null,t.createdAt,t.updatedAt??null)}function ge(t){let n=u().prepare("SELECT * FROM strategies WHERE id = ?").get(t);return n?L(n):void 0}function ct(t=100){return u().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(t).map(L)}function lt(t){return u().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(t).map(L)}function b(t,e){return u().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(t,e).map(L)}function me(t,e){u().prepare(`
6
6
  UPDATE strategies
7
7
  SET alpha = alpha + ?,
8
8
  beta = beta + ?,
@@ -13,12 +13,12 @@ import{a as oe}from"./chunk-IZNEOYRP.js";import{k as F}from"./chunk-NWMOV23A.js"
13
13
  END,
14
14
  updated_at = ?
15
15
  WHERE id = ?
16
- `).run(e,1-e,e,e,Date.now(),t)}v();function fe(t){return{id:t.id,name:t.name,description:t.description??void 0,roleId:t.role,metricType:t.metric_type,targetValue:t.target_value,currentValue:t.current_value,deadline:t.deadline,budgetUsd:t.budget_usd,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at??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}}function ut(t){u().prepare(`
16
+ `).run(e,1-e,e,e,Date.now(),t)}v();function fe(t){return{id:t.id,name:t.name,description:t.description??void 0,roleId:t.role,metricType:t.metric_type,targetValue:t.target_value,currentValue:t.current_value,deadline:t.deadline,budgetUsd:t.budget_usd,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at??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}}function pt(t){u().prepare(`
17
17
  INSERT INTO goals (id, name, description, role, metric_type, target_value,
18
18
  current_value, deadline, budget_usd, status, created_at, updated_at,
19
19
  source_session_id, deliver_to, report_to)
20
20
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
21
- `).run(t.id,t.name,t.description??null,t.roleId,t.metricType,t.targetValue,t.currentValue,t.deadline,t.budgetUsd,t.status,t.createdAt,t.updatedAt??null,t.sourceSessionId??null,t.deliverTo?JSON.stringify(t.deliverTo):null,t.reportTo?JSON.stringify(t.reportTo):null)}function he(t){let n=u().prepare("SELECT * FROM goals WHERE id = ?").get(t);return n?fe(n):void 0}function pt(t,e){let n=u(),r=[],i=[],o={name:"name",description:"description",roleId:"role",metricType:"metric_type",targetValue:"target_value",currentValue:"current_value",deadline:"deadline",budgetUsd:"budget_usd",status:"status",updatedAt:"updated_at",sourceSessionId:"source_session_id"};for(let[s,c]of Object.entries(o))s in e&&(r.push(`${c} = ?`),i.push(e[s]??null));"deliverTo"in e&&(r.push("deliver_to = ?"),i.push(JSON.stringify(e.deliverTo))),"reportTo"in e&&(r.push("report_to = ?"),i.push(JSON.stringify(e.reportTo))),r.length!==0&&(i.push(t),n.prepare(`UPDATE goals SET ${r.join(", ")} WHERE id = ?`).run(...i))}function gt(t,e=100,n=0){let r=u(),i="SELECT * FROM goals",o=[];return t&&(i+=" WHERE status = ?",o.push(t)),i+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",o.push(e,n),r.prepare(i).all(...o).map(fe)}function mt(t){u().prepare("DELETE FROM goals WHERE id = ?").run(t)}var C=class{static collect(e,n){let r=h(e);if(!r)return this.emptyMetrics(e,n);let i=ee(e,500,0),o=r.completedAt&&r.startedAt?r.completedAt-r.startedAt:0,s=new Set,c=0,a=0;for(let l of i)l.type==="tool_call"&&l.toolName&&s.add(l.toolName),l.type==="error"&&c++,l.type==="approval_request"&&a++;let d={taskId:e,goalId:n,timestamp:Date.now(),durationMs:o,costUsd:r.costUsd??0,turns:r.numTurns??0,toolCount:s.size,errorCount:c,approvalCount:a,rawScore:0,isComplete:r.status==="completed"};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(e){let r=1-Math.min(e.durationMs/6e5,1),o=1-Math.min(e.costUsd/5,1),c=1-Math.min(e.turns/50,1),a;e.toolCount>=3&&e.toolCount<=15?a=1:e.toolCount<3?a=e.toolCount/3:a=Math.max(0,1-(e.toolCount-15)/15);let d=e.errorCount===0?1:Math.max(0,1-e.errorCount*.2),l=Math.min(1,.5+e.approvalCount*.25);return .3*r+.2*o+.2*c+.1*a+.15*d+.05*l}static cache=new Map;static persist(e){this.cache.set(e.taskId,e)}static getCached(e){return this.cache.get(e)}static clearCache(){this.cache.clear()}static emptyMetrics(e,n){return{taskId:e,goalId:n,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};v();function je(t){return{id:t.id,strategyId:t.strategy_id,goalId:t.goal_id,taskId:t.task_id??void 0,reward:t.reward??void 0,metricL2Score:t.metric_l2_score??void 0,metricL3Score:t.metric_l3_score??void 0,context:t.context??void 0,completedAt:t.completed_at}}function be(t){u().prepare(`
21
+ `).run(t.id,t.name,t.description??null,t.roleId,t.metricType,t.targetValue,t.currentValue,t.deadline,t.budgetUsd,t.status,t.createdAt,t.updatedAt??null,t.sourceSessionId??null,t.deliverTo?JSON.stringify(t.deliverTo):null,t.reportTo?JSON.stringify(t.reportTo):null)}function he(t){let n=u().prepare("SELECT * FROM goals WHERE id = ?").get(t);return n?fe(n):void 0}function gt(t,e){let n=u(),r=[],i=[],o={name:"name",description:"description",roleId:"role",metricType:"metric_type",targetValue:"target_value",currentValue:"current_value",deadline:"deadline",budgetUsd:"budget_usd",status:"status",updatedAt:"updated_at",sourceSessionId:"source_session_id"};for(let[s,c]of Object.entries(o))s in e&&(r.push(`${c} = ?`),i.push(e[s]??null));"deliverTo"in e&&(r.push("deliver_to = ?"),i.push(JSON.stringify(e.deliverTo))),"reportTo"in e&&(r.push("report_to = ?"),i.push(JSON.stringify(e.reportTo))),r.length!==0&&(i.push(t),n.prepare(`UPDATE goals SET ${r.join(", ")} WHERE id = ?`).run(...i))}function mt(t,e=100,n=0){let r=u(),i="SELECT * FROM goals",o=[];return t&&(i+=" WHERE status = ?",o.push(t)),i+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",o.push(e,n),r.prepare(i).all(...o).map(fe)}function ft(t){u().prepare("DELETE FROM goals WHERE id = ?").run(t)}var C=class{static collect(e,n){let r=h(e);if(!r)return this.emptyMetrics(e,n);let i=ee(e,500,0),o=r.completedAt&&r.startedAt?r.completedAt-r.startedAt:0,s=new Set,c=0,a=0;for(let l of i)l.type==="tool_call"&&l.toolName&&s.add(l.toolName),l.type==="error"&&c++,l.type==="approval_request"&&a++;let d={taskId:e,goalId:n,timestamp:Date.now(),durationMs:o,costUsd:r.costUsd??0,turns:r.numTurns??0,toolCount:s.size,errorCount:c,approvalCount:a,rawScore:0,isComplete:r.status==="completed"};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(e){let r=1-Math.min(e.durationMs/6e5,1),o=1-Math.min(e.costUsd/5,1),c=1-Math.min(e.turns/50,1),a;e.toolCount>=3&&e.toolCount<=15?a=1:e.toolCount<3?a=e.toolCount/3:a=Math.max(0,1-(e.toolCount-15)/15);let d=e.errorCount===0?1:Math.max(0,1-e.errorCount*.2),l=Math.min(1,.5+e.approvalCount*.25);return .3*r+.2*o+.2*c+.1*a+.15*d+.05*l}static cache=new Map;static persist(e){this.cache.set(e.taskId,e)}static getCached(e){return this.cache.get(e)}static clearCache(){this.cache.clear()}static emptyMetrics(e,n){return{taskId:e,goalId:n,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};v();function je(t){return{id:t.id,strategyId:t.strategy_id,goalId:t.goal_id,taskId:t.task_id??void 0,reward:t.reward??void 0,metricL2Score:t.metric_l2_score??void 0,metricL3Score:t.metric_l3_score??void 0,context:t.context??void 0,completedAt:t.completed_at}}function be(t){u().prepare(`
22
22
  INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
23
23
  metric_l2_score, metric_l3_score, context, completed_at)
24
24
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -33,15 +33,15 @@ Provide:
33
33
  2. Confidence (0-1): How confident are you in this evaluation?
34
34
  3. Reasoning: Brief explanation of your scoring
35
35
 
36
- Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};v();function Be(t){return{id:t.id,goalId:t.goal_id,level:t.level,parentId:t.parent_id??void 0,name:t.name,description:t.description??void 0,weight:t.weight,calibrationFactor:t.calibration_factor,createdAt:t.created_at}}function xt(t){u().prepare(`
36
+ Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};v();function Be(t){return{id:t.id,goalId:t.goal_id,level:t.level,parentId:t.parent_id??void 0,name:t.name,description:t.description??void 0,weight:t.weight,calibrationFactor:t.calibration_factor,createdAt:t.created_at}}function It(t){u().prepare(`
37
37
  INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
38
38
  weight, calibration_factor, created_at)
39
39
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
40
- `).run(t.id,t.goalId,t.level,t.parentId??null,t.name,t.description??null,t.weight,t.calibrationFactor,t.createdAt)}function Re(t){return u().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(t).map(Be)}var Ge={L0:.2,L1:.15,L2:.35,L3:.3},A=class t{goalId;nodes;children;constructor(e,n){this.goalId=e,this.nodes=new Map(n.map(r=>[r.id,r])),this.children=new Map;for(let r of n){let i=r.parentId,o=this.children.get(i)??[];o.push(r),this.children.set(i,o)}this.validateAcyclicity()}validateAcyclicity(){for(let e of this.nodes.values()){if(e.parentId&&!this.nodes.has(e.parentId))continue;let n=new Set,r=e.id;for(;r;){if(n.has(r))throw new Error(`Cycle detected in metric tree at node ${r}`);n.add(r),r=this.nodes.get(r)?.parentId}}}static buildFromGoal(e){let n=Re(e);return new t(e,n)}static fromNodes(e,n){return new t(e,n)}queryPath(e){let n=[];for(let r of this.nodes.values())r.level===e&&n.push(r);return n.sort((r,i)=>i.weight-r.weight)}aggregateScores(e,n){let r=this.queryPath(e);if(r.length===0)return 0;let i=0,o=0;for(let s of r){let c=n.get(s.id)??0,a=s.weight*s.calibrationFactor;i+=c*a,o+=a}return o>0?i/o:0}getWeightedScore(e){let n=0;for(let[r,i]of Object.entries(Ge)){let o=this.aggregateScores(r,e);n+=o*i}return Math.max(0,Math.min(1,n))}getNodeCount(){return this.nodes.size}getChildren(e){return this.children.get(e)??[]}};X();var Ut=k("agent");function Te(t,e){let n=Date.now(),r=A.buildFromGoal(t),i=new Map,o=x.collect(t);for(let a of r.queryPath("L0"))i.set(a.id,o.rawScore);let s=We(r);if(e){let a=C.collect(e,t);if(a.isComplete){for(let l of r.queryPath("L3"))i.set(l.id,a.rawScore);let d=r.getNodeCount()>0?r.getWeightedScore(i):Math.max(0,Math.min(1,a.rawScore*.65+o.rawScore*.35));return{goalId:t,taskId:e,reward:d,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:a.rawScore},calibrationFactors:s,source:"objective",confidence:.9,computedAt:n}}}if(e&&!y.shouldUseObjective(e)){let d=y.evaluate(e,"general_quality"),l=o.rawScore*.5+.5*.5;return{goalId:t,taskId:e,reward:o.rawScore,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:s,source:"llm_judge",confidence:.4,computedAt:n}}let c=r.getNodeCount()>0?r.getWeightedScore(i):o.rawScore;return{goalId:t,reward:c,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:0},calibrationFactors:s,source:"fallback",confidence:.3,computedAt:n}}function We(t){let e={L0:1,L1:1,L2:1,L3:1};for(let n of["L0","L1","L2","L3"]){let r=t.queryPath(n);r.length>0&&(e[n]=r[0].calibrationFactor)}return e}import{v4 as we}from"uuid";var M=class{static sampleBeta(e,n){let r=this.sampleGamma(e,1),i=this.sampleGamma(n,1);return r/(r+i)}static sampleGamma(e,n){if(e<1)return this.sampleGamma(e+1,n)*Math.pow(Math.random(),1/e);let r=e-1/3,i=1/Math.sqrt(9*r);for(;;){let o,s;do o=this.randn(),s=1+i*o;while(s<=0);s=s*s*s;let c=Math.random();if(c<1-.0331*o*o*o*o||Math.log(c)<.5*o*o+r*(1-s+Math.log(s)))return r*s/n}}static randn(){let e=Math.random(),n=Math.random();return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*n)}static sample(e){if(e.length===0)return null;let n=null,r=-1;for(let i of e){let o=this.sampleBeta(i.alpha,i.beta);o>r&&(r=o,n=i)}return n}static getProbabilities(e,n=1e4){let r=new Map;for(let o=0;o<n;o++){let s=this.sample(e);s&&r.set(s.id,(r.get(s.id)||0)+1)}let i=new Map;for(let[o,s]of r)i.set(o,s/n);return i}};var He=5,$=20,_e=.5,I=class{static selectStrategy(e,n){let r=b(e,n);return M.sample(r)}static recordTrial(e,n,r,i,o,s,c){me(e,i),be({id:we(),strategyId:e,goalId:n,taskId:r,reward:i,metricL2Score:o,metricL3Score:s,context:c,completedAt:Date.now()})}static getStrategies(e,n){return b(e,n)}static getStrategyById(e){return ge(e)}static getPopulationStats(e,n){let r=b(e,n);if(r.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let o=r.reduce((a,d)=>a+d.totalTrials,0)/r.length,s=r.filter(a=>a.avgReward!==void 0).map(a=>a.avgReward),c=s.length>0?s.reduce((a,d)=>a+d,0)/s.length:0;return{count:r.length,avgTrials:o,avgReward:c,minTrials:Math.min(...r.map(a=>a.totalTrials)),maxTrials:Math.max(...r.map(a=>a.totalTrials))}}static shouldEvolve(e,n){let r=this.getPopulationStats(e,n);return r.count<He?!0:r.count<$&&r.maxTrials>0}static addStrategy(e,n,r,i){if(b(e,n).length>=$)throw new Error(`Strategy population at maximum (${$}) for ${e}/${n}`);let s={id:`strat-${we().slice(0,8)}`,roleId:e,taskType:n,name:r,promptTemplate:i,alpha:_e,beta:_e,totalTrials:0,createdAt:Date.now()};return pe(s),s}static getTopStrategies(e,n,r=3){let o=b(e,n).filter(s=>s.totalTrials>0);return o.sort((s,c)=>(c.avgReward??0)-(s.avgReward??0)),o.slice(0,r)}static getSamplingProbabilities(e,n){let r=b(e,n);return M.getProbabilities(r)}static evaluateAndRecord(e,n,r,i,o,s){let c=Te(n,r);return this.recordTrial(e,n,r,c.reward,i,o,s),c.reward}};import{v4 as Je}from"uuid";v();import{v4 as $e}from"uuid";function ve(t){u().prepare(`
40
+ `).run(t.id,t.goalId,t.level,t.parentId??null,t.name,t.description??null,t.weight,t.calibrationFactor,t.createdAt)}function Re(t){return u().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(t).map(Be)}var Ge={L0:.2,L1:.15,L2:.35,L3:.3},I=class t{goalId;nodes;children;constructor(e,n){this.goalId=e,this.nodes=new Map(n.map(r=>[r.id,r])),this.children=new Map;for(let r of n){let i=r.parentId,o=this.children.get(i)??[];o.push(r),this.children.set(i,o)}this.validateAcyclicity()}validateAcyclicity(){for(let e of this.nodes.values()){if(e.parentId&&!this.nodes.has(e.parentId))continue;let n=new Set,r=e.id;for(;r;){if(n.has(r))throw new Error(`Cycle detected in metric tree at node ${r}`);n.add(r),r=this.nodes.get(r)?.parentId}}}static buildFromGoal(e){let n=Re(e);return new t(e,n)}static fromNodes(e,n){return new t(e,n)}queryPath(e){let n=[];for(let r of this.nodes.values())r.level===e&&n.push(r);return n.sort((r,i)=>i.weight-r.weight)}aggregateScores(e,n){let r=this.queryPath(e);if(r.length===0)return 0;let i=0,o=0;for(let s of r){let c=n.get(s.id)??0,a=s.weight*s.calibrationFactor;i+=c*a,o+=a}return o>0?i/o:0}getWeightedScore(e){let n=0;for(let[r,i]of Object.entries(Ge)){let o=this.aggregateScores(r,e);n+=o*i}return Math.max(0,Math.min(1,n))}getNodeCount(){return this.nodes.size}getChildren(e){return this.children.get(e)??[]}};X();var Bt=k("agent");function Te(t,e){let n=Date.now(),r=I.buildFromGoal(t),i=new Map,o=x.collect(t);for(let a of r.queryPath("L0"))i.set(a.id,o.rawScore);let s=We(r);if(e){let a=C.collect(e,t);if(a.isComplete){for(let l of r.queryPath("L3"))i.set(l.id,a.rawScore);let d=r.getNodeCount()>0?r.getWeightedScore(i):Math.max(0,Math.min(1,a.rawScore*.65+o.rawScore*.35));return{goalId:t,taskId:e,reward:d,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:a.rawScore},calibrationFactors:s,source:"objective",confidence:.9,computedAt:n}}}if(e&&!y.shouldUseObjective(e)){let d=y.evaluate(e,"general_quality"),l=o.rawScore*.5+.5*.5;return{goalId:t,taskId:e,reward:o.rawScore,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:s,source:"llm_judge",confidence:.4,computedAt:n}}let c=r.getNodeCount()>0?r.getWeightedScore(i):o.rawScore;return{goalId:t,reward:c,breakdown:{L0:o.rawScore,L1:0,L2:0,L3:0},calibrationFactors:s,source:"fallback",confidence:.3,computedAt:n}}function We(t){let e={L0:1,L1:1,L2:1,L3:1};for(let n of["L0","L1","L2","L3"]){let r=t.queryPath(n);r.length>0&&(e[n]=r[0].calibrationFactor)}return e}import{v4 as we}from"uuid";var M=class{static sampleBeta(e,n){let r=this.sampleGamma(e,1),i=this.sampleGamma(n,1);return r/(r+i)}static sampleGamma(e,n){if(e<1)return this.sampleGamma(e+1,n)*Math.pow(Math.random(),1/e);let r=e-1/3,i=1/Math.sqrt(9*r);for(;;){let o,s;do o=this.randn(),s=1+i*o;while(s<=0);s=s*s*s;let c=Math.random();if(c<1-.0331*o*o*o*o||Math.log(c)<.5*o*o+r*(1-s+Math.log(s)))return r*s/n}}static randn(){let e=Math.random(),n=Math.random();return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*n)}static sample(e){if(e.length===0)return null;let n=null,r=-1;for(let i of e){let o=this.sampleBeta(i.alpha,i.beta);o>r&&(r=o,n=i)}return n}static getProbabilities(e,n=1e4){let r=new Map;for(let o=0;o<n;o++){let s=this.sample(e);s&&r.set(s.id,(r.get(s.id)||0)+1)}let i=new Map;for(let[o,s]of r)i.set(o,s/n);return i}};var He=5,$=20,_e=.5,A=class{static selectStrategy(e,n){let r=b(e,n);return M.sample(r)}static recordTrial(e,n,r,i,o,s,c){me(e,i),be({id:we(),strategyId:e,goalId:n,taskId:r,reward:i,metricL2Score:o,metricL3Score:s,context:c,completedAt:Date.now()})}static getStrategies(e,n){return b(e,n)}static getStrategyById(e){return ge(e)}static getPopulationStats(e,n){let r=b(e,n);if(r.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let o=r.reduce((a,d)=>a+d.totalTrials,0)/r.length,s=r.filter(a=>a.avgReward!==void 0).map(a=>a.avgReward),c=s.length>0?s.reduce((a,d)=>a+d,0)/s.length:0;return{count:r.length,avgTrials:o,avgReward:c,minTrials:Math.min(...r.map(a=>a.totalTrials)),maxTrials:Math.max(...r.map(a=>a.totalTrials))}}static shouldEvolve(e,n){let r=this.getPopulationStats(e,n);return r.count<He?!0:r.count<$&&r.maxTrials>0}static addStrategy(e,n,r,i){if(b(e,n).length>=$)throw new Error(`Strategy population at maximum (${$}) for ${e}/${n}`);let s={id:`strat-${we().slice(0,8)}`,roleId:e,taskType:n,name:r,promptTemplate:i,alpha:_e,beta:_e,totalTrials:0,createdAt:Date.now()};return pe(s),s}static getTopStrategies(e,n,r=3){let o=b(e,n).filter(s=>s.totalTrials>0);return o.sort((s,c)=>(c.avgReward??0)-(s.avgReward??0)),o.slice(0,r)}static getSamplingProbabilities(e,n){let r=b(e,n);return M.getProbabilities(r)}static evaluateAndRecord(e,n,r,i,o,s){let c=Te(n,r);return this.recordTrial(e,n,r,c.reward,i,o,s),c.reward}};import{v4 as Je}from"uuid";v();import{v4 as $e}from"uuid";function ve(t){u().prepare(`
41
41
  INSERT INTO manager_decisions
42
42
  (id, task_id, role_id, decision_type, requirements_json, fit_score, candidates_json, tie_break_reason, created_at)
43
43
  VALUES (?, ?, ?, 'admission', ?, ?, ?, ?, ?)
44
- `).run($e(),t.taskId,t.chosenRoleId,JSON.stringify(t.requirements),t.fitScore,JSON.stringify(t.candidates),t.tieBreakReason??null,Date.now())}function Ve(t){let e=t.toLowerCase(),n={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]};for(let[r,i]of Object.entries(n))if(i.some(o=>e.includes(o)))return r;return"general"}async function or(t){let{prompt:e,roleId:n,requirements:r,autoSelectRole:i,deliverTo:o,reportTo:s,toolOverrides:c,config:a,sourceSessionId:d,parentId:l,templateId:p,stepId:S}=t,O;try{O=K()}catch{O=Q}let w=Je(),ye=Ve(e),f=await ue({taskId:w,requirements:r,roleId:n,autoSelectRole:i});if(!f.ok)return{ok:!1,code:f.code,reason:f.reason,requirements:r,missing:f.missing,candidates:f.candidates};let{executionProfile:R}=f,E=f.roleId,V,q=e,P=I.selectStrategy(E,ye);P?.promptTemplate&&(q=`${P.promptTemplate}
44
+ `).run($e(),t.taskId,t.chosenRoleId,JSON.stringify(t.requirements),t.fitScore,JSON.stringify(t.candidates),t.tieBreakReason??null,Date.now())}function Ve(t){let e=t.toLowerCase(),n={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]};for(let[r,i]of Object.entries(n))if(i.some(o=>e.includes(o)))return r;return"general"}async function ir(t){let{prompt:e,roleId:n,requirements:r,autoSelectRole:i,deliverTo:o,reportTo:s,toolOverrides:c,config:a,sourceSessionId:d,parentId:l,templateId:p,stepId:S,traceId:Ye}=t,O;try{O=K()}catch{O=Q}let w=Je(),ye=Ve(e),f=await ue({taskId:w,requirements:r,roleId:n,autoSelectRole:i});if(!f.ok)return{ok:!1,code:f.code,reason:f.reason,requirements:r,missing:f.missing,candidates:f.candidates};let{executionProfile:R}=f,E=f.roleId,V,q=e,P=A.selectStrategy(E,ye);P?.promptTemplate&&(q=`${P.promptTemplate}
45
45
 
46
46
  ## Task
47
- ${e}`,V=P.id);let m=O.defaults,T={allowedTools:R.allowedTools??[],disallowedTools:R.disallowedTools??[],approvalRequired:R.approvalRequired??[],maxBudgetUsd:R.maxBudgetUsd??m.maxBudgetUsd,plugins:[]},_={allowedTools:qe(T.allowedTools,m.allowedTools),disallowedTools:J(T.disallowedTools,m.disallowedTools),approvalRequired:J(T.approvalRequired,m.approvalRequired),maxBudgetUsd:T.maxBudgetUsd>0?Math.min(T.maxBudgetUsd,m.maxBudgetUsd):m.maxBudgetUsd,plugins:J(T.plugins,m.plugins??[])},Y=_.allowedTools;c?.allowedTools&&(Y=c.allowedTools);let Me={timeout:a?.timeout??m.timeout,approvalRequired:_.approvalRequired,approvalTimeout:a?.approvalTimeout??m.approvalTimeout,allowedTools:Y,disallowedTools:c?.disallowedTools??_.disallowedTools,maxTurns:a?.maxTurns??m.maxTurns,maxBudgetUsd:_.maxBudgetUsd,mcpServers:a?.mcpServers,model:a?.model??R.model??m.model,effort:a?.effort??m.effort,settingSources:a?.settingSources??m.settingSources,workspacePath:a?.workspacePath,env:a?.env??m.env,claudeCodePath:m.claudeCodePath,plugins:a?.plugins??_.plugins,requirements:r,executionProfile:R},Ee={id:w,status:"pending",prompt:q,originalPrompt:e,roleId:E,parentId:l,templateId:p,stepId:S,deliverTo:o,reportTo:s,config:Me,sourceSessionId:d,createdAt:Date.now()};Z(Ee),f.auditCandidates&&ve({taskId:w,chosenRoleId:E,requirements:r??{},fitScore:f.fitScore,tieBreakReason:f.tieBreakReason,candidates:f.auditCandidates});let{serverBus:ke}=await import("./server-bus-GEGVMSCA.js");return ke.emit({type:"task_created",taskId:w}),{ok:!0,taskId:w,roleId:E,requirements:r??{},fitScore:f.fitScore,strategyId:V,warnings:f.warnings}}function qe(t,e){return t?.length?e?.length?t.filter(n=>e.includes(n)):t:e??[]}function J(t=[],e=[]){let n=new Set(t);for(let r of e)n.add(r);return[...n]}export{Pe as a,ce as b,U as c,De as d,se as e,ue as f,at as g,ct as h,ut as i,he as j,pt as k,gt as l,mt as m,xt as n,Te as o,I as p,or as q};
47
+ ${e}`,V=P.id);let m=O.defaults,T={allowedTools:R.allowedTools??[],disallowedTools:R.disallowedTools??[],approvalRequired:R.approvalRequired??[],maxBudgetUsd:R.maxBudgetUsd??m.maxBudgetUsd,plugins:[]},_={allowedTools:qe(T.allowedTools,m.allowedTools),disallowedTools:J(T.disallowedTools,m.disallowedTools),approvalRequired:J(T.approvalRequired,m.approvalRequired),maxBudgetUsd:T.maxBudgetUsd>0?Math.min(T.maxBudgetUsd,m.maxBudgetUsd):m.maxBudgetUsd,plugins:J(T.plugins,m.plugins??[])},Y=_.allowedTools;c?.allowedTools&&(Y=c.allowedTools);let Me={timeout:a?.timeout??m.timeout,approvalRequired:_.approvalRequired,approvalTimeout:a?.approvalTimeout??m.approvalTimeout,allowedTools:Y,disallowedTools:c?.disallowedTools??_.disallowedTools,maxTurns:a?.maxTurns??m.maxTurns,maxBudgetUsd:_.maxBudgetUsd,mcpServers:a?.mcpServers,model:a?.model??R.model??m.model,effort:a?.effort??m.effort,settingSources:a?.settingSources??m.settingSources,workspacePath:a?.workspacePath,env:a?.env??m.env,claudeCodePath:m.claudeCodePath,plugins:a?.plugins??_.plugins,requirements:r,executionProfile:R},Ee={id:w,status:"pending",prompt:q,originalPrompt:e,roleId:E,parentId:l,templateId:p,stepId:S,deliverTo:o,reportTo:s,config:Me,sourceSessionId:d,createdAt:Date.now(),traceId:t.traceId};Z(Ee),f.auditCandidates&&ve({taskId:w,chosenRoleId:E,requirements:r??{},fitScore:f.fitScore,tieBreakReason:f.tieBreakReason,candidates:f.auditCandidates});let{serverBus:ke}=await import("./server-bus-GEGVMSCA.js");return ke.emit({type:"task_created",taskId:w}),{ok:!0,taskId:w,roleId:E,requirements:r??{},fitScore:f.fitScore,strategyId:V,warnings:f.warnings}}function qe(t,e){return t?.length?e?.length?t.filter(n=>e.includes(n)):t:e??[]}function J(t=[],e=[]){let n=new Set(t);for(let r of e)n.add(r);return[...n]}export{Pe as a,ce as b,U as c,De as d,se as e,ue as f,ct as g,lt as h,pt as i,he as j,gt as k,mt as l,ft as m,It as n,Te as o,A as p,ir as q};
@@ -1 +1 @@
1
- import{a as i}from"./chunk-UQJZU3R5.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-GSMC3VUM.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-MRTJFYPR.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
1
+ import{a as i}from"./chunk-YVVKUPGL.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-OFTIPZTH.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-MRTJFYPR.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function A(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function C(e){let t=k();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as o}from"async_hooks";import{v4 as a}from"uuid";var t=new o;function u(r,e){return t.run({traceId:a(),origin:r},e)}function T(r,e,n){return t.run({traceId:r,origin:e},n)}function g(){return t.getStore()?.traceId}export{u as a,T as b,g as c};
@@ -1,4 +1,4 @@
1
- import{b as t,d}from"./chunk-5EPG2US5.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
1
+ import{b as t,d}from"./chunk-AQO6IIHV.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
2
2
  INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
3
3
  deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1 +1 @@
1
- import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-2YTDCR6A.js";import{a as l}from"./chunk-SWP2JC54.js";import{b as S,d as y}from"./chunk-B6LOT5CG.js";import{a as i}from"./chunk-L7JP7DUO.js";import{a as C}from"./chunk-DVN3BFPP.js";import{e as p}from"./chunk-PG6LMSX6.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};
1
+ import{a as l}from"./chunk-SWP2JC54.js";import{a as h,b as u,c,d as m,e as v,f as x}from"./chunk-FUWPDXXG.js";import{a as C}from"./chunk-X5V4VMET.js";import{b as S,d as y}from"./chunk-ZQ4PNKMQ.js";import{a as i}from"./chunk-L7JP7DUO.js";import{e as p}from"./chunk-5AUQIK3Q.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=S(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let f=r.content.slice(0,500),g;try{g=await l(f)}catch{}let M=$(f),T={id:I(),roleId:t,type:r.type,content:f,embedding:g,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};C(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function Q(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return h(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function V(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=v(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),p().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function W(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function X(e){y(e),x(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Y(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function Z(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function ee(e){return m(e)}function P(){let t=p().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function te(){return a}function se(){F(),R()}function oe(){d(),n.clear()}function ne(){d(),n.clear()}export{F as a,Q as b,V as c,B as d,E as e,W as f,X as g,Y as h,Z as i,ee as j,R as k,d as l,te as m,se as n,oe as o,ne as p};