adam-agent-server 1.15.1 → 1.16.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/dist/App-Z2GJAMX3.js +14 -0
  2. package/dist/approval-handler-6NPN24UN.js +1 -0
  3. package/dist/artifacts-S2KD6W76.js +1 -0
  4. package/dist/audit-diagnostics-2MDM3IQT.js +1 -0
  5. package/dist/audit-manager-QG7CMBV2.js +1 -0
  6. package/dist/bree-engine-3QSLZF3W.js +1 -0
  7. package/dist/channels-S4AAOOTN.js +1 -0
  8. package/dist/channels-TYXSSI7D.js +1 -0
  9. package/dist/{chat-tool-calls-KARPW7PE.js → chat-tool-calls-2C7O4B2X.js} +1 -1
  10. package/dist/chunk-32LOJEHE.js +32 -0
  11. package/dist/{chunk-VNXTBIPI.js → chunk-3UR2PN5N.js} +1 -1
  12. package/dist/{chunk-D3SPXZZY.js → chunk-3UZIEE2D.js} +1 -1
  13. package/dist/{chunk-MFFJ5HFI.js → chunk-4234WJJD.js} +5 -5
  14. package/dist/{chunk-2N4EOZZ4.js → chunk-52FETPCI.js} +1 -1
  15. package/dist/{chunk-QZ34KQ76.js → chunk-6Y2DN2UH.js} +1 -1
  16. package/dist/{chunk-NWGRLNUM.js → chunk-AG5SADAI.js} +1 -1
  17. package/dist/{chunk-LZDO4PXK.js → chunk-AQAHVNNG.js} +5 -5
  18. package/dist/{chunk-DMDZ3QW7.js → chunk-C2XFPUFV.js} +1 -1
  19. package/dist/{chunk-XA3MZOWU.js → chunk-EWYXVBOG.js} +7 -7
  20. package/dist/{chunk-ISKCTUI7.js → chunk-FHESRUJY.js} +1 -1
  21. package/dist/{chunk-BKNXRSJU.js → chunk-FYULPPFR.js} +1 -1
  22. package/dist/{chunk-27C637GL.js → chunk-H4MMEULK.js} +2 -2
  23. package/dist/chunk-HC34HJFF.js +1 -0
  24. package/dist/{chunk-XF7YHFVR.js → chunk-HJICGOD4.js} +1 -1
  25. package/dist/{chunk-F6U5TMM3.js → chunk-HXDS4NWI.js} +1 -1
  26. package/dist/{chunk-3BRHWRZ5.js → chunk-I44JKROJ.js} +1 -1
  27. package/dist/chunk-K2TZW4DU.js +132 -0
  28. package/dist/{chunk-RBJPQYV3.js → chunk-K4IE6DPX.js} +1 -1
  29. package/dist/{chunk-NPGZRSGL.js → chunk-LQVBWVLE.js} +1 -1
  30. package/dist/chunk-LVHLUAZW.js +22 -0
  31. package/dist/{chunk-ICAM2GUU.js → chunk-MNSZE3NV.js} +1 -1
  32. package/dist/{chunk-KJNAORKM.js → chunk-MTQI6B7T.js} +1 -1
  33. package/dist/chunk-NS6WVZMS.js +1 -0
  34. package/dist/{chunk-IRUR4DVD.js → chunk-OGY42NUN.js} +1 -1
  35. package/dist/{chunk-VLS3BPCG.js → chunk-OXGWWSKT.js} +1 -1
  36. package/dist/{chunk-OW3HDZV5.js → chunk-P5Q2UINT.js} +1 -1
  37. package/dist/{chunk-BPXS4QEO.js → chunk-QL2ZOLMC.js} +88 -21
  38. package/dist/{chunk-TZCMK3UG.js → chunk-R24YRJRG.js} +1 -1
  39. package/dist/{chunk-RX274IH7.js → chunk-SCUPWMI5.js} +1 -1
  40. package/dist/{chunk-J3VYLSJI.js → chunk-TCBGUVVU.js} +1 -1
  41. package/dist/{chunk-XIVFVKMB.js → chunk-TJTH7LHX.js} +1 -1
  42. package/dist/chunk-VVQ532U2.js +6 -0
  43. package/dist/chunk-WVHN54MA.js +14 -0
  44. package/dist/{chunk-LBINDAPE.js → chunk-YNS5LQX5.js} +1 -1
  45. package/dist/cli.js +2 -2
  46. package/dist/{config-XO7TGH27.js → config-HDAAV5FV.js} +1 -1
  47. package/dist/{db-WCTOLFAZ.js → db-HFBXO2O5.js} +1 -1
  48. package/dist/{delivery-log-ML4RJOBM.js → delivery-log-3O3OHKY4.js} +1 -1
  49. package/dist/engine-J43ECCH7.js +1 -0
  50. package/dist/{evolution-audit-HLU7LQL6.js → evolution-audit-BSGPFGFK.js} +1 -1
  51. package/dist/execution-tools-HHUPWLCF.js +1 -0
  52. package/dist/index.js +41 -41
  53. package/dist/{learner-NJXX2RUL.js → learner-TQQZKRSB.js} +1 -1
  54. package/dist/{memories-JDTQM3UN.js → memories-2DY5G6ZN.js} +1 -1
  55. package/dist/{memory-extractor-X2HTMKCV.js → memory-extractor-TUOOFST2.js} +1 -1
  56. package/dist/memory-gc-MRO53MEY.js +1 -0
  57. package/dist/memory-service-23WVAW7T.js +1 -0
  58. package/dist/outbound-gateway-VXODXSQR.js +1 -0
  59. package/dist/presets-KJV6SNNB.js +1 -0
  60. package/dist/{reflection-job-BHX3BWAG.js → reflection-job-EFFW3WOR.js} +1 -1
  61. package/dist/role-presets-PHHL3OEN.js +1 -0
  62. package/dist/role-workspace-USY47ZPQ.js +1 -0
  63. package/dist/{roles-F6AEM6B5.js → roles-3JXNHL7K.js} +1 -1
  64. package/dist/{session-manager-6MUWHQYF.js → session-manager-PI3JEINK.js} +1 -1
  65. package/dist/skill-registry-ROGU2WED.js +1 -0
  66. package/dist/{task-templates-6G46OVYT.js → task-templates-4YPKFFKG.js} +1 -1
  67. package/dist/template-dispatch-46TN534D.js +1 -0
  68. package/package.json +1 -1
  69. package/web/dist/assets/ArtifactDetail-9DJdEqCz.js +66 -0
  70. package/web/dist/assets/Artifacts-CQ6SAemH.js +1 -0
  71. package/web/dist/assets/{Button-fLMsJd5o.js → Button-xVc-P0vm.js} +1 -1
  72. package/web/dist/assets/{Card-cy-gHU0O.js → Card-WUD1cwG6.js} +1 -1
  73. package/web/dist/assets/ChannelDetail-B21nBQwi.js +1 -0
  74. package/web/dist/assets/{Channels-DMutLV9r.js → Channels-CAeGE1r7.js} +2 -2
  75. package/web/dist/assets/Chat-KpFWchPp.js +2 -0
  76. package/web/dist/assets/{Dashboard-CoatfhW8.js → Dashboard-DkRwHNmr.js} +1 -1
  77. package/web/dist/assets/{EmptyState-C5kVDHc7.js → EmptyState-BLB33cKG.js} +1 -1
  78. package/web/dist/assets/{EnvVarEditor-BvRsHayG.js → EnvVarEditor-BchUNrmz.js} +1 -1
  79. package/web/dist/assets/{EventDefDetail-zuJydp12.js → EventDefDetail-DnBwWWfT.js} +1 -1
  80. package/web/dist/assets/Events-ByIzPIs2.js +1 -0
  81. package/web/dist/assets/{Evolution-Br41g99g.js → Evolution-Vh9RKdma.js} +1 -1
  82. package/web/dist/assets/{ExtensionDetail-BXlphIkn.js → ExtensionDetail-0CtJh5rF.js} +1 -1
  83. package/web/dist/assets/Extensions--O1ulwlC.js +1 -0
  84. package/web/dist/assets/{FeatureRequests-oaXQNu43.js → FeatureRequests-XhQbGg_q.js} +1 -1
  85. package/web/dist/assets/GoalDetail-DIOxf7ES.js +1 -0
  86. package/web/dist/assets/Goals-CZnHu9qC.js +1 -0
  87. package/web/dist/assets/{Logs-BZKxhdnb.js → Logs-DdeG3GiY.js} +1 -1
  88. package/web/dist/assets/{Memories-DhJJk-KB.js → Memories-D-EAODUg.js} +1 -1
  89. package/web/dist/assets/{Mistakes-DxThj9as.js → Mistakes-wW78K3cP.js} +1 -1
  90. package/web/dist/assets/{NotFound-buXr2gl7.js → NotFound-BsxIP-Xm.js} +1 -1
  91. package/web/dist/assets/{PageHeader-BgNbz3JV.js → PageHeader-D8pqg_wk.js} +1 -1
  92. package/web/dist/assets/Plugins-DDUdX51_.js +1 -0
  93. package/web/dist/assets/{RoleDetail-rClUsHwS.js → RoleDetail-CU3G9j_q.js} +4 -4
  94. package/web/dist/assets/Roles-BCoSzDBg.js +1 -0
  95. package/web/dist/assets/{SectionHeader-CwX6m1f6.js → SectionHeader-DZo4QVWr.js} +1 -1
  96. package/web/dist/assets/{Settings-My2lOEWv.js → Settings-K3usfV-2.js} +1 -1
  97. package/web/dist/assets/{Strategies-YLMryJlG.js → Strategies-Bg4qlLei.js} +1 -1
  98. package/web/dist/assets/{Switch-PNpjNoGn.js → Switch-WWPXnSOG.js} +1 -1
  99. package/web/dist/assets/{Table-BrERwl-F.js → Table-XjSmrOyn.js} +1 -1
  100. package/web/dist/assets/{Tabs-CGHmpUAD.js → Tabs-CSbcG_5T.js} +1 -1
  101. package/web/dist/assets/TaskDetail-C5roukcV.js +2 -0
  102. package/web/dist/assets/Work-DGTWSgtc.js +1 -0
  103. package/web/dist/assets/{es2015-JqLIWAgH.js → es2015-BgPT8VkR.js} +1 -1
  104. package/web/dist/assets/index-KNUbHDLy.css +2 -0
  105. package/web/dist/assets/index-iD-HOtIu.js +12 -0
  106. package/web/dist/assets/{useIsMobileLayout-Blj4Mk4K.js → useIsMobileLayout-DF2fEEM9.js} +1 -1
  107. package/web/dist/assets/{usePluginsWithUsage-Ch9WCFTb.js → usePluginsWithUsage-CjU8Lkdn.js} +1 -1
  108. package/web/dist/assets/vendor-icons-H7p0EuQJ.js +1 -0
  109. package/web/dist/assets/{vendor-react-Bp_V-Hsf.js → vendor-react-C1yKjxEP.js} +1 -1
  110. package/web/dist/assets/{vendor-state-Zjl_6-V3.js → vendor-state-D0TNAbOY.js} +1 -1
  111. package/web/dist/index.html +7 -7
  112. package/dist/App-6TRGTNZ7.js +0 -13
  113. package/dist/approval-handler-ZWZZ3FKR.js +0 -1
  114. package/dist/audit-diagnostics-MASYIEGZ.js +0 -1
  115. package/dist/audit-manager-3YOVBIFV.js +0 -1
  116. package/dist/bree-engine-Y6WEQCC4.js +0 -1
  117. package/dist/channels-2DFKJ33W.js +0 -1
  118. package/dist/channels-2IL6USWL.js +0 -1
  119. package/dist/chunk-2Q6XLYCC.js +0 -25
  120. package/dist/chunk-CLNYHWZ6.js +0 -5
  121. package/dist/chunk-JUVQWLWM.js +0 -14
  122. package/dist/chunk-JYJWNUGH.js +0 -1
  123. package/dist/chunk-L47LZYVG.js +0 -21
  124. package/dist/chunk-VVPRB2JU.js +0 -114
  125. package/dist/engine-IZRMVJRH.js +0 -1
  126. package/dist/execution-tools-3UATAFUL.js +0 -1
  127. package/dist/memory-gc-BCHTOSXK.js +0 -1
  128. package/dist/memory-service-66EMRJXO.js +0 -1
  129. package/dist/outbound-gateway-R6EVRWHP.js +0 -1
  130. package/dist/presets-ZZVLCPB2.js +0 -1
  131. package/dist/role-presets-JJI7532O.js +0 -1
  132. package/dist/role-workspace-SIHNI6HO.js +0 -1
  133. package/dist/skill-registry-4JT62GEF.js +0 -1
  134. package/dist/template-dispatch-NDQH6S2P.js +0 -1
  135. package/dist/template-execution-artifacts-NEPSVD2B.js +0 -1
  136. package/web/dist/assets/ChannelDetail-CsKBPHkT.js +0 -1
  137. package/web/dist/assets/Chat-DWTs-iOw.js +0 -2
  138. package/web/dist/assets/Events-nCImjXyr.js +0 -1
  139. package/web/dist/assets/Extensions-3lhbw0A2.js +0 -1
  140. package/web/dist/assets/GoalDetail-DRDg1JDv.js +0 -1
  141. package/web/dist/assets/Goals-DGmKvtGA.js +0 -1
  142. package/web/dist/assets/Plugins-BXrsGsXs.js +0 -1
  143. package/web/dist/assets/Roles-DH9cRv8h.js +0 -1
  144. package/web/dist/assets/TaskDetail-Bkaq0NwW.js +0 -2
  145. package/web/dist/assets/Work-4OcGMu_a.js +0 -1
  146. package/web/dist/assets/index-C-e-qpXc.js +0 -12
  147. package/web/dist/assets/index-DGTVc0qD.css +0 -2
  148. package/web/dist/assets/vendor-icons-U4igmrUq.js +0 -1
  149. /package/web/dist/assets/{format-BUYXZqDw.js → format-ZWN4JNj-.js} +0 -0
  150. /package/web/dist/assets/{ui-CerQw0jA.js → ui-D1crlGpt.js} +0 -0
@@ -0,0 +1,14 @@
1
+ import{a as fo}from"./chunk-NS6WVZMS.js";import{b as S,d as $r,e as jo}from"./chunk-NLTYJUQG.js";import{a as Mr,f as Wo,h as Go}from"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";import{Box as Br,Text as lr,useInput as il}from"ink";import{useState as al,useEffect as io,useRef as Wt,useReducer as ll}from"react";import{createContext as Rs,useContext as Ds,useReducer as Ms}from"react";import{jsx as _s}from"react/jsx-runtime";var $s={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",selectedTaskId:null,configVersion:0,session:null,version:null};function Ns(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,selectedTaskId:t.selectedTaskId??e.selectedTaskId};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 Ko=Rs(null);function Ho({children:e}){let[t,r]=Ms(Ns,$s);return _s(Ko.Provider,{value:{state:t,dispatch:r},children:e})}function Ye(){let e=Ds(Ko);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as zo,useRef as Xo}from"react";var Ls=15e3;function Yo(){let{state:e,dispatch:t}=Ye(),r=Xo(null),a=Xo(null);zo(()=>{a.current=e.session?.id??null},[e.session?.id]),zo(()=>{let o=!0,u=null,d=()=>{r.current&&(clearTimeout(r.current),r.current=null)},l=()=>{d(),r.current=setTimeout(()=>{o&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Ls)};return(()=>{try{u=new $r("/events"),u.on("task_status_change",()=>{}),u.on("approval_request",n=>{if(!o)return;let p=n;t({type:"SET_PENDING_APPROVAL",approval:{taskId:p.taskId,approvalId:p.approvalId,toolName:p.toolName,toolInput:p.toolInput,matchedPattern:p.matchedPattern}})}),u.on("plan_approval_request",n=>{if(!o)return;let p=n;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:p.taskId,planId:p.planId,roleId:p.roleId,plan:p.plan}})}),u.on("plan_approval_decision",()=>{o&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),u.on("config_changed",()=>{o&&t({type:"CONFIG_CHANGED"})}),u.on("execution_task_start",n=>{if(!o)return;let p=n,g=a.current;g&&(async()=>{try{let v=await S(`/tasks/${p.taskId}`);o&&v.sourceSessionId===g&&t({type:"SET_ACTIVE_TASK",taskId:p.taskId})}catch{}})()}),u.on("stats_update",n=>{if(!o)return;let p=n;t({type:"UPDATE_STATS",activeTasks:p.activeTasks,queuedTasks:p.queuedTasks,costToday:p.totalCostToday})}),u.connect().then(async()=>{if(o){d(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let n=await S("/version");t({type:"SET_VERSION",version:n.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{o&&(t({type:"SET_CONNECTED",connected:!1}),l())})}catch{o&&(t({type:"SET_CONNECTED",connected:!1}),l())}})(),()=>{o=!1,d(),u?.close()}},[t])}import{useEffect as Fs,useRef as Os,useState as Qo,useCallback as qs}from"react";function Jo(e){let[t,r]=Qo([]),[a,o]=Qo(!1),u=Os(null),d=qs(()=>{r([]),o(!1)},[]);return Fs(()=>{if(!e)return;let l=!0;r([]),o(!0);try{let i=new jo(e);return u.current=i,i.on("reasoning",n=>{if(!l)return;let g=n.content??"";r(v=>{let b=v[v.length-1];if(b?.type==="reasoning"){let k=[...v];return k[k.length-1]={...b,content:b.content+g},k}return[...v,{type:"reasoning",content:g,timestamp:Date.now()}]})}),i.on("tool_call",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"tool_call",content:p.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:p.toolName}}])}),i.on("tool_result",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"tool_result",content:p.content??"",timestamp:Date.now()}])}),i.on("error",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"error",content:p.error??"unknown error",timestamp:Date.now()}])}),i.on("complete",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"complete",content:p.result??"",timestamp:Date.now(),metadata:{cost:p.costUsd,turns:p.numTurns,duration:p.totalDurationMs}}]),o(!1)}),i.connect().catch(()=>{l&&(r(n=>[...n,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),o(!1))}),()=>{l=!1,i.close()}}catch{o(!1)}},[e]),{events:t,isStreaming:a,clearEvents:d}}import{useState as go,useEffect as Vs,useCallback as mr}from"react";function po(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function Zo(){let[e,t]=go(null),[r,a]=go(!0),[o,u]=go(null),d=mr(async()=>{try{let v=(await S("/chat/sessions?status=active")).sessions.find(b=>b.source.type==="tui");return v?po(v):null}catch{return null}},[]),l=mr(async()=>{try{let g=await S("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),v=po(g.session);return t(v),v}catch{return u("Failed to create session"),null}},[]),i=mr(async g=>{try{let v=await S("/chat/messages",{method:"POST",body:{content:g,source:{type:"tui"}}});return t(b=>b&&{...b,messageCount:b.messageCount+1,lastActiveAt:Date.now()}),v}catch{return null}},[]),n=mr(async()=>{if(!e)return!1;try{return await S(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),p=mr(async()=>{if(e)try{let g=await S(`/chat/sessions/${e.id}`);t(po(g.session))}catch{t(null)}},[e]);return Vs(()=>{let g=!1;async function v(){a(!0);let b=await d();g||(b?t(b):await l(),g||a(!1))}return v(),()=>{g=!0}},[]),{session:e,loading:r,error:o,sendMessage:i,createNewSession:l,archiveCurrentSession:n,refreshSession:p,setSession:t}}import{useEffect as en,useRef as Us,useState as Ws}from"react";function tn(e){let[t,r]=Ws(null),a=Us(new Set);return en(()=>{if(!e)return;let o=!0,u=null;try{u=new $r("/chat/stream"),u.on("chat_message",d=>{if(!o)return;let i=d.message;i&&i.sessionId===e&&i.role==="assistant"&&(a.current.has(i.id)||(a.current.add(i.id),r(i)))}),u.connect().catch(()=>{})}catch{}return()=>{o=!1,u?.close()}},[e]),en(()=>{a.current.clear(),r(null)},[e]),{latestMessage:t}}import{Box as xo,Text as Oe}from"ink";import{Fragment as Nr,jsx as Be,jsxs as zt}from"react/jsx-runtime";var Gs=90;function rn({children:e}){return Be(xo,{children:e})}function on(){let{state:e}=Ye(),t=e.session,a=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,o=e.connected?"up":"down",u=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),d=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,i=(process.stdout.columns??100)<Gs,n=zt(Nr,{children:[Be(Oe,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),Be(Oe,{dimColor:!0,children:" | "}),Be(Oe,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),Be(Oe,{children:` ${o}`}),Be(Oe,{dimColor:!0,children:" | "}),Be(Oe,{children:u.toLowerCase()})]}),p=zt(Nr,{children:[Be(Oe,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),Be(Oe,{dimColor:!0,children:" | "}),Be(Oe,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&zt(Nr,{children:[Be(Oe,{dimColor:!0,children:" | "}),Be(Oe,{children:d}),a&&zt(Nr,{children:[Be(Oe,{dimColor:!0,children:" | "}),Be(Oe,{color:"yellow",children:"timeout"})]})]})]});return i?zt(xo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[Be(rn,{children:n}),Be(rn,{children:p})]}):zt(xo,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[n,Be(Oe,{dimColor:!0,children:" | "}),p]})}import{Box as _r,Text as Lr,useInput as Ks}from"ink";import{useState as ho,useMemo as Hs}from"react";import zs from"ink-text-input";var js=[{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:"artifacts",description:"Browse artifacts across tasks"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function To(e){let t=e.toLowerCase();return js.filter(r=>r.name.startsWith(t))}function nn(e){let t=To(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Fr,jsxs as fr}from"react/jsx-runtime";function sn({onSubmit:e}){let[t,r]=ho(""),[a,o]=ho(0),[u,d]=ho(!1),l=t.startsWith("/")&&t.length>=1,i=t.slice(1),n=Hs(()=>l?To(i):[],[l,i]),p=b=>{r(b),b.startsWith("/")?(d(!0),o(0)):d(!1)},g=()=>{let b=t.trim();if(b){if(b.startsWith("/")){let k=b.slice(1),s=nn(k);e(s?`/${s.name}`:b)}else e(b);r(""),d(!1)}},v=b=>{e(`/${b.name}`),r(""),d(!1)};return Ks((b,k)=>{if(!(!u||!l||n.length===0)){if(k.upArrow){o(s=>s<=0?n.length-1:s-1);return}if(k.downArrow){o(s=>s>=n.length-1?0:s+1);return}if(k.tab){let s=n[a];s&&v(s);return}if(k.escape){d(!1),r("");return}}},{isActive:u&&l&&n.length>0}),fr(_r,{flexDirection:"column",children:[u&&l&&n.length>0&&Fr(_r,{flexDirection:"column",marginBottom:0,paddingX:1,children:n.map((b,k)=>{let s=k===a;return fr(_r,{children:[Fr(Lr,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),fr(Lr,{color:s?"cyan":"white",bold:s,children:["/",b.name]}),fr(Lr,{dimColor:!0,children:[" \u2014 ",b.description]})]},b.name)})}),fr(_r,{borderStyle:"round",borderDimColor:!0,children:[Fr(Lr,{bold:!0,children:"\u25B8 "}),Fr(zs,{value:t,onChange:p,onSubmit:g,placeholder:"Type a message or / for commands..."})]})]})}import{Box as Xt,Text as $e,useInput as Xs}from"ink";import{useState as Ys}from"react";import{jsx as Ge,jsxs as dt}from"react/jsx-runtime";function Qs({content:e,expanded:t}){let r=e.split(`
2
+ `);return r.length<=5?Ge($e,{color:"green",children:e}):t?Ge($e,{color:"green",children:e}):dt($e,{color:"green",children:[r.slice(0,3).join(`
3
+ `),`
4
+ `,dt($e,{dimColor:!0,children:["(",r.length," lines) [Ctrl+O] expand"]})]})}function Js({event:e,expanded:t}){switch(e.type){case"reasoning":return Ge(Xt,{children:Ge($e,{color:"gray",children:e.content})});case"tool_call":return Ge(Xt,{children:dt($e,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return dt(Xt,{flexDirection:"column",children:[Ge($e,{color:"blue",dimColor:!0,children:"[result]"}),Ge(Qs,{content:e.content,expanded:t})]});case"error":return Ge(Xt,{children:dt($e,{color:"red",children:["[error] ",e.content]})});case"complete":return dt(Xt,{flexDirection:"column",marginTop:1,children:[e.content&&Ge($e,{children:e.content}),Ge($e,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&dt($e,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&dt($e,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&dt($e,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function an({events:e,isStreaming:t}){let[r,a]=Ys(!1),o=e.some(u=>u.type==="tool_result"&&u.content.split(`
5
+ `).length>5);return Xs((u,d)=>{d.ctrl&&u==="o"&&a(l=>!l)},{isActive:o}),e.length===0&&!t?null:dt(Xt,{flexDirection:"column",children:[t&&e.length===0&&Ge($e,{dimColor:!0,children:"Waiting for response..."}),e.map((u,d)=>Ge(Js,{event:u,expanded:r},d)),o&&Ge($e,{dimColor:!0,children:r?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as bn,Text as jr}from"ink";import{Box as Zs,Text as Or}from"ink";import ei from"ink-spinner";import{jsx as qr,jsxs as ln}from"react/jsx-runtime";var ti={running:{glyph:"",color:"blue"},completed:{glyph:"\u2713",color:"green"},failed:{glyph:"\u2717",color:"red"},retrying:{glyph:"\u21BB",color:"yellow"},blocked:{glyph:"\u23F8",color:"yellow"}};function cn({content:e,phase:t,taskShortId:r}){let a=ti[t];return ln(Zs,{children:[qr(Or,{color:a.color,children:t==="running"?qr(ei,{type:"dots"}):a.glyph}),qr(Or,{children:" "}),r&&ln(Or,{dimColor:!0,children:["[",r,"] "]}),qr(Or,{dimColor:!0,children:e})]})}import{Box as gr,Text as Wr}from"ink";var dn=["cyan","magenta","green","yellow","blue","red"];function ri(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r);return Math.abs(t)}function Vr(e){return e?dn[ri(e)%dn.length]:"cyan"}function Ur(e){return e?`T-${e.replace(/-/g,"").slice(0,8).toUpperCase()}`:""}import{jsx as pr,jsxs as Gr}from"react/jsx-runtime";function oi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function ni(e){if(!e)return"";let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function si(e){return e.map(t=>{if(t.type==="channel"&&t.channelId)return t.channelId;if(t.type==="webhook"&&t.webhookUrl)try{return new URL(t.webhookUrl).hostname}catch{return t.webhookUrl}return t.type}).join(", ")}function un(e){let t=Vr(e.roleId),r=e.roleName??"?",a=e.taskShortIdLabel?` \xB7 ${e.taskShortIdLabel}`:"";return Gr(gr,{flexDirection:"column",borderStyle:"round",borderColor:t,paddingX:1,children:[pr(gr,{children:Gr(Wr,{bold:!0,color:t,children:["[",r,a,"]"]})}),pr(gr,{marginTop:1,children:pr(Wr,{children:e.content})}),e.attachments&&e.attachments.length>0&&pr(gr,{flexDirection:"column",marginTop:1,children:e.attachments.map(o=>{let u=o.purpose?`purpose=${o.purpose}, `:"";return Gr(Wr,{dimColor:!0,children:["[file] ",o.filename," (",u,oi(o.size),") \u2192 ",o.locator]},o.artifactId)})}),e.mirroredToTargets&&e.mirroredToTargets.length>0&&pr(gr,{marginTop:1,children:Gr(Wr,{dimColor:!0,italic:!0,children:["(also delivered to: ",si(e.mirroredToTargets)," @ ",ni(e.createdAt),")"]})})]})}import{Box as Nt,Text as Yt}from"ink";import ii from"ink-select-input";import{useState as mn}from"react";import{jsx as ht,jsxs as xr}from"react/jsx-runtime";var ai=[{label:"\u6279\u51C6 / Yes",value:"\u6279\u51C6"},{label:"\u62D2\u7EDD / No",value:"\u62D2\u7EDD"}];function fn({promptId:e,content:t,shape:r,choices:a,onSubmitted:o,onSubmitFailure:u}){let[d,l]=mn(null),[i,n]=mn(null),p=r==="yes_no"?ai:r==="choose_one"&&a&&a.length>0?a.map(v=>({label:v,value:v})):[],g=async v=>{try{await S("/chat/messages",{method:"POST",body:{content:v.value,source:{type:"tui"},buttonPayload:{promptId:e,value:v.value}}}),l(v.value),o?.(v.value)}catch{n(`Failed to submit. Try again or type "#${e} ${v.value}" in the input bar.`),u?.()}};return xr(Nt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[xr(Yt,{bold:!0,color:"yellow",children:["\u26A0 #",e]}),ht(Nt,{marginTop:1,children:ht(Yt,{children:t})}),d?ht(Nt,{marginTop:1,children:xr(Yt,{color:"green",children:["[\u5DF2\u63D0\u4EA4: ",d," \u2713]"]})}):r==="free_input"?ht(Nt,{marginTop:1,children:xr(Yt,{dimColor:!0,children:["Free-input shape: \u8BF7\u56DE\u590D #",e," \u4F60\u7684\u7B54\u590D"]})}):p.length>0?ht(Nt,{marginTop:1,children:ht(ii,{items:p,onSelect:g})}):ht(Nt,{marginTop:1,children:xr(Yt,{color:"red",dimColor:!0,children:["(no choices configured for shape=",r,")"]})}),i&&ht(Nt,{marginTop:1,children:ht(Yt,{color:"red",children:i})})]})}import{Box as li,Text as ci}from"ink";import{jsx as ui,jsxs as di}from"react/jsx-runtime";function gn({content:e}){return ui(li,{children:di(ci,{dimColor:!0,children:["\xB7 ",e]})})}import{Box as yo,Text as mi}from"ink";import{jsx as xn,jsxs as pn}from"react/jsx-runtime";function Tn({threadRoot:e,roleId:t,roleName:r,taskShortIdLabel:a,brief:o,children:u}){let d=Vr(t),l=[a,r,o].filter(Boolean),i=l.length>0?l.join(" / "):e.slice(0,8);return pn(yo,{flexDirection:"column",borderStyle:"round",borderColor:d,paddingX:1,marginBottom:1,children:[xn(yo,{children:pn(mi,{bold:!0,color:d,children:["[Thread ",i,"]"]})}),xn(yo,{flexDirection:"column",marginTop:1,children:u})]})}import{useEffect as fi,useState as hn}from"react";function yn(){let[e,t]=hn(new Map),[r,a]=hn(!1);return fi(()=>{let o=!1;async function u(){try{let d=await S("/roles");if(o)return;let l=new Map;for(let i of d.roles)l.set(i.id,i.name);t(l)}catch{}finally{o||a(!0)}}return u(),()=>{o=!0}},[]),{getName:o=>o&&e.get(o)||"?",loaded:r}}import{jsx as Et,jsxs as bo}from"react/jsx-runtime";function gi(e){let t=e.toLowerCase();return t.includes("completed")||t.includes("done")||t.includes("\u6210\u529F")?"completed":t.includes("failed")||t.includes("error")||t.includes("\u5931\u8D25")?"failed":t.includes("retry")||t.includes("\u91CD\u8BD5")?"retrying":t.includes("blocked")||t.includes("auth_required")||t.includes("\u963B\u585E")?"blocked":"running"}function pi(e,t,r){return function(o,u){if(!o.kind||o.kind==="user_message"||o.kind==="assistant_text")return bo(bn,{flexDirection:"column",marginBottom:1,children:[Et(jr,{dimColor:!0,bold:!0,children:o.role==="user"?"You:":"Adam:"}),Et(jr,{children:o.content})]},u);if(o.kind==="status_report")return Et(cn,{content:o.content,phase:gi(o.content),taskShortId:Ur(o.taskId)},u);if(o.kind==="result_delivery")return Et(un,{content:o.content,roleId:o.roleId,roleName:e(o.roleId),taskShortIdLabel:Ur(o.taskId),attachments:o.attachments,mirroredToTargets:o.mirroredToTargets,createdAt:o.createdAt},u);if(o.kind==="approval_prompt"&&o.promptId&&o.approvalShape){let d=o.promptId;return Et(fn,{promptId:d,content:o.content,shape:o.approvalShape,onSubmitted:()=>t?.(d),onSubmitFailure:()=>r?.(d)},u)}return o.kind==="system_note"?Et(gn,{content:o.content},u):Et(jr,{dimColor:!0,children:o.content},u)}}function xi(e){let t=[],r=0;for(;r<e.length;){let a=e[r];if(a.kind==="status_report"){let o=r;for(;o<e.length&&e[o].kind==="status_report";)o++;let u=o-r;if(u>=3){t.push({__synthetic:!0,count:u,lastContent:e[o-1].content}),r=o;continue}}t.push(a),r++}return t}function vn({messages:e,onApprovalSubmitted:t,onApprovalFailed:r}){let{getName:a}=yn(),o=pi(a,t,r);if(e.length===0)return null;let u=[],d=new Map;for(let l of e)if(!l.threadRoot)u.push(l);else{let i=d.get(l.threadRoot)??[];i.push(l),d.set(l.threadRoot,i)}return bo(bn,{flexDirection:"column",children:[u.map((l,i)=>o(l,`free-${l.id??i}`)),Array.from(d.entries()).map(([l,i])=>{let n=i[0],p=xi(i);return Et(Tn,{threadRoot:l,roleId:n.roleId,roleName:a(n.roleId),taskShortIdLabel:Ur(n.taskId),brief:n.content.slice(0,30),children:p.map((g,v)=>"__synthetic"in g?bo(jr,{dimColor:!0,children:["\u2026 ",g.count," \u6761\u8FDB\u5C55\uFF08\u6700\u8FD1: ",g.lastContent.slice(0,40),"\uFF09"]},`compressed-${v}`):o(g,`${l}-${g.id??v}`))},`thread-${l}`)})]})}import{Box as Tr,Text as ut,useInput as Ti}from"ink";import{jsx as mt,jsxs as hr}from"react/jsx-runtime";function Cn({approval:e,onResolved:t}){return Ti(r=>{r==="a"?S(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):r==="r"&&S(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),hr(Tr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[mt(ut,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),hr(Tr,{marginTop:1,children:[mt(ut,{children:"Tool: "}),mt(ut,{bold:!0,children:e.toolName})]}),hr(Tr,{children:[mt(ut,{children:"Input: "}),mt(ut,{children:JSON.stringify(e.toolInput)})]}),hr(Tr,{children:[mt(ut,{children:"Pattern: "}),mt(ut,{dimColor:!0,children:e.matchedPattern})]}),hr(Tr,{marginTop:1,children:[mt(ut,{color:"green",children:"[a] Approve"}),mt(ut,{children:" "}),mt(ut,{color:"red",children:"[r] Reject"})]})]})}import{Box as yr,Text as Ne,useInput as hi}from"ink";import{useState as yi,useEffect as bi}from"react";import{jsx as yt,jsxs as ot}from"react/jsx-runtime";var vi=300;function Sn({approval:e,onResolved:t,onTimeout:r}){let[a,o]=yi(vi);bi(()=>{let d=setInterval(()=>{o(l=>l<=1?(clearInterval(d),r(),0):l-1)},1e3);return()=>clearInterval(d)},[r]),hi(d=>{d==="a"?S(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):d==="r"?S(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):d==="p"&&S(`/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 ot(yr,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[yt(Ne,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),ot(Ne,{dimColor:!0,children:["Plan ID: ",e.planId]}),ot(Ne,{dimColor:!0,children:["Time remaining: ",a,"s"]}),ot(yr,{marginTop:1,children:[yt(Ne,{children:"Overall Risk: "}),yt(Ne,{bold:!0,color:u,children:e.plan.overallRisk.toUpperCase()})]}),ot(Ne,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(d=>{let l=d.riskLevel==="high"?"red":d.riskLevel==="medium"?"yellow":"green";return ot(yr,{paddingLeft:2,children:[ot(Ne,{children:["[",d.index,"] "]}),yt(Ne,{children:d.description}),ot(Ne,{dimColor:!0,children:[" (",d.toolsNeeded.join(", "),")"]}),ot(Ne,{color:l,children:[" [",d.riskLevel,"]"]})]},d.index)}),ot(yr,{marginTop:1,children:[yt(Ne,{dimColor:!0,children:"Permissions: "}),yt(Ne,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),ot(yr,{marginTop:1,children:[yt(Ne,{color:"green",children:"[a] Allow once "}),yt(Ne,{color:"green",children:"[p] Allow permanent "}),yt(Ne,{color:"red",children:"[r] Deny"})]})]})}import{Box as Ie,Text as ee,useInput as Pi}from"ink";import{useEffect as Ri,useState as At,useCallback as An}from"react";import{Box as Se,Text as j,useInput as Ci}from"ink";import{useEffect as Si,useState as Qt}from"react";import{jsx as me,jsxs as Y}from"react/jsx-runtime";var wn={plan:!0,result:!1,routing:!0,error:!0},wi={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function En({taskId:e,onBack:t}){let[r,a]=Qt(null),[o,u]=Qt([]),[d,l]=Qt([]),[i,n]=Qt(null),[p,g]=Qt(wn),[v,b]=Qt(!1);Si(()=>{let C=!1;return a(null),u([]),l([]),n(null),g(wn),b(!1),S(`/tasks/${e}`).then(({task:A})=>{C||a(A)}).catch(A=>{C||n(A instanceof Error?A.message:String(A))}),S(`/tasks/${e}/plan`).then(({plans:A})=>{C||u(A)}).catch(()=>{C||u([])}),S(`/tasks/${e}/delivery-log?limit=8`).then(({logs:A})=>{C||l(A)}).catch(()=>{C||l([])}),()=>{C=!0}},[e]);let k=C=>{g(A=>({...A,[C]:!A[C]}))};if(Ci((C,A)=>{if(C==="b"||A.escape){t();return}C==="1"&&k("plan"),C==="2"&&k("result"),C==="3"&&k("routing"),C==="4"&&k("error"),C==="5"&&b(W=>!W)}),i)return Y(Se,{flexDirection:"column",children:[Y(j,{color:"red",children:["Task detail failed: ",i]}),me(j,{dimColor:!0,children:"[b] Back"})]});if(!r)return Y(j,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let s=o[0],c=Ei(r.deliverTo,r.reportTo),E=d.length>0?`${d.length} delivery event${d.length===1?"":"s"}`:"No delivery events";return Y(Se,{flexDirection:"column",children:[Y(Se,{children:[Y(j,{bold:!0,color:"cyan",children:["Task ",r.id.slice(0,8)]}),me(j,{dimColor:!0,children:" \u2022 "}),me(j,{color:wi[r.status]??"white",bold:!0,children:r.status.toUpperCase()})]}),Y(j,{dimColor:!0,children:[r.roleId?`role ${r.roleId}`:"no role"," \u2022 ",In(r.createdAt)," \u2022 ",Ii(r.totalDurationMs)]}),Y(Se,{marginTop:1,flexDirection:"column",children:[me(j,{bold:!0,children:"Summary"}),me(j,{children:v?r.prompt:ki(r.prompt,240)}),r.prompt.length>240&&Y(j,{dimColor:!0,children:["[5] ",v?"collapse prompt":"expand prompt"]}),Y(Se,{marginTop:1,flexDirection:"column",children:[Y(j,{dimColor:!0,children:["Cost: ",Bi(r.costUsd)]}),Y(j,{dimColor:!0,children:["Turns: ",r.numTurns??"\u2014"]}),Y(j,{dimColor:!0,children:["Template: ",r.templateId??"\u2014"]}),Y(j,{dimColor:!0,children:["Source Session: ",r.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),Y(Se,{marginTop:1,flexDirection:"column",children:[Y(j,{bold:!0,children:["[1] Plan ",p.plan?"hide":"show"]}),me(j,{dimColor:!0,children:s?`${s.plan.steps.length} planned step${s.plan.steps.length===1?"":"s"} \u2022 ${s.plan.overallRisk} risk \u2022 ${s.status}`:"No execution plan"}),p.plan&&s&&Y(Se,{marginTop:1,flexDirection:"column",children:[s.plan.steps.map(C=>Y(Se,{flexDirection:"column",marginBottom:1,children:[Y(j,{children:[C.index,". ",C.description]}),Y(j,{dimColor:!0,children:[C.riskLevel," risk \u2022 ",C.toolsNeeded.join(", ")||"no tools listed"]}),C.expectedOutput?Y(j,{dimColor:!0,children:["Expected: ",C.expectedOutput]}):null]},C.index)),s.learnedRules&&s.learnedRules.length>0&&Y(Se,{flexDirection:"column",children:[me(j,{color:"blue",bold:!0,children:"Learned Rules"}),s.learnedRules.map((C,A)=>Y(j,{dimColor:!0,children:["\u2022 ",C]},A))]})]})]}),Y(Se,{marginTop:1,flexDirection:"column",children:[Y(j,{bold:!0,children:["[2] Result ",p.result?"hide":"show"]}),me(j,{dimColor:!0,children:r.result?"Execution produced output.":"No result captured yet."}),p.result&&me(Se,{marginTop:1,children:me(j,{children:r.result?Bn(r.result,18):"No result yet."})})]}),Y(Se,{marginTop:1,flexDirection:"column",children:[Y(j,{bold:!0,children:["[3] Routing ",p.routing?"hide":"show"]}),Y(j,{dimColor:!0,children:[c," \u2022 ",E]}),p.routing&&Y(Se,{marginTop:1,flexDirection:"column",children:[me(j,{color:"cyan",children:"Deliver To"}),kn(r.deliverTo),me(j,{color:"cyan",children:"Report To"}),kn(r.reportTo),d.length>0&&Y(Se,{marginTop:1,flexDirection:"column",children:[me(j,{color:"cyan",children:"Recent Delivery"}),d.map(C=>Y(j,{dimColor:!0,children:[C.status," \u2022 ",Ai(C)," \u2022 ",In(C.createdAt)]},C.id))]})]})]}),Y(Se,{marginTop:1,flexDirection:"column",children:[Y(j,{bold:!0,children:["[4] Error ",p.error?"hide":"show"]}),me(j,{dimColor:!0,children:r.error?"Execution returned an error condition.":"No error recorded."}),p.error&&r.error&&me(Se,{marginTop:1,children:me(j,{color:"red",children:Bn(r.error,16)})})]}),me(Se,{marginTop:1,children:me(j,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function kn(e){return!e||e.length===0?me(j,{dimColor:!0,children:" none"}):me(Se,{flexDirection:"column",children:e.map((t,r)=>me(j,{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}-${r}`))})}function Bn(e,t){let r=e.split(`
6
+ `);return r.length<=t?e:`${r.slice(0,t).join(`
7
+ `)}
8
+ \u2026`}function ki(e,t){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}\u2026`}function Bi(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Ii(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60),a=t%60;return a===0?`${r}m`:`${r}m ${a}s`}function In(e){return new Date(e).toLocaleString()}function Ei(e,t){let r=e?.length??0,a=t?.length??0;return r===0&&a===0?"No delivery targets":`${r} output target${r===1?"":"s"} \u2022 ${a} report target${a===1?"":"s"}`}function Ai(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 Mi,jsx as le,jsxs as ce}from"react/jsx-runtime";var Pn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},Kr=["all","pending","queued","running","completed","failed","cancelled","blocked"],vo=15;function zr({onBack:e}){let[t,r]=At([]),[a,o]=At(!0),[u,d]=At("list"),[l,i]=At(0),[n,p]=At("all"),[g,v]=At(0),[b,k]=At(0),[s,c]=At(null),E=An(async()=>{o(!0);try{let N=new URLSearchParams({limit:"100"});n!=="all"&&N.set("status",n);let F=await S(`/tasks?${N}`);r(F.tasks)}catch{r([])}finally{o(!1)}},[n]);Ri(()=>{E()},[E]);let C=Math.max(1,Math.ceil(t.length/vo)),A=t.slice(b*vo,(b+1)*vo),W=An(async()=>{let N=A[l];if(N)try{await S(`/tasks/${N.id}/cancel`,{method:"POST"}),c(`Cancelled: ${N.id.slice(0,8)}`),d("list"),E()}catch(F){c(`Failed: ${F instanceof Error?F.message:String(F)}`),d("list")}},[A,l,E]);if(Pi((N,F)=>{if(u==="detail"){(F.escape||F.return||N==="q")&&d("list");return}if(u==="cancelling"){N==="y"?W():d("list");return}if(u==="filter"){if(F.escape){d("list");return}F.upArrow&&g>0&&v(q=>q-1),F.downArrow&&g<Kr.length-1&&v(q=>q+1),F.return&&(p(Kr[g]),k(0),i(0),d("list"));return}if(F.escape||N==="q"){e();return}if(F.upArrow&&l>0&&i(q=>q-1),F.downArrow&&l<A.length-1&&i(q=>q+1),F.return&&A[l]&&d("detail"),N==="x"&&A[l]){let q=A[l];["running","pending","queued","paused"].includes(q.status)?(d("cancelling"),c(null)):c(`Cannot cancel task in status: ${q.status}`)}N==="f"&&(v(Kr.indexOf(n)),d("filter")),N==="r"&&E(),(F.pageDown||N==="n")&&b<C-1&&(k(q=>q+1),i(0)),(F.pageUp||N==="p")&&b>0&&(k(q=>q-1),i(0))}),a)return le(ee,{dimColor:!0,children:"Loading tasks..."});if(u==="filter")return ce(Ie,{flexDirection:"column",children:[le(ee,{bold:!0,children:"Filter by status:"}),Kr.map((N,F)=>le(Ie,{children:ce(ee,{color:F===g?"cyan":"white",children:[F===g?"> ":" ",N,N===n?" (current)":""]})},N)),le(ee,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(u==="detail"&&A[l])return le(En,{taskId:A[l].id,onBack:()=>d("list")});if(u==="cancelling"&&A[l])return ce(Ie,{flexDirection:"column",children:[ce(ee,{color:"red",children:['Cancel task "',A[l].id.slice(0,8),'"? (y/n)']}),s&&le(ee,{color:"red",children:s})]});let X=A[l]??null;return ce(Ie,{flexDirection:"column",children:[ce(Ie,{children:[ce(ee,{bold:!0,children:["Tasks (",t.length,")"]}),n!=="all"&&ce(ee,{dimColor:!0,children:[" [filter: ",n,"]"]}),ce(ee,{dimColor:!0,children:[" \u2022 Page ",b+1,"/",C]})]}),s&&le(ee,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?ce(ee,{dimColor:!0,children:["No tasks found",n!=="all"?` with status "${n}"`:"","."]}):ce(Ie,{marginTop:1,flexDirection:"row",gap:2,children:[le(Ie,{flexDirection:"column",flexGrow:3,children:A.map((N,F)=>{let q=F===l,I=Pn[N.status]??"white";return ce(Ie,{flexDirection:"column",marginBottom:1,children:[ce(Ie,{children:[le(ee,{color:q?"cyan":"gray",bold:q,children:q?"\u276F ":" "}),le(ee,{color:I,bold:!0,children:N.status.toUpperCase()}),le(ee,{dimColor:!0,children:` ${N.id.slice(0,8)}`})]}),le(Ie,{paddingLeft:2,children:le(ee,{color:q?"white":void 0,children:Hr(N.prompt,q?72:56)})}),le(Ie,{paddingLeft:2,children:ce(ee,{dimColor:!0,children:[Mn(N.createdAt)," \u2022 ",Rn(N)," \u2022 ",Dn(N.costUsd)]})})]},N.id)})}),le(Ie,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:X?ce(Mi,{children:[le(ee,{bold:!0,children:"Preview"}),ce(Ie,{marginTop:1,children:[le(ee,{color:Pn[X.status]??"white",bold:!0,children:X.status.toUpperCase()}),le(ee,{dimColor:!0,children:` ${X.id.slice(0,8)}`})]}),le(ee,{children:Hr(X.prompt,220)}),ce(Ie,{marginTop:1,flexDirection:"column",children:[ce(ee,{dimColor:!0,children:["Role: ",X.roleId??X.agentId??"\u2014"]}),ce(ee,{dimColor:!0,children:["Created: ",Mn(X.createdAt)]}),ce(ee,{dimColor:!0,children:["Duration: ",Rn(X)]}),ce(ee,{dimColor:!0,children:["Cost: ",Dn(X.costUsd)]}),ce(ee,{dimColor:!0,children:["Turns: ",X.numTurns??"\u2014"]})]}),X.error?ce(Ie,{marginTop:1,flexDirection:"column",children:[le(ee,{color:"red",bold:!0,children:"Error"}),le(ee,{color:"red",children:Hr(X.error,180)})]}):X.result?ce(Ie,{marginTop:1,flexDirection:"column",children:[le(ee,{color:"green",bold:!0,children:"Latest Result"}),le(ee,{children:Hr(X.result,180)})]}):null,le(Ie,{marginTop:1,children:le(ee,{dimColor:!0,children:"Enter opens full detail"})})]}):le(ee,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Di(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function Hr(e,t){return Di(e.replace(/\s+/g," ").trim(),t)}function Rn(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let r=Math.max(1,Math.round(t/1e3));if(r<60)return`${r}s`;let a=Math.floor(r/60),o=r%60;return o===0?`${a}m`:`${a}m ${o}s`}function Dn(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function Mn(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let r=Math.floor(t/60);if(r<60)return`${r}m ago`;let a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}Go();import{Box as _t,Text as qe,useInput as $i}from"ink";import{useEffect as Ni,useState as $n}from"react";import{readFileSync as _i,existsSync as Li}from"fs";import{parse as Fi}from"yaml";import{Fragment as qi,jsx as _e,jsxs as je}from"react/jsx-runtime";function Nn({onBack:e}){let[t,r]=$n(null),[a,o]=$n(null);return $i((u,d)=>{(d.escape||u==="q")&&e()}),Ni(()=>{try{let u=Wo;if(!Li(u)){o(`Config file not found: ${u}`);return}let d=_i(u,"utf-8");r(Fi(d))}catch(u){o(u.message)}},[]),a?je(_t,{flexDirection:"column",children:[_e(qe,{color:"red",children:a}),_e(qe,{dimColor:!0,children:"Press Esc to go back"})]}):t?je(_t,{flexDirection:"column",children:[_e(qe,{bold:!0,children:"Configuration (Esc to go back)"}),_e(_t,{marginTop:1,flexDirection:"column",children:_e(Co,{obj:t,indent:0})})]}):_e(qe,{dimColor:!0,children:"Loading config..."})}function Co({obj:e,indent:t}){let r=" ".repeat(t);return _e(qi,{children:Object.entries(e).map(([a,o])=>_e(Oi,{label:a,value:o,indent:t,parentKey:a},a))})}function Oi({label:e,value:t,indent:r,parentKey:a}){let o=" ".repeat(r);return Array.isArray(t)?je(_t,{flexDirection:"column",children:[je(qe,{children:[o,_e(qe,{color:"cyan",children:e}),":"]}),t.length===0?je(qe,{dimColor:!0,children:[o," []"]}):t.map((u,d)=>_e(_n,{value:u,indent:r+1,parentKey:a,index:d},`${e}-${d}`))]}):t&&typeof t=="object"?je(_t,{flexDirection:"column",children:[je(qe,{children:[o,_e(qe,{color:"cyan",children:e}),":"]}),_e(Co,{obj:t,indent:r+1})]}):je(qe,{children:[o,_e(qe,{color:"cyan",children:e}),": ",Ln(a,Fn(t))]})}function _n({value:e,indent:t,parentKey:r,index:a}){let o=" ".repeat(t);return Array.isArray(e)?je(_t,{flexDirection:"column",children:[je(qe,{children:[o,"- [",a,"]"]}),e.map((u,d)=>_e(_n,{value:u,indent:t+1,parentKey:r,index:d},`${a}-${d}`))]}):e&&typeof e=="object"?je(_t,{flexDirection:"column",children:[je(qe,{children:[o,"-"]}),_e(Co,{obj:e,indent:t+1})]}):je(qe,{children:[o,"- ",Ln(r,Fn(e))]})}function Ln(e,t){let r=e.toLowerCase();return r.includes("key")||r.includes("token")||r.includes("secret")||r.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function Fn(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as Xr,Text as nt,useInput as Vi}from"ink";import{useEffect as Ui,useState as So}from"react";import{jsx as br,jsxs as ft}from"react/jsx-runtime";function On({onBack:e}){let[t,r]=So([]),[a,o]=So(!0),[u,d]=So(null);return Vi((l,i)=>{(i.escape||l==="q")&&e()}),Ui(()=>{S("/evolution-audit?limit=20").then(l=>{r(l),o(!1)}).catch(l=>{d(l.message),o(!1)})},[]),a?br(nt,{dimColor:!0,children:"Loading evolution log..."}):u?ft(Xr,{flexDirection:"column",children:[br(nt,{color:"red",children:u}),br(nt,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?ft(Xr,{flexDirection:"column",children:[br(nt,{dimColor:!0,children:"No evolution records yet"}),br(nt,{dimColor:!0,children:"Press Esc to go back"})]}):ft(Xr,{flexDirection:"column",children:[ft(nt,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(l=>ft(Xr,{flexDirection:"column",marginTop:1,children:[ft(nt,{bold:!0,children:["[",new Date(l.timestamp).toLocaleString(),"]"]}),l.triggerTaskId&&ft(nt,{dimColor:!0,children:[" Task: ",l.triggerTaskId.slice(0,8)]}),l.diff.split(`
9
+ `).map((i,n)=>i.startsWith("+")?ft(nt,{color:"green",children:[" ",i]},n):i.startsWith("-")?ft(nt,{color:"red",children:[" ",i]},n):ft(nt,{dimColor:!0,children:[" ",i]},n))]},l.id))]})}import{Box as bt,Text as fe,useInput as Wi}from"ink";import Gi from"ink-text-input";import{useEffect as ji,useState as Jt}from"react";import{jsx as Ve,jsxs as Ee}from"react/jsx-runtime";var Ki={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Hi(e,t=20){let r=Math.round(e*t),a=t-r;return"\u2588".repeat(r)+"\u2591".repeat(a)}function zi(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Yr({onBack:e}){let[t,r]=Jt([]),[a,o]=Jt(null),[u,d]=Jt("list"),[l,i]=Jt(""),[n,p]=Jt(!1),[g,v]=Jt(null);Wi((s,c)=>{if(u==="create"){c.escape&&(d("list"),i(""),v(null));return}(c.escape||s==="q")&&e(),s==="c"&&(d("create"),v(null)),s==="r"&&b()});let b=()=>{S("/goals?limit=20").then(({goals:s})=>r(s)).catch(s=>o(s.message))};ji(()=>{b()},[]);let k=async s=>{if(s.trim()){p(!0),v(null);try{let c=await S("/goals",{method:"POST",body:{input:s.trim()}});v(`Goal created: ${c.goal.name}`),i(""),d("list"),b()}catch(c){v(`Failed: ${c instanceof Error?c.message:String(c)}`)}finally{p(!1)}}};return a?Ee(bt,{flexDirection:"column",children:[Ee(fe,{color:"red",children:["Failed to load goals: ",a]}),Ve(fe,{dimColor:!0,children:"Press Esc or q to return"})]}):u==="create"?Ee(bt,{flexDirection:"column",children:[Ve(fe,{bold:!0,children:"Create Goal"}),Ve(fe,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Ee(bt,{marginTop:1,children:[Ve(fe,{color:"cyan",children:"> "}),Ve(Gi,{value:l,onChange:i,onSubmit:k})]}),n&&Ve(fe,{color:"yellow",children:"Creating goal..."}),g&&Ve(fe,{color:g.startsWith("Failed")?"red":"green",children:g}),Ve(fe,{dimColor:!0,children:"Press Esc to cancel"})]}):Ee(bt,{flexDirection:"column",children:[Ee(fe,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Ve(fe,{dimColor:!0,children:"No goals found. Press c to create one."}):Ve(bt,{marginTop:1,flexDirection:"column",children:t.map(s=>{let c=s.targetValue>0?s.currentValue/s.targetValue:0,E=Ki[s.status]??"white";return Ee(bt,{marginBottom:1,flexDirection:"column",children:[Ee(bt,{children:[Ve(fe,{bold:!0,color:E,children:s.name}),Ee(fe,{dimColor:!0,children:[" (",s.role,")"]}),Ve(fe,{dimColor:!0,children:" \u2014 "}),Ve(fe,{color:E,children:s.status})]}),Ee(bt,{children:[Ee(fe,{dimColor:!0,children:[" ",Hi(c)," "]}),Ee(fe,{color:c>=1?"green":"white",children:[Math.round(c*100),"%"]}),Ee(fe,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),Ee(bt,{children:[Ee(fe,{dimColor:!0,children:[" \u23F0 ",zi(s.deadline)," left"]}),Ee(fe,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),Ee(fe,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),Ve(fe,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as Zt,Text as Qe,useInput as Xi}from"ink";import{useEffect as Yi,useState as qn}from"react";import{jsx as Ct,jsxs as vt}from"react/jsx-runtime";function Qi(e,t,r=15){let a=e/(e+t),o=Math.round(a*r);return"\u2593".repeat(o)+"\u2591".repeat(r-o)}function Vn({onBack:e}){let[t,r]=qn([]),[a,o]=qn(null);if(Xi((d,l)=>{(l.escape||d==="q")&&e()}),Yi(()=>{S("/strategies?limit=50").then(d=>r(d.strategies??[])).catch(d=>o(d.message))},[]),a)return vt(Zt,{flexDirection:"column",children:[vt(Qe,{color:"red",children:["Failed to load strategies: ",a]}),Ct(Qe,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return vt(Zt,{flexDirection:"column",children:[Ct(Qe,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Ct(Qe,{dimColor:!0,children:"Press Esc or q to return"})]});let u=new Map;for(let d of t){let l=`${d.role}/${d.taskType}`,i=u.get(l)??[];i.push(d),u.set(l,i)}return vt(Zt,{flexDirection:"column",children:[Ct(Qe,{bold:!0,children:"Strategy Lab"}),Ct(Qe,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Ct(Zt,{marginTop:1,flexDirection:"column",children:Array.from(u.entries()).map(([d,l])=>vt(Zt,{marginBottom:1,flexDirection:"column",children:[Ct(Qe,{bold:!0,color:"cyan",children:d}),l.sort((i,n)=>{let p=i.alpha/(i.alpha+i.beta);return n.alpha/(n.alpha+n.beta)-p}).map(i=>{let n=i.alpha/(i.alpha+i.beta);return vt(Zt,{children:[Ct(Qe,{dimColor:!0,children:" "}),vt(Qe,{children:[Qi(i.alpha,i.beta)," "]}),vt(Qe,{color:n>.6?"green":n>.4?"yellow":"red",children:[(n*100).toFixed(0),"%"]}),vt(Qe,{dimColor:!0,children:[" ",i.name," (\u03B1=",i.alpha.toFixed(1)," \u03B2=",i.beta.toFixed(1)," trials=",i.totalTrials,")"]})]},i.id)})]},d))}),Ct(Qe,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as we,Text as K,useInput as ra}from"ink";import wo from"ink-text-input";import{useEffect as oa,useState as Ze,useCallback as Pt}from"react";import{CronExpressionParser as na}from"cron-parser";import{useState as Ji,useEffect as Zi,useCallback as Un,useRef as ea}from"react";var ta=3e3;function Je(){let[e,t]=Ji(null),r=ea(null),a=Un(()=>{r.current&&(clearTimeout(r.current),r.current=null),t(null)},[]),o=Un((u,d)=>{r.current&&(clearTimeout(r.current),r.current=null),t({text:u,type:d}),d==="success"&&(r.current=setTimeout(()=>{t(null),r.current=null},ta))},[]);return Zi(()=>()=>{r.current&&clearTimeout(r.current)},[]),{message:e,setMessage:o,clearMessage:a}}import{Fragment as ia,jsx as ie,jsxs as te}from"react/jsx-runtime";var ko=["manual","cron","once","template_complete"],Wn=["cron","once","template_complete"],Qr={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function sa(e){try{return na.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function Jr({onBack:e}){let[t,r]=Ze([]),[a,o]=Ze(!0),[u,d]=Ze(0),[l,i]=Ze("list"),[n,p]=Ze({...Qr}),[g,v]=Ze("name"),[b,k]=Ze(null),{message:s,setMessage:c,clearMessage:E}=Je(),[C,A]=Ze(!1),[W,X]=Ze(!1),[N,F]=Ze({}),[q,I]=Ze(null),[H,oe]=Ze(!1),Q=Pt(()=>{o(!0),S("/task-templates").then(({templates:x})=>{r(x),new Set(x.flatMap(R=>R.steps?.map(Z=>Z.roleId).filter(Boolean)??[])).size>0?S("/roles").then(({roles:R})=>{if(!Array.isArray(R)){F({});return}F(Object.fromEntries(R.map(Z=>[Z.id,Z.name])))}).catch(()=>F({})):F({}),o(!1)}).catch(()=>o(!1))},[]);oa(()=>{Q()},[Q]);let Me=l==="create"||l==="edit",Re=Pt(async()=>{let x=t[u];if(!(!x||C)){A(!0),c(`Triggering ${x.name}...`,"loading");try{let w=await S(`/task-templates/${x.id}/run`,{method:"POST"});c(`Triggered: ${x.name} (${w.executionId})`,"success")}catch(w){c(`Trigger failed: ${w instanceof Error?w.message:String(w)}`,"error")}finally{A(!1)}}},[t,u,C,c]),M=Pt(async()=>{let x=t[u];if(!x||W)return;if(!Wn.includes(x.trigger?.type??"manual")){c("Toggle not applicable for manual triggers","error");return}let w=!x.enabled;X(!0),c(`${x.name} \u2192 ${w?"enabling":"disabling"}...`,"loading");try{await S(`/task-templates/${x.id}`,{method:"PATCH",body:{enabled:w}}),r(R=>R.map(Z=>Z.id===x.id?{...Z,enabled:w}:Z)),c(`${x.name} ${w?"enabled":"disabled"}`,"success")}catch(R){c(`Toggle failed: ${R instanceof Error?R.message:String(R)}`,"error")}finally{X(!1)}},[t,u,W,c]),ne=Pt(async()=>{if(H)return;let x=t[u];if(x){oe(!0);try{let w=await S(`/task-templates/${x.id}/dependents`,{method:"GET"});I({templateId:x.id,templateName:x.name,executionCount:w.dependents.executionCount,taskCount:w.dependents.taskCount}),w.dependents.taskCount===0&&w.dependents.executionCount===0?c(`Delete "${x.name}"? Press d to confirm, Esc to cancel.`,"loading"):c(`"${x.name}" has ${w.dependents.executionCount} template execution${w.dependents.executionCount===1?"":"s"}, ${w.dependents.taskCount} task${w.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(w){c(`Failed to inspect dependents: ${w instanceof Error?w.message:String(w)}`,"error")}finally{oe(!1)}}},[t,u,c,H]),_=Pt(async x=>{let w=q;if(w){I(null);try{let R=await S(`/task-templates/${w.templateId}?mode=${x}`,{method:"DELETE"}),Z=[];R.deletedCounts.templateExecutions>0&&Z.push(`${R.deletedCounts.templateExecutions} template exec`),R.deletedCounts.tasks>0&&Z.push(`${R.deletedCounts.tasks} task${R.deletedCounts.tasks===1?"":"s"}`);let ge=Z.length?` (+${Z.join(", ")})`:"";c(`Deleted: ${w.templateName}${ge}`,"success"),Q(),d(he=>Math.max(0,Math.min(he,t.length-2)))}catch(R){c(`Delete failed: ${R instanceof Error?R.message:String(R)}`,"error")}}},[q,Q,c,t.length]),se=Pt(()=>{I(null),E()},[E]),Ce=Pt(()=>{let x=t[u];x&&(k(x.id),p({name:x.name,triggerType:x.trigger?.type??"manual",cron:x.trigger?.cron??"",targetTemplateId:x.trigger?.type==="template_complete"?x.trigger.event?.split(":")[1]??"":"",stepPrompt:x.steps?.[0]?.prompt??""}),v("name"),i("edit"))},[t,u]),V=Pt(async()=>{let x={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{l==="create"?(await S("/task-templates",{method:"POST",body:x}),c(`Created: ${n.name}`,"success")):l==="edit"&&b&&(await S(`/task-templates/${b}`,{method:"PATCH",body:x}),c(`Updated: ${n.name}`,"success"))}catch(w){c(`Save failed: ${w instanceof Error?w.message:String(w)}`,"error")}i("list"),p({...Qr}),k(null),Q()},[n,l,b,Q]);return ra((x,w)=>{if(Me){if(w.escape){i("list"),p({...Qr}),k(null);return}if(w.return){let R=["name","triggerType","cron","stepPrompt"],ge=n.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:R.filter($=>$!=="targetTemplateId"),he=ge.indexOf(g);if(he<ge.length-1){let $=he+1;if(ge[$]==="cron"&&n.triggerType!=="cron"&&$++,$<ge.length){v(ge[$]);return}}V();return}if(w.tab&&g==="triggerType"){p(R=>{let Z=ko.indexOf(R.triggerType);return{...R,triggerType:ko[(Z+1)%ko.length]}});return}if(w.tab&&g==="targetTemplateId"){p(R=>{let Z=t.filter($=>$.id!==b),ge=Z.findIndex($=>$.id===R.targetTemplateId),he=Z[(ge+1)%Z.length];return{...R,targetTemplateId:he?.id??""}});return}return}if(q){if(w.escape){se();return}if(x==="D"&&w.shift){_("with_tasks");return}if(x==="d"&&!w.shift){_("template_only");return}return}if(w.escape||x==="q"){e();return}if(w.upArrow){d(R=>Math.max(0,R-1));return}if(w.downArrow){d(R=>Math.min(t.length-1,R+1));return}if(x==="t"){Re();return}if(x==="d"&&!w.shift){ne();return}if(x==="e"){Ce();return}if(x==="c"){p({...Qr}),v("name"),i("create");return}if(x==="s"||x===" "){M();return}x==="r"&&(Q(),E())}),a?ie(K,{dimColor:!0,children:"Loading templates..."}):Me?te(we,{flexDirection:"column",children:[te(K,{bold:!0,children:[l==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),te(we,{marginTop:1,flexDirection:"column",children:[te(we,{children:[te(K,{bold:g==="name",color:g==="name"?"cyan":void 0,children:["Name:"," "]}),g==="name"?ie(wo,{value:n.name,onChange:x=>p(w=>({...w,name:x})),placeholder:"template name"}):ie(K,{children:n.name||"(empty)"})]}),te(we,{children:[te(K,{bold:g==="triggerType",color:g==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),ie(K,{children:n.triggerType}),g==="triggerType"&&ie(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),n.triggerType==="cron"&&te(we,{children:[te(K,{bold:g==="cron",color:g==="cron"?"cyan":void 0,children:["Cron:"," "]}),g==="cron"?ie(wo,{value:n.cron,onChange:x=>p(w=>({...w,cron:x})),placeholder:"*/5 * * * *"}):ie(K,{children:n.cron||"(empty)"})]}),n.triggerType==="template_complete"&&te(we,{children:[te(K,{bold:g==="targetTemplateId",color:g==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),ie(K,{children:(()=>{let x=t.find(w=>w.id===n.targetTemplateId);return x?x.name:n.targetTemplateId?`(id: ${n.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),g==="targetTemplateId"&&ie(K,{dimColor:!0,children:" (Tab to cycle)"})]}),te(we,{children:[te(K,{bold:g==="stepPrompt",color:g==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),g==="stepPrompt"?ie(wo,{value:n.stepPrompt,onChange:x=>p(w=>({...w,stepPrompt:x})),placeholder:"What should this template do?"}):ie(K,{children:n.stepPrompt||"(empty)"})]})]}),ie(we,{marginTop:1,children:ie(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):te(we,{flexDirection:"column",children:[te(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&ie(we,{marginTop:1,children:te(K,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?ie(we,{marginTop:1,children:ie(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):ie(we,{marginTop:1,flexDirection:"column",children:t.map((x,w)=>{let R=w===u,Z=x.trigger?.type==="cron"&&x.trigger?.cron?sa(x.trigger.cron):"",ge=new Set(x.steps?.filter($=>$.roleId).map($=>$.roleId)),he=x.steps?.length>1?`${x.steps.length} steps${ge.size>0?` / ${ge.size} roles`:""}`:`${x.steps?.length??0} step`;return te(we,{flexDirection:"column",children:[te(we,{children:[ie(K,{color:R?"cyan":void 0,bold:R,children:R?"> ":" "}),ie(K,{color:R?"cyan":void 0,bold:R,children:vr(x.name,24)}),ie(K,{dimColor:!0,children:vr(x.trigger?.type,10)}),Wn.includes(x.trigger?.type??"manual")?ie(K,{color:x.enabled?"green":"gray",children:vr(x.enabled?"on":"off",6)}):ie(K,{dimColor:!0,children:vr("\u2014",6)}),ie(K,{dimColor:!0,children:vr(he,18)}),Z&&te(K,{dimColor:!0,children:["next: ",Z]})]}),R&&te(ia,{children:[x.config?.delivery&&ie(we,{marginLeft:4,marginTop:0,children:te(K,{dimColor:!0,children:[" Delivery: ",x.config.delivery.mode,x.config.delivery.mode==="primary-artifact"&&x.config.delivery.primaryArtifact&&` (${x.config.delivery.primaryArtifact.stepId}/${x.config.delivery.primaryArtifact.key})`]})}),x.steps&&x.steps.length>1&&ie(we,{flexDirection:"column",marginLeft:4,marginTop:0,children:x.steps.map(($,Gt)=>te(we,{children:[te(K,{dimColor:!0,children:[" ",Gt+1,". "]}),ie(K,{dimColor:!0,children:$.id}),$.roleId&&te(K,{color:"yellow",children:[" @",N[$.roleId]??$.roleId]}),$.dependsOn&&$.dependsOn.length>0&&te(K,{dimColor:!0,children:[" (after: ",$.dependsOn.join(", "),")"]}),$.consumesFrom&&$.consumesFrom.length>0&&te(K,{dimColor:!0,children:[" [consumes: ",$.consumesFrom.join(", "),"]"]}),$.consumesFromOptional&&$.consumesFromOptional.length>0&&te(K,{dimColor:!0,children:[" [consumes?: ",$.consumesFromOptional.join(", "),"]"]}),$.persona&&te(K,{dimColor:!0,children:[" [speak as: ",$.persona.speakAs,$.persona.voiceConstraints?` / ${$.persona.voiceConstraints}`:"","]"]}),$.outputContract&&te(K,{dimColor:!0,children:[" [",$.outputContract.lengthTarget?`${$.outputContract.lengthTarget.min}-${$.outputContract.lengthTarget.max} ${$.outputContract.lengthTarget.unit}`:"",$.outputContract.format?` ${$.outputContract.format}`:"",$.outputContract.mustReferenceArtifacts?" ref-artifacts":"","]"]}),$.config&&te(K,{dimColor:!0,children:[" ","[",[$.config.timeout!==void 0?`timeout:${$.config.timeout}s`:"",$.config.maxTurns!==void 0?`turns:${$.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},$.id))})]})]},x.id)})}),ie(we,{marginTop:1,children:ie(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function vr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Rt,Text as Ke,useInput as aa}from"ink";import la from"ink-text-input";import{useEffect as ca,useState as er,useCallback as Gn}from"react";import{jsx as Le,jsxs as Lt}from"react/jsx-runtime";function jn({onBack:e}){let[t,r]=er([]),[a,o]=er(""),[u,d]=er(!0),[l,i]=er(!1),[n,p]=er(""),[g,v]=er(null),b=Gn(()=>{d(!0),S("/webhooks").then(({webhooks:s,auth:c})=>{r(s),o(c),d(!1)}).catch(()=>d(!1))},[]);ca(()=>{b()},[b]);let k=Gn(async s=>{if(s.trim())try{let c=await S(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});v(`Triggered: ${c.executionId}`)}catch(c){v(`Trigger failed: ${c instanceof Error?c.message:String(c)}`)}},[]);return aa((s,c)=>{if(l){if(c.escape){i(!1),p("");return}if(c.return){k(n),i(!1),p("");return}return}if(c.escape||s==="q"){e();return}if(s==="t"){i(!0),p(""),v(null);return}s==="r"&&(b(),v(null))}),u?Le(Ke,{dimColor:!0,children:"Loading webhooks..."}):Lt(Rt,{flexDirection:"column",children:[Lt(Ke,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),Lt(Ke,{dimColor:!0,children:["Auth: ",a]}),g&&Le(Rt,{marginTop:1,children:Le(Ke,{color:"yellow",children:g})}),l&&Lt(Rt,{marginTop:1,children:[Le(Ke,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Le(la,{value:n,onChange:p,placeholder:"webhook name or ID"}),Le(Ke,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Le(Rt,{marginTop:1,children:Le(Ke,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):Lt(Rt,{marginTop:1,flexDirection:"column",children:[Le(Rt,{children:Lt(Ke,{bold:!0,children:[tr("NAME",24),tr("DESCRIPTION",36),tr("TRIGGER",28),"TAGS"]})}),t.map(s=>Lt(Rt,{children:[Le(Ke,{children:tr(s.displayName,24)}),Le(Ke,{dimColor:!0,children:tr(da(s.description??"",34),36)}),Le(Ke,{dimColor:!0,children:tr(s.trigger,28)}),Le(Ke,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),Le(Rt,{marginTop:1,children:Le(Ke,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function tr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function da(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as gt,Text as ye,useInput as ua}from"ink";import ma from"ink-text-input";import{useEffect as Kn,useState as St,useCallback as Bo}from"react";import{jsx as be,jsxs as st}from"react/jsx-runtime";function fa(e){return e>=4?"red":e===3?"yellow":"gray"}function ga(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function pa(e){return new Date(e).toLocaleDateString()}function zn({onBack:e}){let[t,r]=St([]),[a,o]=St(0),[u,d]=St([]),[l,i]=St(!0),[n,p]=St(!1),[g,v]=St(""),[b,k]=St("all"),[s,c]=St(null),[E,C]=St(!1),A=Bo(()=>{S("/agents").then(({agents:I})=>{r(I),i(!1)}).catch(()=>i(!1))},[]);Kn(()=>{A()},[A]);let W=t[a],X=Bo(()=>{W&&(C(!1),S(`/memories/${W.id}`).then(({memories:I})=>{d(I),c(null)}).catch(I=>c(`Failed: ${I instanceof Error?I.message:String(I)}`)))},[W]);Kn(()=>{W&&X()},[W,X]);let N=Bo(async I=>{if(!(!W||!I.trim()))try{let H=await S("/memories/query",{method:"POST",body:{agentId:W.id,prompt:I.trim()}});d(H.memories),C(!0),c(`Search: ${H.count} results`)}catch(H){c(`Search failed: ${H instanceof Error?H.message:String(H)}`)}},[W]),F=n,q=u.filter(I=>b==="all"?!0:b==="high"?I.importance>3:b==="medium"?I.importance===3:I.importance<3);return ua((I,H)=>{if(F){if(H.escape){p(!1),v("");return}if(H.return){N(g),p(!1),v("");return}return}if(H.escape||I==="q"){e();return}if(I==="a"){o(oe=>(oe+1)%Math.max(1,t.length));return}if(H.leftArrow){o(oe=>(oe-1+t.length)%Math.max(1,t.length));return}if(H.rightArrow){o(oe=>(oe+1)%Math.max(1,t.length));return}if(I==="s"){p(!0),v(""),c(null);return}if(I==="h"){k(oe=>oe==="high"?"all":"high");return}if(I==="m"){k(oe=>oe==="medium"?"all":"medium");return}if(I==="l"){k(oe=>oe==="low"?"all":"low");return}I==="r"&&X()}),l?be(ye,{dimColor:!0,children:"Loading agents..."}):t.length===0?st(gt,{flexDirection:"column",children:[be(ye,{dimColor:!0,children:"No agents found"}),be(ye,{dimColor:!0,children:"Press Esc to go back"})]}):st(gt,{flexDirection:"column",children:[be(ye,{bold:!0,children:"Memories (Esc to go back)"}),st(gt,{marginTop:1,children:[be(ye,{children:"Agent: "}),be(ye,{bold:!0,color:"cyan",children:W?.name??"?"}),st(ye,{dimColor:!0,children:[" (",a+1,"/",t.length,") [a/arrows to switch]"]})]}),be(gt,{children:st(ye,{dimColor:!0,children:["Filter: ",b==="all"?"all":b," | ",E?"search results":"all memories"," (",q.length,")"]})}),s&&be(gt,{children:be(ye,{color:"yellow",children:s})}),n&&st(gt,{marginTop:1,children:[be(ye,{bold:!0,color:"cyan",children:"Search: "}),be(ma,{value:g,onChange:v,placeholder:"search query..."}),be(ye,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),q.length===0?be(gt,{marginTop:1,children:st(ye,{dimColor:!0,children:["No memories",b!=="all"?` matching filter '${b}'`:""]})}):be(gt,{marginTop:1,flexDirection:"column",children:q.map(I=>st(gt,{marginBottom:0,children:[st(ye,{color:fa(I.importance),bold:!0,children:[ga(I.importance)," "]}),be(ye,{dimColor:!0,children:Hn(I.type??"?",12)}),be(ye,{dimColor:!0,children:Hn(`\xD7${I.retrievedCount??0}`,5)}),st(ye,{children:[xa(I.content,55)," "]}),be(ye,{dimColor:!0,children:pa(I.createdAt)}),I.score!==void 0&&st(ye,{dimColor:!0,children:[" (",I.score.toFixed(2),")"]})]},I.id))}),be(gt,{marginTop:1,children:be(ye,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Hn(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function xa(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as it,Text as xe,useInput as Ta}from"ink";import Zr from"ink-text-input";import{useState as Ue,useEffect as Xn,useCallback as Io}from"react";import{jsx as Ae,jsxs as ke}from"react/jsx-runtime";var Yn={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"],"Execution Artifacts":["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},ha={"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 Qn({onBack:e}){let{state:t}=Ye(),[r,a]=Ue({}),[o,u]=Ue([]),[d,l]=Ue(null),[i,n]=Ue("view"),[p,g]=Ue(0),[v,b]=Ue(""),[k,s]=Ue(null),[c,E]=Ue(!1),[C,A]=Ue([]),[W,X]=Ue({}),[N,F]=Ue(0),[q,I]=Ue(""),[H,oe]=Ue(""),[Q,Me]=Ue(""),Re=Object.values(Yn).flat(),M=Io(()=>{S("/config").then(V=>{a(V.config),u(V.mutable)}).catch(V=>l(V.message)),S("/config/env-diff").then(V=>{A(V.diffs)}).catch(()=>{}),S("/config/env").then(V=>X(V.env??{})).catch(()=>{})},[]);Xn(()=>{M()},[M]),Xn(()=>{t.configVersion>0&&M()},[t.configVersion,M]);let ne=Io(async()=>{let V=Re[p];if(V){E(!0),s(null);try{let x=v,w=r[V];if(w&&typeof w.value=="number"&&(x=Number(v),isNaN(x))){s("Invalid number"),E(!1);return}let R=await S("/config",{method:"PATCH",body:{[V]:x}});R.updated.length>0&&(s(`Updated: ${V}`),M()),R.errors.length>0&&s(R.errors[0]),n("view")}catch(x){s(`Failed: ${x instanceof Error?x.message:String(x)}`)}finally{E(!1)}}},[Re,p,v,r,M]),_=Object.keys(W),se=Io(async V=>{try{await S("/config/env",{method:"PUT",body:V}),s("Env vars saved"),M()}catch(x){s(`Failed: ${x instanceof Error?x.message:String(x)}`)}},[M]);if(Ta((V,x)=>{if(i==="edit"){if(x.escape){n("view");return}return}if(i==="env-list"){if(x.escape){n("view");return}if(x.upArrow&&N>0&&F(w=>w-1),x.downArrow&&N<_.length-1&&F(w=>w+1),V==="a"){I(""),n("env-add-key");return}if(V==="d"&&_.length>0){let w=_[N],R={...W};delete R[w],se(R),N>=_.length-1&&N>0&&F(Z=>Z-1);return}if(x.return&&_.length>0){Me(W[_[N]]??""),n("env-edit-value");return}return}if(i==="env-add-key"){if(x.escape){n("env-list");return}return}if(i==="env-add-value"){if(x.escape){n("env-list");return}return}if(i==="env-edit-value"){if(x.escape){n("env-list");return}return}if(x.escape||V==="q"){e();return}if(x.upArrow&&p>0&&g(w=>w-1),x.downArrow&&p<Re.length-1&&g(w=>w+1),x.return||V==="e"){let w=Re[p],R=r[w];R&&R.mutable?(b(String(R.value??"")),n("edit"),s(null)):R&&!R.mutable&&s("This setting requires a restart to change")}V==="v"&&(F(0),n("env-list"),s(null)),V==="r"&&(M(),s("Refreshed")),V==="s"&&C.length>0&&S("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),A([]),M()}),V==="l"&&C.length>0&&S("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),M()})}),d)return ke(it,{flexDirection:"column",children:[ke(xe,{color:"red",children:["Failed to load config: ",d]}),Ae(xe,{dimColor:!0,children:"Press Esc or q to return"})]});let Ce=0;return ke(it,{flexDirection:"column",children:[Ae(xe,{bold:!0,children:"Settings"}),k&&Ae(xe,{color:k.startsWith("Failed")||k.startsWith("This setting")?"yellow":"green",children:k}),C&&C.length>0&&ke(it,{flexDirection:"column",marginBottom:1,children:[ke(xe,{color:"yellow",children:[".env differs from DB (",C.length," key(s)): ",C.map(V=>V.envKey).join(", ")]}),Ae(xe,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Ae(it,{marginTop:1,flexDirection:"column",children:Object.entries(Yn).map(([V,x])=>ke(it,{marginBottom:1,flexDirection:"column",children:[Ae(xe,{bold:!0,color:"cyan",children:V}),x.map(w=>{let R=r[w],ge=Ce++===p,he=o.includes(w),$=ha[w]??w,Gt=R?String(R.value??""):"...";return i==="edit"&&ge?ke(it,{children:[ke(xe,{color:"cyan",children:["> ",$,": "]}),Ae(Zr,{value:v,onChange:b,onSubmit:()=>{ne()}}),c&&Ae(xe,{color:"yellow",children:" saving..."})]},w):ke(it,{children:[ke(xe,{color:ge?"cyan":"white",children:[ge?"> ":" ",he?" ":"\u{1F512} ",$,": "," "]}),Ae(xe,{color:he?"white":"gray",children:Gt}),!he&&Ae(xe,{dimColor:!0,children:" (restart required)"})]},w)})]},V))}),Ae(xe,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),i.startsWith("env")&&ke(it,{flexDirection:"column",marginTop:1,children:[ke(xe,{bold:!0,color:"cyan",children:["Environment Variables (",_.length,")"]}),_.length===0&&i==="env-list"&&Ae(xe,{dimColor:!0,children:" No env vars. Press a to add."}),_.map((V,x)=>{let w=x===N;return i==="env-edit-value"&&w?ke(it,{children:[ke(xe,{color:"cyan",children:["> ",V," = "]}),Ae(Zr,{value:Q,onChange:Me,onSubmit:()=>{se({...W,[V]:Q}),n("env-list")}})]},V):ke(xe,{color:w&&i==="env-list"?"cyan":"white",children:[w&&i==="env-list"?"> ":" ",V," = ",W[V]]},V)}),i==="env-add-key"&&ke(it,{children:[Ae(xe,{color:"green",children:" New key: "}),Ae(Zr,{value:q,onChange:I,onSubmit:()=>{q.trim()&&(oe(""),n("env-add-value"))}})]}),i==="env-add-value"&&ke(it,{children:[ke(xe,{color:"green",children:[" ",q," = "]}),Ae(Zr,{value:H,onChange:oe,onSubmit:()=>{se({...W,[q.trim()]:H}),n("env-list")}})]}),Ae(xe,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as Ft,Text as Fe,useInput as ya}from"ink";import{useEffect as ba,useState as Eo,useCallback as va}from"react";import{jsx as De,jsxs as or}from"react/jsx-runtime";function Jn({onBack:e}){let[t,r]=Eo([]),[a,o]=Eo(!0),[u,d]=Eo(0),{message:l,setMessage:i,clearMessage:n}=Je(),p=va(()=>{o(!0),S("/plugins").then(({plugins:g})=>{r(g),o(!1)}).catch(()=>o(!1))},[]);return ba(()=>{p()},[p]),ya((g,v)=>{if(v.escape||g==="q"){e();return}if(v.upArrow){d(b=>Math.max(0,b-1));return}if(v.downArrow){d(b=>Math.min(t.length-1,b+1));return}g==="r"&&(p(),n())}),a?De(Fe,{dimColor:!0,children:"Loading plugins..."}):or(Ft,{flexDirection:"column",children:[or(Fe,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),l&&De(Ft,{marginTop:1,children:or(Fe,{color:l.type==="success"?"green":l.type==="error"?"red":"gray",children:[l.type==="success"?"\u2713 ":l.type==="error"?"\u2717 ":"\u2192 ",l.text]})}),t.length===0?De(Ft,{marginTop:1,children:De(Fe,{dimColor:!0,children:"No plugins installed."})}):or(Ft,{marginTop:1,flexDirection:"column",children:[or(Ft,{children:[De(Fe,{dimColor:!0,children:" "}),De(Fe,{dimColor:!0,children:rr("Name",24)}),De(Fe,{dimColor:!0,children:rr("Scope",8)}),De(Fe,{dimColor:!0,children:rr("User",6)}),De(Fe,{dimColor:!0,children:"Path"})]}),t.map((g,v)=>{let b=v===u,k=g.id.split("@")[0];return or(Ft,{children:[De(Fe,{color:b?"cyan":void 0,bold:b,children:b?"> ":" "}),De(Fe,{color:b?"cyan":void 0,bold:b,children:rr(k,24)}),De(Fe,{color:b?"cyan":void 0,bold:b,children:rr(g.scope,8)}),De(Fe,{color:g.globalEnabled?"green":"gray",children:rr(g.globalEnabled?"on":"off",6)}),De(Fe,{dimColor:!0,children:g.installPath})]},g.id)})]}),De(Ft,{marginTop:1,children:De(Fe,{dimColor:!0,children:"r:refresh"})})]})}function rr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ao,Text as Po,useInput as Ca}from"ink";import{useState as Sa}from"react";import{jsx as Ot,jsxs as Zn}from"react/jsx-runtime";var wa=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function es({onBack:e}){let[t,r]=Sa("tasks");return Ca((a,o)=>{if(o.escape||a==="q"){e();return}if(a==="1"){r("tasks");return}if(a==="2"){r("automations");return}if(a==="3"){r("goals");return}}),Zn(Ao,{flexDirection:"column",children:[Ot(Po,{bold:!0,children:"Work Surface"}),Ot(Po,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Ot(Ao,{gap:3,marginBottom:1,marginTop:1,children:wa.map(a=>{let o=t===a.id;return Ot(Ao,{children:Zn(Po,{color:o?"cyan":"gray",bold:o,children:[o?"\u25CF":"\u25CB"," ",a.key,". ",a.label]})},a.id)})}),t==="tasks"&&Ot(zr,{onBack:e}),t==="automations"&&Ot(Jr,{onBack:e}),t==="goals"&&Ot(Yr,{onBack:e})]})}import{Box as de,Text as re,useInput as ka}from"ink";import{useEffect as Ba,useState as Cr}from"react";import{jsx as G,jsxs as Pe}from"react/jsx-runtime";var ts={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function rs({onBack:e}){let[t,r]=Cr([]),[a,o]=Cr(!0),[u,d]=Cr(0),[l,i]=Cr(null),[n,p]=Cr("");Ba(()=>{g()},[]);async function g(){try{let k=await S("/channels");r(k.channels)}catch{}o(!1)}async function v(k){if(t.find(c=>c.id===k)?.platform==="wechat")try{p("Starting WeChat QR login...");let c=await S(`/channels/${k}/wechat/qr-start`,{method:"POST"});if(c.qrcodeUrl){p(`Scan QR: ${c.qrcodeUrl}
10
+ Waiting for scan...`);let E=await S(`/channels/${k}/wechat/qr-wait`,{method:"POST",body:{sessionKey:c.sessionKey,timeoutMs:12e4}});p(E.message)}else p(c.message);g()}catch{p("WeChat connect failed")}else try{await S(`/channels/${k}/connect`,{method:"POST"}),p("Connecting..."),g()}catch{p("Connect failed")}}async function b(k){try{await S(`/channels/${k}/disconnect`,{method:"POST"}),p("Disconnected"),g()}catch{p("Disconnect failed")}}return ka((k,s)=>{if(l){if(s.escape||k==="q"){i(null);return}if(k==="c"){v(l.id);return}if(k==="d"){b(l.id);return}return}if(s.escape){e();return}if(s.upArrow){d(c=>Math.max(0,c-1));return}if(s.downArrow){d(c=>Math.min(t.length-1,c+1));return}if(s.return&&t[u]){i(t[u]),p("");return}}),a?G(de,{flexDirection:"column",children:G(re,{dimColor:!0,children:"Loading channels..."})}):l?Pe(de,{flexDirection:"column",children:[Pe(de,{marginBottom:1,children:[Pe(re,{bold:!0,children:["Channel: ",l.name]}),G(re,{dimColor:!0,children:" (Esc to go back)"})]}),Pe(de,{flexDirection:"column",gap:0,children:[Pe(re,{children:["ID: ",l.id]}),Pe(re,{children:["Platform: ",l.platform]}),Pe(re,{children:["Status: ",G(re,{color:ts[l.status]??"white",children:l.status})]}),Pe(re,{children:["Enabled: ",l.enabled?"yes":"no"]}),Pe(re,{children:["Messages: ",l.messageCount]}),Pe(re,{children:["Config: ",JSON.stringify(l.config)]})]}),G(de,{marginTop:1,children:G(re,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),n&&G(re,{color:"yellow",children:n})]}):Pe(de,{flexDirection:"column",children:[Pe(de,{marginBottom:1,children:[G(re,{bold:!0,children:"Channels"}),Pe(re,{dimColor:!0,children:[" (",t.length," total) "]}),G(re,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?G(re,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):Pe(de,{flexDirection:"column",children:[Pe(de,{children:[G(de,{width:3,children:G(re,{dimColor:!0,children:" "})}),G(de,{width:12,children:G(re,{bold:!0,dimColor:!0,children:"ID"})}),G(de,{width:16,children:G(re,{bold:!0,dimColor:!0,children:"Name"})}),G(de,{width:12,children:G(re,{bold:!0,dimColor:!0,children:"Platform"})}),G(de,{width:14,children:G(re,{bold:!0,dimColor:!0,children:"Status"})}),G(de,{width:10,children:G(re,{bold:!0,dimColor:!0,children:"Enabled"})}),G(de,{width:10,children:G(re,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((k,s)=>Pe(de,{children:[G(de,{width:3,children:G(re,{children:s===u?">":" "})}),G(de,{width:12,children:G(re,{inverse:s===u,children:k.id.slice(0,8)})}),G(de,{width:16,children:G(re,{children:k.name})}),G(de,{width:12,children:G(re,{children:k.platform})}),G(de,{width:14,children:Pe(re,{color:ts[k.status]??"white",children:[k.status==="connected"?"\u25CF":k.status==="error"?"\u2717":"\u25CB"," ",k.status]})}),G(de,{width:10,children:G(re,{color:k.enabled?"green":"gray",children:k.enabled?"yes":"no"})}),G(de,{width:10,children:G(re,{children:k.messageCount})})]},k.id))]})]})}import{Box as nr,Text as lt,useInput as Aa}from"ink";import{useEffect as Pa,useState as Sr,useCallback as Ra}from"react";import{Box as D,Text as T,useInput as Ia}from"ink";import at from"ink-text-input";import{useEffect as os,useState as z,useCallback as pt}from"react";Go();import{Fragment as eo,jsx as y,jsxs as B}from"react/jsx-runtime";var Ea=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function ns({roleId:e,onBack:t}){let[r,a]=z(null),[o,u]=z([]),[d,l]=z(!0),[i,n]=z("view"),[p,g]=z(""),[v,b]=z(0),[k,s]=z(""),[c,E]=z([]),[C,A]=z(0),[W,X]=z(new Set),[N,F]=z("inline"),[q,I]=z(""),[H,oe]=z(""),[Q,Me]=z(""),[Re,M]=z([]),[ne,_]=z(new Set),[se,Ce]=z(0),[V,x]=z("default"),[w,R]=z(""),[Z,ge]=z(""),[he,$]=z("mode"),[Gt,ys]=z([]),[jt,bs]=z(null),[ao,vs]=z([]),[Kt,lo]=z([]),[No,co]=z(""),[$t,Ir]=z(0),[Er,_o]=z(""),[Lo,Fo]=z(""),[Oo,qo]=z(""),[Ar,uo]=z(0),[dr,Vo]=z([]),[Pr,mo]=z(0),[Rr,Dr]=z(!1),[Ht,Cs]=z(""),{message:L,setMessage:O}=Je(),ae=pt(()=>{l(!0),S(`/roles/${e}`).then(({role:m,projectPlugins:h,workspacePath:f})=>{a(m),u(h??[]),Cs(f??""),g(m.cagPrompt??""),X(new Set(m.allowedTools??[])),F(m.executionMode??"inline"),I(m.model??""),oe(m.effortTier??""),Me(m.maxBudgetUsd!=null?String(m.maxBudgetUsd):""),l(!1)}).catch(()=>l(!1))},[e]);os(()=>{ae(),S("/config").then(m=>{let h=m.config["defaults.deniedReadPaths"]?.value;Array.isArray(h)&&ys(h),bs(m.sandbox),vs(m.osCapabilities?.registry??[])}).catch(()=>{})},[ae]),os(()=>{F(r?.executionMode??"inline"),I(r?.model??""),oe(r?.effortTier??""),Me(r?.maxBudgetUsd!=null?String(r?.maxBudgetUsd):""),x(r?.permissionMode??"default"),R((r?.allowedBashPatterns??[]).join(", ")),ge((r?.deniedBashPatterns??[]).join(", ")),lo(r?.osCapabilities??[]);let m=r?.osCapabilities?.find(h=>h.id==="automation")?.targets??[];co(m.join(", "))},[r?.id,r?.executionMode,r?.model,r?.effortTier,r?.maxBudgetUsd,r?.permissionMode,r?.allowedBashPatterns,r?.deniedBashPatterns,r?.osCapabilities]);let Ss=pt(async()=>{if(r)try{await S(`/roles/${r.id}`,{method:"PATCH",body:{cagPrompt:p}}),O("CAG prompt saved","success"),n("view"),ae()}catch(m){O(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,p,ae,O]),ws=pt(async()=>{if(r)try{await S(`/roles/${r.id}`,{method:"PATCH",body:{additionalDirectories:rt}}),O("Directories saved","success"),n("view"),ae()}catch(m){O(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,ae,O]),ks=pt(async()=>{if(r)try{await S(`/roles/${r.id}`,{method:"PATCH",body:{allowedTools:Array.from(W)}}),O("Tool permissions saved","success"),n("view"),ae()}catch(m){O(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,W,ae,O]),Bs=pt(async()=>{if(!r)return;let m={executionMode:N};q!==void 0&&(m.model=q),m.effortTier=H===""?null:H;let h=parseFloat(Q);isNaN(h)||(m.maxBudgetUsd=h);try{await S(`/roles/${r.id}`,{method:"PATCH",body:m}),O("Execution config saved","success"),n("view"),ae()}catch(f){O(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,N,q,H,Q,ae,O]),Is=pt(async()=>{if(!r)return;let m={permissionMode:V},h=w.split(",").map(P=>P.trim()).filter(Boolean),f=Z.split(",").map(P=>P.trim()).filter(Boolean);m.allowedBashPatterns=h.length>0?h:[],m.deniedBashPatterns=f.length>0?f:[];try{await S(`/roles/${r.id}`,{method:"PATCH",body:m}),O("Permission config saved","success"),n("view"),ae()}catch(P){O(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[r,V,w,Z,ae,O]),Uo=pt(m=>{let h=new Map;for(let f of m){if(!f.id)continue;let P={id:f.id};f.targets?.length&&(P.targets=Array.from(new Set(f.targets.map(U=>U.trim()).filter(Boolean)))),h.set(f.id,P)}return Array.from(h.values()).sort((f,P)=>f.id.localeCompare(P.id))},[]),Es=pt(async()=>{if(!r)return;let m=Uo(Kt),h=m.find(f=>f.id==="automation")?.targets??[];if(m.some(f=>f.id==="automation")&&(h.length===0||h.some(f=>!Ea.test(f)))){O("Automation requires valid bundle id targets","error");return}try{await S(`/roles/${r.id}`,{method:"PATCH",body:{osCapabilities:m}}),O("OS capabilities saved","success"),n("view"),ae()}catch(f){O(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,Kt,Uo,ae,O]),As=pt(async m=>{if(!Ht){O("workspace path not loaded yet","error");return}Dr(!0);try{await S(`/plugins/install/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:Ht})}),O(`Bound ${m.split("@")[0]}`,"success"),ae()}catch(h){O(`Bind failed: ${h instanceof Error?h.message:"unknown"}`,"error")}finally{Dr(!1)}},[Ht,ae,O]),Ps=pt(async m=>{if(!Ht){O("workspace path not loaded yet","error");return}Dr(!0);try{await S(`/plugins/uninstall/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:Ht})}),O(`Unbound ${m.split("@")[0]}`,"success"),ae()}catch(h){O(`Unbind failed: ${h instanceof Error?h.message:"unknown"}`,"error")}finally{Dr(!1)}},[Ht,ae,O]),rt=r?.additionalDirectories??[];if(Ia((m,h)=>{if(h.escape){n("view");return}if(m==="r"){ae();return}switch(i){case"view":{if(m==="c"){n("edit-cag");return}if(m==="d"){n("edit-dirs"),b(0),s("");return}if(m==="t"){n("edit-tools");return}if(m==="o"){n("edit-oscaps");return}if(m==="x"){n("edit-exec");return}if(m==="h"){S("/channels?enabled=true").then(({channels:f})=>{M(f.map(P=>({name:P.name,id:P.id}))),_(new Set(r?.allowedChannels??[])),Ce(0),n("edit-channels")}).catch(()=>O("Failed to load channels","error"));return}if(m==="p"){x(r?.permissionMode??"default"),R((r?.allowedBashPatterns??[]).join(", ")),ge((r?.deniedBashPatterns??[]).join(", ")),$("mode"),n("edit-permissions");return}if(m==="v"){Ir(0),n("edit-env");return}if(m==="b"){uo(0),n("edit-plugins");return}if(m==="i"){if(!r)return;let f=!r.inheritUserSettings;S(`/roles/${r.id}`,{method:"PATCH",body:{inheritUserSettings:f}}).then(()=>{O(`Inherit user settings: ${f?"ON":"OFF"}`,"success"),ae()}).catch(()=>O("Failed to toggle","error"));return}if(m==="R"&&r?.presetId){S(`/presets/role/${r.presetId}/restore`,{method:"POST"}).then(()=>{O("Preset restored","success"),ae()}).catch(f=>O(`Restore failed: ${f instanceof Error?f.message:String(f)}`,"error"));return}break}case"edit-cag":{if(h.ctrl&&m==="s"){Ss();return}break}case"edit-dirs":{if(m==="s"){ws();return}if(m==="a"){n("edit-dirs-add");return}if(m==="m"&&rt.length>0){let f=rt[v];if(f){a(U=>U&&{...U,additionalDirectories:U.additionalDirectories?.map((pe,Tt)=>Tt===v?{...typeof pe=="string"?{path:pe}:pe,mode:pe.mode==="ro"?"rw":"ro"}:pe)});let P=f.mode==="ro"?"rw":"ro";O(`Mode set to ${P.toUpperCase()}`,"success")}return}if(m==="x"&&rt.length>0){a(f=>f&&{...f,additionalDirectories:rt.filter((P,U)=>U!==v)}),b(f=>Math.max(0,Math.min(f,rt.length-2)));return}if(h.upArrow){b(f=>Math.max(0,f-1));return}if(h.downArrow){b(f=>Math.min(rt.length-1,f+1));return}break}case"edit-dirs-add":{if(h.escape){n("edit-dirs"),s(""),E([]);return}if(h.return&&c.length>0){let f=c[C];f&&(s(f.endsWith("/")?f:f+"/"),E([]));return}if(h.return){let f=k.trim();f&&f.startsWith("/")?(a(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:f,mode:"rw"}]}),s(""),E([]),n("edit-dirs")):O("Path must be absolute (must start with /)","error");return}if(h.tab){let f=k.trim();if(!f||!f.startsWith("/"))return;S(`/fs/suggest-dirs?prefix=${encodeURIComponent(f)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),E([])):P.length>1&&(E(P),A(0))}).catch(()=>{E([])});return}if(h.upArrow&&c.length>0){A(f=>Math.max(0,f-1));return}if(h.downArrow&&c.length>0){A(f=>Math.min(c.length-1,f+1));return}break}case"edit-tools":{if(m==="s"){ks();return}let f=parseInt(m,10)-1;if(!isNaN(f)&&f>=0&&f<Mr.length){let P=Mr[f];X(U=>{let pe=new Set(U);return pe.has(P)?pe.delete(P):pe.add(P),pe});return}break}case"edit-oscaps":{if(m==="s"){Es();return}if(m==="a"&&Kt.some(U=>U.id==="automation")){let U=Kt.find(pe=>pe.id==="automation")?.targets??[];co(U.join(", ")),n("edit-oscaps-targets");return}let f=ao.filter(U=>U.editable),P=parseInt(m,10)-1;if(!isNaN(P)&&P>=0&&P<f.length){let U=f[P];lo(pe=>pe.some(ur=>ur.id===U.id)?pe.filter(ur=>ur.id!==U.id):[...pe,{id:U.id,targets:U.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(h.return){let f=No.split(",").map(P=>P.trim()).filter(Boolean);lo(P=>P.map(U=>U.id==="automation"?{...U,targets:f}:U)),n("edit-oscaps");return}break}case"edit-exec":{if(m==="s"){Bs();return}if(h.tab){F(f=>f==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(m==="s"){Is();return}if(h.tab){$(f=>f==="mode"?"allowed":f==="allowed"?"denied":"mode");return}if(he==="mode"&&(h.upArrow||h.downArrow)){let f=["default","acceptEdits","dontAsk","bypassPermissions"],P=f.indexOf(V);h.upArrow&&x(f[Math.max(0,P-1)]),h.downArrow&&x(f[Math.min(f.length-1,P+1)]);return}break}case"edit-channels":{if(m==="s"){if(!r)return;let f=ne.size>0?Array.from(ne):[];S(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:f}}).then(()=>{O("Channels saved","success"),n("view"),ae()}).catch(()=>O("Save failed","error"));return}if(m==="u"){if(!r)return;S(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{O("Channels: unrestricted","success"),n("view"),ae()}).catch(()=>O("Save failed","error"));return}if(m===" "){let f=Re[se];f&&_(P=>{let U=new Set(P);return U.has(f.name)?U.delete(f.name):U.add(f.name),U});return}if(h.upArrow){Ce(f=>Math.max(0,f-1));return}if(h.downArrow){Ce(f=>Math.min(Re.length-1,f+1));return}break}case"edit-env":{let f=Object.keys(r?.envVars??{});if(m==="a"){_o(""),n("edit-env-add-key");return}if(m==="d"&&f.length>0){let P=f[$t],U={...r?.envVars??{}};delete U[P],S(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{O("Deleted","success"),ae()}).catch(()=>O("Delete failed","error")),$t>=f.length-1&&$t>0&&Ir(pe=>pe-1);return}if(h.return&&f.length>0){qo((r?.envVars??{})[f[$t]]??""),n("edit-env-edit-value");return}h.upArrow&&$t>0&&Ir(P=>P-1),h.downArrow&&$t<f.length-1&&Ir(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break;case"edit-plugins":{if(Rr)return;if(m==="a"){S("/plugins").then(({plugins:f})=>{let P=new Set(o.map(U=>U.id));Vo(f.filter(U=>!P.has(U.id))),mo(0),n("edit-plugins-add")}).catch(()=>O("Failed to load plugins","error"));return}if(m==="x"&&o.length>0){let f=o[Ar];f&&Ps(f.id);return}if(h.upArrow){uo(f=>Math.max(0,f-1));return}if(h.downArrow){uo(f=>Math.min(o.length-1,f+1));return}break}case"edit-plugins-add":{if(Rr)return;if(h.escape){n("edit-plugins"),Vo([]);return}if(h.return&&dr.length>0){let f=dr[Pr];f&&As(f.id);return}if(h.upArrow){mo(f=>Math.max(0,f-1));return}if(h.downArrow){mo(f=>Math.min(dr.length-1,f+1));return}break}}}),d)return y(T,{dimColor:!0,children:"Loading role..."});if(!r)return y(T,{dimColor:!0,children:"Role not found."});if(i==="edit-plugins")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Plugins (\u2191\u2193 navigate, x:unbind a:add Esc:cancel)"}),Rr&&y(T,{dimColor:!0,children:"Binding..."}),o.length===0?y(T,{dimColor:!0,children:"No plugins bound. Press a to add."}):o.map((m,h)=>B(D,{children:[B(T,{color:h===Ar?"cyan":void 0,bold:h===Ar,children:[h===Ar?"> ":" ",m.name]}),B(T,{dimColor:!0,children:[" v",m.version]})]},m.id)),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i==="edit-plugins-add")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Add Plugin (\u2191\u2193 navigate, Enter:bind Esc:cancel)"}),Rr&&y(T,{dimColor:!0,children:"Binding..."}),dr.length===0?y(T,{dimColor:!0,children:"No available plugins."}):dr.map((m,h)=>B(D,{children:[B(T,{color:h===Pr?"cyan":void 0,bold:h===Pr,children:[h===Pr?"> ":" ",m.name]}),B(T,{dimColor:!0,children:[" v",m.version]})]},m.id)),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i==="edit-cag")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),y(at,{value:p,onChange:g,placeholder:"Character And Guidance prompt..."}),L&&y(D,{marginTop:1,children:y(T,{color:L.type==="error"?"red":"green",children:L.text})})]});if(i==="edit-dirs-add")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),y(at,{value:k,onChange:m=>{s(m),E([])},placeholder:"/absolute/path/to/directory"}),c.length>0&&B(D,{flexDirection:"column",marginTop:1,children:[c.map((m,h)=>B(T,{color:h===C?"cyan":void 0,dimColor:h!==C,children:[h===C?"> ":" ",m,"/"]},m)),y(T,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),L&&y(D,{marginTop:1,children:y(T,{color:L.type==="error"?"red":"green",children:L.text})})]});if(i==="edit-dirs")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),rt.length===0?y(T,{dimColor:!0,children:"No directories. Press a to add one."}):rt.map((m,h)=>{let f=typeof m=="string"?{path:m,mode:"rw"}:m,P=f.mode!=="ro";return B(D,{children:[y(T,{color:h===v?"cyan":void 0,bold:h===v,children:h===v?"> ":" "}),B(T,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),y(T,{color:h===v?"cyan":void 0,children:f.path})]},f.path)})]});if(i==="edit-tools")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),Mr.map((m,h)=>{let f=W.has(m);return B(D,{children:[B(T,{dimColor:!0,children:[h+1,". "]}),y(T,{color:f?"green":"red",children:f?"[ON] ":"[OFF] "}),y(T,{children:m})]},m)})]});if(i==="edit-oscaps"){let m=ao.filter(h=>h.editable);return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),jt&&B(T,{dimColor:!0,children:["Platform: ",jt.platform," ",jt.available?"(sandbox active)":"(sandbox unavailable)"]}),ao.map(h=>{let f=m.findIndex(Tt=>Tt.id===h.id),P=Kt.some(Tt=>Tt.id===h.id),U=f>=0?`${f+1}.`:" -",pe=h.id==="automation"?(()=>{let Tt=Kt.find(ur=>ur.id===h.id)?.targets??[];return Tt.length>0?` targets: ${Tt.join(", ")}`:" targets: (none)"})():"";return B(D,{flexDirection:"column",marginBottom:1,children:[B(T,{color:P?"green":h.editable?"red":"gray",children:[U," ",P?"[ON]":"[OFF]"," ",h.label," [",h.availability,"]"]}),B(T,{dimColor:!0,children:[" ",h.description,pe]}),h.effectiveDisabledReason&&!h.editable&&B(T,{dimColor:!0,children:[" ",h.effectiveDisabledReason]})]},h.id)}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]})}if(i==="edit-oscaps-targets")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),y(at,{value:No,onChange:co,placeholder:"com.apple.mail, com.apple.systemevents"}),y(T,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i==="edit-exec")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(D,{children:[y(T,{bold:!0,children:" Mode: "}),y(T,{color:"cyan",children:N}),y(T,{dimColor:!0,children:" (Tab to toggle)"})]}),B(D,{children:[y(T,{bold:!0,children:" Model: "}),y(at,{value:q,onChange:I,placeholder:"sonnet, opus, haiku, or blank"})]}),B(D,{children:[y(T,{bold:!0,children:" Effort Tier: "}),y(at,{value:H,onChange:oe,placeholder:"low, medium, high, or blank to inherit"})]}),B(D,{children:[y(T,{bold:!0,children:" Max Budget (USD): "}),y(at,{value:Q,onChange:Me,placeholder:"0 = unlimited"})]}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i==="edit-permissions")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(D,{children:[y(T,{bold:!0,color:he==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(h=>B(T,{color:h===V?"green":"gray",children:[h===V?`[${h}]`:` ${h} `," "]},h))]}),B(D,{children:[y(T,{bold:!0,color:he==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),he==="allowed"?y(at,{value:w,onChange:R,placeholder:"git add *, pnpm test*"}):y(T,{children:w||"(none)"})]}),B(D,{children:[y(T,{bold:!0,color:he==="denied"?"cyan":void 0,children:" Denied Bash: "}),he==="denied"?y(at,{value:Z,onChange:ge,placeholder:"rm -rf *, ssh *"}):y(T,{children:Z||"(none)"})]}),y(T,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i==="edit-channels")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Re.length===0?y(T,{dimColor:!0,children:"No channels available"}):Re.map((m,h)=>B(D,{children:[B(T,{children:[h===se?">":" "," "]}),B(T,{color:ne.has(m.name)?"green":"gray",children:["[",ne.has(m.name)?"x":" ","] ",m.name]})]},m.id)),B(T,{dimColor:!0,children:["Selected: ",ne.size>0?Array.from(ne).join(", "):"none (= block all)"]}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(i.startsWith("edit-env")){let m=Object.keys(r.envVars??{});return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Environment Variables (",m.length,")"]}),m.length===0&&i==="edit-env"&&y(T,{dimColor:!0,children:" No env vars. Press a to add."}),m.map((h,f)=>{let P=f===$t;return i==="edit-env-edit-value"&&P?B(D,{children:[B(T,{color:"cyan",children:["> ",h," = "]}),y(at,{value:Oo,onChange:qo,onSubmit:()=>{let U={...r.envVars??{},[h]:Oo};S(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{O("Saved","success"),ae(),n("edit-env")}).catch(()=>O("Save failed","error"))}})]},h):B(T,{color:P&&i==="edit-env"?"cyan":"white",children:[P&&i==="edit-env"?"> ":" ",h," = ",(r.envVars??{})[h]]},h)}),i==="edit-env-add-key"&&B(D,{children:[y(T,{color:"green",children:" New key: "}),y(at,{value:Er,onChange:_o,onSubmit:()=>{Er.trim()&&(Fo(""),n("edit-env-add-value"))}})]}),i==="edit-env-add-value"&&B(D,{children:[B(T,{color:"green",children:[" ",Er," = "]}),y(at,{value:Lo,onChange:Fo,onSubmit:()=>{let h={...r.envVars??{},[Er.trim()]:Lo};S(`/roles/${r.id}`,{method:"PATCH",body:{envVars:h}}).then(()=>{O("Added","success"),ae(),n("edit-env")}).catch(()=>O("Add failed","error"))}})]}),y(T,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),L&&y(T,{color:L.type==="error"?"red":"green",children:L.text})]})}return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Role: ",r.name]}),B(D,{children:[y(T,{dimColor:!0,children:"ID: "}),y(T,{children:r.id})]}),B(D,{children:[y(T,{dimColor:!0,children:"Status: "}),y(T,{color:r.status==="active"?"green":r.status==="probation"?"yellow":"red",children:r.status})]}),r.performanceScore!=null&&B(D,{children:[y(T,{dimColor:!0,children:"Score: "}),B(T,{children:[(r.performanceScore*100).toFixed(0),"%"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"Created: "}),y(T,{children:new Date(r.createdAt).toLocaleString()})]}),B(D,{children:[y(T,{dimColor:!0,children:"Execution: "}),B(T,{children:[r.executionMode??"inline"," / tier:",r.effortTier??"\u2014"," / model:",r.model??"inherit"," / ",r.maxBudgetUsd!=null?`$${r.maxBudgetUsd}`:"no limit"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"OS Capabilities: "}),y(T,{children:(r.osCapabilities?.length??0)>0?r.osCapabilities.map(m=>m.id==="automation"&&m.targets?.length?`automation(${m.targets.join(",")})`:m.id).join(", "):"None"})]}),jt&&B(D,{children:[y(T,{dimColor:!0,children:"Sandbox Platform: "}),B(T,{children:[jt.platform," ",jt.available?"(active)":"(unavailable)"]})]}),rt.length>0&&B(eo,{children:[y(T,{bold:!0,children:"Additional Directories:"}),rt.map(m=>B(T,{dimColor:!0,children:[" ",m.path]},m.path))]}),B(D,{children:[y(T,{dimColor:!0,children:"Permission: "}),y(T,{children:r.permissionMode??"default"})]}),(r.allowedBashPatterns?.length??0)>0&&B(D,{children:[y(T,{dimColor:!0,children:" Bash Allow: "}),y(T,{children:r.allowedBashPatterns.join(", ")})]}),(r.deniedBashPatterns?.length??0)>0&&B(D,{children:[y(T,{dimColor:!0,children:" Bash Deny: "}),y(T,{children:r.deniedBashPatterns.join(", ")})]}),Gt.length>0&&B(D,{flexDirection:"column",children:[y(T,{dimColor:!0,children:"Denied Read Paths (global):"}),Gt.map(m=>B(T,{dimColor:!0,children:[" ",m]},m)),B(T,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"Channels: "}),y(T,{children:r.allowedChannels===void 0?"Unrestricted":r.allowedChannels.length===0?"Blocked":r.allowedChannels.join(", ")})]}),B(D,{children:[y(T,{dimColor:!0,children:"Inherit User Settings: "}),y(T,{color:r.inheritUserSettings?"green":"gray",children:r.inheritUserSettings?"Yes":"No"})]}),r.learnedRules.stylePreferences.length>0&&B(eo,{children:[y(T,{bold:!0,children:"Style Preferences:"}),r.learnedRules.stylePreferences.map(m=>B(T,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.avoidedActions.length>0&&B(eo,{children:[y(T,{bold:!0,children:"Avoided Actions:"}),r.learnedRules.avoidedActions.map(m=>B(T,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.pinnedParameters.length>0&&B(eo,{children:[y(T,{bold:!0,children:"Pinned Parameters:"}),r.learnedRules.pinnedParameters.map(m=>{let h=Object.entries(m.params).map(([P,U])=>`${P}=${JSON.stringify(U)}`).join(", "),f=m.condition?` [when: ${m.condition}]`:"";return B(T,{dimColor:!0,children:[" - ",m.tool," \u2192 ",h,f]},`${m.tool}-${m.pinnedAt}`)})]}),B(D,{children:[y(T,{dimColor:!0,children:"Plugins: "}),o.length===0?y(T,{dimColor:!0,children:"None"}):o.map(m=>B(T,{children:[m.name," "]},m.id))]}),L&&y(D,{children:y(T,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),y(D,{marginTop:1,children:B(T,{dimColor:!0,children:["c:CAG d:dirs t:tools b:plugins o:oscaps x:exec p:perms h:channels v:env i:inherit"," ",r?.presetId?"R:restore-preset ":"","r:refresh Esc:back"]})})]})}import{jsx as He,jsxs as wr}from"react/jsx-runtime";function ss({onBack:e}){let[t,r]=Sr([]),[a,o]=Sr(!0),[u,d]=Sr(0),[l,i]=Sr("list"),[n,p]=Sr(null),{message:g,setMessage:v,clearMessage:b}=Je(),k=Ra(()=>{o(!0),S("/roles").then(({roles:s})=>{r(s.map(c=>({id:c.id,name:c.name,status:c.status,performanceScore:c.performanceScore,createdAt:c.createdAt,presetId:c.presetId,contractComplianceEma:c.contractComplianceEma}))),o(!1)}).catch(()=>o(!1))},[]);return Pa(()=>{k()},[k]),Aa((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(E=>Math.max(0,E-1));return}if(c.downArrow){d(E=>Math.min(t.length-1,E+1));return}if(s==="r"&&(k(),b()),s===`
11
+ `||s==="o"||s==="e"){t.length>0&&(p(t[u].id),i("detail"));return}}),a?He(lt,{dimColor:!0,children:"Loading roles..."}):l==="detail"&&n?He(ns,{roleId:n,onBack:()=>i("list")}):wr(nr,{flexDirection:"column",children:[wr(lt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),g&&He(nr,{marginTop:1,children:wr(lt,{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?He(nr,{marginTop:1,children:He(lt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):He(nr,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let E=c===u,C=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014",A=s.contractComplianceEma!=null?`[\u5951\u7EA6 ${s.contractComplianceEma.toFixed(2)}]`:"[\u5951\u7EA6 \u2014]";return wr(nr,{children:[He(lt,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),He(lt,{color:E?"cyan":void 0,bold:E,children:Ro(s.name,24)}),s.presetId&&wr(lt,{dimColor:!0,children:["[",s.presetId,"]"]}),He(lt,{color:Da(s.status),children:Ro(s.status,12)}),He(lt,{dimColor:!0,children:Ro(C,8)}),He(lt,{dimColor:!0,children:A})]},s.id)})}),He(nr,{marginTop:1,children:He(lt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function Da(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Ro(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ma,Text as Do}from"ink";import $a from"react";import{jsx as to,jsxs as _a}from"react/jsx-runtime";var We={key:"Esc",label:"back"},Na={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},We],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},We],config:[We],evolution:[We],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},We],strategies:[We],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"},We],webhooks:[We],memories:[We],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},We],roles:[We],settings:[We],channels:[We]};function is(){let{state:e}=Ye(),t=Na[e.view]??[We];return to(Ma,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((r,a)=>_a($a.Fragment,{children:[a>0&&to(Do,{dimColor:!0,children:" "}),to(Do,{color:"cyan",children:r.key}),to(Do,{dimColor:!0,children:` ${r.label}`})]},`${r.key}-${r.label}`))})}import{Box as sr,Text as et,useInput as La}from"ink";import{useEffect as Fa,useState as ro,useCallback as Oa}from"react";import{jsx as kt,jsxs as wt}from"react/jsx-runtime";function as({onBack:e}){let[t,r]=ro([]),[a,o]=ro(!0),[u,d]=ro(0),[l,i]=ro("all"),{message:n,setMessage:p}=Je(),g=Oa(()=>{o(!0);let c=l!=="all"?`?status=${l}`:"";S(`/feature-requests${c}`).then(({featureRequests:E})=>{r(E),d(0),o(!1)}).catch(()=>o(!1))},[l]);Fa(()=>{g()},[g]);let v=async(c,E)=>{try{await S(`/feature-requests/${c}/status`,{method:"PATCH",body:{status:E}}),p(`Marked as ${E}`,"success"),await g()}catch(C){p(`Failed: ${C instanceof Error?C.message:String(C)}`,"error")}},b=t;La((c,E)=>{if(E.escape||c==="q"){e();return}if(E.upArrow){d(A=>Math.max(0,A-1));return}if(E.downArrow){d(A=>Math.min(b.length-1,A+1));return}if(c==="r"){g();return}let C={0:"all",1:"new",2:"reviewed",3:"dismissed",4:"converted"};if(C[c]){i(C[c]);return}if(c==="s"&&b.length>0){let A=b[u];if(A&&A.status==="new"){v(A.id,"reviewed");return}}if(c==="d"&&b.length>0){let A=b[u];if(A){v(A.id,"dismissed");return}}if(c==="c"&&b.length>0){let A=b[u];if(A){v(A.id,"converted");return}}});let k=c=>c==="new"?"cyan":c==="reviewed"?"green":c==="dismissed"?"gray":c==="converted"?"yellow":"white",s=c=>{let E=Date.now()-c;if(Math.floor(E/6e4)<1)return"now";let A=Math.floor(E/36e5);return A<24?`${A}h ago`:`${Math.floor(A/24)}d ago`};return wt(sr,{flexDirection:"column",children:[wt(et,{bold:!0,children:["Feature Requests (",b.length,") (Esc:back q:quit r:refresh)"]}),n&&kt(sr,{marginTop:1,children:wt(et,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),kt(et,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),kt(et,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),a?kt(et,{dimColor:!0,children:"Loading..."}):b.length===0?kt(et,{dimColor:!0,children:"No feature requests found."}):kt(sr,{marginTop:1,flexDirection:"column",children:b.map((c,E)=>{let C=E===u,A=c.content.length>80?c.content.slice(0,80)+"...":c.content;return wt(sr,{flexDirection:"column",children:[wt(sr,{children:[kt(et,{color:C?"cyan":void 0,bold:C,children:C?"> ":" "}),wt(et,{color:k(c.status),children:["[",c.status,"]"]}),wt(et,{dimColor:!0,children:[" ",s(c.extractedAt)]}),c.tags&&c.tags.length>0&&wt(et,{dimColor:!0,children:[" ",c.tags.slice(0,3).join(", ")]})]}),wt(sr,{paddingLeft:4,flexDirection:"column",children:[c.summary&&kt(et,{color:C?"cyan":"white",children:c.summary}),kt(et,{dimColor:!0,children:A})]})]},c.id)})})]})}import{Box as ir,Text as ze,useInput as qa}from"ink";import{useEffect as Va,useState as oo,useCallback as Ua}from"react";import{jsx as Bt,jsxs as xt}from"react/jsx-runtime";function ls({onBack:e}){let[t,r]=oo([]),[a,o]=oo(!0),[u,d]=oo(0),[l,i]=oo("all"),{message:n,setMessage:p}=Je(),g=Ua(()=>{o(!0);let s=l!=="all"?`?status=${l}`:"";S(`/mistake-patterns${s}`).then(({mistakePatterns:c})=>{r(c),d(0),o(!1)}).catch(()=>o(!1))},[l]);Va(()=>{g()},[g]);let v=async(s,c)=>{try{await S(`/mistake-patterns/${s}`,{method:"PATCH",body:{status:c}}),p(`Marked as ${c}`,"success"),await g()}catch(E){p(`Failed: ${E instanceof Error?E.message:String(E)}`,"error")}};qa((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(C=>Math.max(0,C-1));return}if(c.downArrow){d(C=>Math.min(t.length-1,C+1));return}if(s==="r"){g();return}let E={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(E[s]){i(E[s]);return}if(s==="a"&&t.length>0){let C=t[u];if(C&&C.status!=="acknowledged"){v(C.id,"acknowledged");return}}if(s==="d"&&t.length>0){let C=t[u];if(C&&C.status!=="dismissed"){v(C.id,"dismissed");return}}if(s==="n"&&t.length>0){let C=t[u];if(C&&C.status!=="new"){v(C.id,"new");return}}});let b=s=>s==="new"?"cyan":s==="acknowledged"?"green":s==="dismissed"?"gray":"white",k=s=>{let c=Date.now()-s;if(Math.floor(c/6e4)<1)return"now";let C=Math.floor(c/36e5);return C<24?`${C}h ago`:`${Math.floor(C/24)}d ago`};return xt(ir,{flexDirection:"column",children:[xt(ze,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),n&&Bt(ir,{marginTop:1,children:xt(ze,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),Bt(ze,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),Bt(ze,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),a?Bt(ze,{dimColor:!0,children:"Loading..."}):t.length===0?Bt(ze,{dimColor:!0,children:"No mistake patterns found."}):Bt(ir,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let E=c===u,C=s.dimensionValue.length>80?s.dimensionValue.slice(0,80)+"...":s.dimensionValue;return xt(ir,{flexDirection:"column",children:[xt(ir,{children:[Bt(ze,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),xt(ze,{color:b(s.status),children:["[",s.status,"]"]}),xt(ze,{dimColor:!0,children:[" ",k(s.lastSeen)]}),xt(ze,{dimColor:!0,children:[" [",s.dimensionType,"]"]}),xt(ze,{dimColor:!0,children:[" ",s.roleIds.length," role(s)"]}),xt(ze,{dimColor:!0,children:[" x",s.count]})]}),Bt(ir,{paddingLeft:4,flexDirection:"column",children:Bt(ze,{color:E?"cyan":"white",children:C})})]},s.id)})})]})}import{Box as It,Text as ve,useInput as ps}from"ink";import{useEffect as tl,useState as ct,useCallback as xs,useRef as Ts}from"react";import{readFileSync as Wa,existsSync as Ga}from"fs";import{join as ja}from"path";import{homedir as Ka}from"os";function Ha(){if(process.env.ADAM_API_KEY)return process.env.ADAM_API_KEY;let e=ja(Ka(),".adam","adam.key");if(Ga(e))return Wa(e,"utf8").trim();throw new Error("ADAM_API_KEY env or ~/.adam/adam.key required")}function za(){return Number(process.env.ADAM_PORT??7100)}async function no(e,t={}){let r={"x-api-key":Ha(),...t.headers??{}};t.body&&(r["Content-Type"]??="application/json");let a=await fetch(`http://localhost:${za()}${e}`,{...t,headers:r});if(!a.ok)throw new Error(`${a.status}: ${await a.text()}`);if(a.status!==204)return a.json()}function cs(e={}){let t=new URLSearchParams(Object.entries(e).map(([r,a])=>[r,String(a)])).toString();return no(`/artifacts${t?"?"+t:""}`)}function ds(e){return no(`/artifacts/${encodeURIComponent(e)}`)}function Mo(e,t=!1){return no(`/artifacts/${encodeURIComponent(e)}${t?"?confirm=true":""}`,{method:"DELETE"})}function us(e,t){return no(`/artifacts/${encodeURIComponent(e)}/redeliver`,{method:"POST",body:JSON.stringify(t)})}import{spawn as Xa}from"child_process";async function ms(e){let t=process.platform==="darwin"?"pbcopy":process.platform==="linux"?"xclip":null;return t?new Promise(r=>{try{let a=process.platform==="linux"?["-selection","clipboard"]:[],o=Xa(t,a);o.on("error",()=>r(!1)),o.on("close",u=>r(u===0)),o.stdin.write(e),o.stdin.end()}catch{r(!1)}}):!1}import{Box as ar,Text as Dt,useInput as Ya}from"ink";import{jsx as Te,jsxs as qt}from"react/jsx-runtime";function Qa(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}function Ja(e){return new Date(e).toLocaleString()}function Xe({label:e,value:t}){return qt(ar,{children:[Te(Dt,{dimColor:!0,children:e.padEnd(20)}),Te(Dt,{color:"cyan",children:t})]})}function fs({artifact:e,deliveryLog:t,onBack:r}){return Ya((a,o)=>{o.escape&&r()}),qt(ar,{flexDirection:"column",children:[Te(Dt,{bold:!0,children:"Artifact Detail (Esc to go back)"}),qt(ar,{flexDirection:"column",marginTop:1,children:[Te(Xe,{label:"ID",value:e.id}),Te(Xe,{label:"Source",value:e.sourceKind}),Te(Xe,{label:"Role",value:e.producedByRole??e.roleId??"\u2014"}),Te(Xe,{label:"Mime",value:e.mime??"\u2014"}),Te(Xe,{label:"Kind",value:e.kind}),Te(Xe,{label:"Size",value:Qa(e.sizeBytes)}),Te(Xe,{label:"Created",value:Ja(e.createdAt)}),Te(Xe,{label:"Key",value:e.key??"\u2014"}),Te(Xe,{label:"Blob path",value:e.blobPath??"\u2014"}),e.executionId&&Te(Xe,{label:"Execution ID",value:e.executionId}),e.taskId&&Te(Xe,{label:"Task ID",value:e.taskId}),e.chatSessionId&&Te(Xe,{label:"Chat Session",value:e.chatSessionId}),e.originalFilename&&Te(Xe,{label:"Filename",value:e.originalFilename})]}),t.length>0&&qt(ar,{flexDirection:"column",marginTop:1,children:[qt(Dt,{bold:!0,dimColor:!0,children:["Delivery Log (",t.length,")"]}),t.map((a,o)=>qt(ar,{children:[Te(Dt,{dimColor:!0,children:" "}),Te(Dt,{color:a.status==="delivered"?"green":a.status==="failed"?"red":"yellow",children:a.status}),qt(Dt,{dimColor:!0,children:[" \u2192 ",a.target?.channelId??"\u2014",a.createdAt?` (${new Date(a.createdAt).toLocaleTimeString()})`:""]})]},o))]}),t.length===0&&Te(ar,{marginTop:1,children:Te(Dt,{dimColor:!0,children:"No delivery log entries."})})]})}import{Box as so,Text as Mt,useInput as Za}from"ink";import{useEffect as el,useState as $o}from"react";import{jsx as Vt,jsxs as kr}from"react/jsx-runtime";function gs({onSelect:e,onCancel:t,fetchChannels:r}){let[a,o]=$o([]),[u,d]=$o(!0),[l,i]=$o(null);return el(()=>{r().then(n=>{o(n.channels),d(!1)}).catch(n=>{i(`Failed to load channels: ${n instanceof Error?n.message:String(n)}`),d(!1)})},[r]),Za((n,p)=>{if(p.escape){t();return}let g=parseInt(n,10);if(!isNaN(g)&&g>=1&&g<=a.length){let v=a[g-1];v&&e(v.id)}}),u?Vt(so,{children:Vt(Mt,{dimColor:!0,children:"Loading channels..."})}):l?kr(so,{children:[Vt(Mt,{color:"red",children:l}),Vt(Mt,{dimColor:!0,children:" (Esc to cancel)"})]}):kr(so,{flexDirection:"column",children:[Vt(Mt,{bold:!0,children:"Select channel to redeliver (Esc to cancel):"}),a.length===0?Vt(Mt,{dimColor:!0,children:"No channels configured."}):a.map((n,p)=>kr(so,{children:[kr(Mt,{children:["[",p+1,"] "]}),Vt(Mt,{color:"cyan",children:n.name}),kr(Mt,{dimColor:!0,children:[" (",n.platform,")"]})]},n.id))]})}import{jsx as ue,jsxs as Ut}from"react/jsx-runtime";function rl(e){return e?e.replace(/[\x00-\x1F\x7F]/g,""):""}function tt(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}function ol(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(0)}K`:`${(e/(1024*1024)).toFixed(1)}M`}function nl(e){let t=Date.now()-e,r=Math.floor(t/1e3),a=Math.floor(r/60),o=Math.floor(a/60);if(r<60)return"just now";if(a<60)return`${a}m ago`;if(o<24)return`${o}h ago`;let u=new Date(e);return`${String(u.getMonth()+1).padStart(2,"0")}-${String(u.getDate()).padStart(2,"0")}`}function sl(e){return e==="template_step"?"tmpl":e==="task_published"?"task":e==="chat_sent"?"chat":e.slice(0,6)}function hs({onBack:e,onSelect:t,onAction:r}){let{dispatch:a}=Ye(),[o,u]=ct([]),[d,l]=ct(0),[i,n]=ct(!0),[p,g]=ct(null),[v,b]=ct(0),[k,s]=ct("list"),[c,E]=ct(null),[C,A]=ct([]),[W,X]=ct(null),[N,F]=ct(null),[q,I]=ct(null),H=Ts(null),oe=Ts(null);function Q(M){I(M),oe.current&&clearTimeout(oe.current),oe.current=setTimeout(()=>I(null),2e3)}let Me=xs(()=>{H.current&&H.current.abort(),H.current=new AbortController,n(!0),g(null),cs({limit:100}).then(M=>{u(M.artifacts),l(M.total),b(0),n(!1)}).catch(M=>{M.name!=="AbortError"&&(g(`Failed to load: ${M instanceof Error?M.message:String(M)}`),n(!1))})},[]);tl(()=>(Me(),()=>{H.current&&H.current.abort(),oe.current&&clearTimeout(oe.current)}),[Me]),ps((M,ne)=>{if(W)if(M==="y"){let _=W;X(null),Mo(_.id,!0).then(()=>{Q("Deleted"),Me()}).catch(se=>Q(`Delete failed: ${se instanceof Error?se.message:String(se)}`))}else(M==="n"||ne.escape)&&X(null)}),ps((M,ne)=>{if(W||N)return;if(ne.escape||M==="q"){e();return}if(ne.upArrow||M==="k"){b(se=>Math.max(0,se-1));return}if(ne.downArrow||M==="j"){b(se=>Math.min(Math.max(0,o.length-1),se+1));return}if(M==="\r"||M===`
12
+ `||M==="o"){if(o.length>0&&o[v]){let se=o[v];t(se),ds(se.id).then(Ce=>{E(Ce.artifact),A(Ce.deliveryLog),s("detail")}).catch(()=>{E(se),A([]),s("detail")})}return}let _=o.length>0?o[v]:void 0;if(_){if(M==="d"){r("d",_),fo(_.mime)?X(_):Mo(_.id,!1).then(()=>{Q("Deleted"),Me()}).catch(Ce=>Q(`Delete failed: ${Ce instanceof Error?Ce.message:String(Ce)}`));return}if(M==="r"){r("r",_),F(_);return}if(M==="c"){r("c",_);let se=_.blobPath??"";ms(se).then(Ce=>{Q(Ce?`Copied: ${se.slice(-40)}`:"Clipboard unavailable")}).catch(()=>Q("Clipboard unavailable"));return}if(M==="t"){r("t",_);let se=_.taskId??_.executionId;a({type:"SET_VIEW",view:"tasks",selectedTaskId:se});return}}});let Re=xs(()=>{let{getApiKey:M,getPort:ne}={getApiKey:()=>process.env.ADAM_API_KEY??"",getPort:()=>Number(process.env.ADAM_PORT??7100)};return fetch(`http://localhost:${ne()}/channels`,{headers:{"x-api-key":M()}}).then(_=>_.json())},[]);if(k==="detail"&&c)return ue(fs,{artifact:c,deliveryLog:C,onBack:()=>s("list")});if(N){let M=N;return ue(gs,{fetchChannels:Re,onSelect:ne=>{F(null),us(M.id,{channelId:ne}).then(_=>Q(`Redeliver queued: ${_.status}`)).catch(_=>Q(`Redeliver failed: ${_ instanceof Error?_.message:String(_)}`))},onCancel:()=>F(null)})}return i?Ut(It,{flexDirection:"column",children:[ue(ve,{bold:!0,children:"Artifacts"}),ue(ve,{dimColor:!0,children:"Loading..."})]}):p?Ut(It,{flexDirection:"column",children:[ue(ve,{bold:!0,children:"Artifacts"}),ue(ve,{color:"red",children:p}),ue(ve,{dimColor:!0,children:"Press Esc to go back or r to retry"})]}):Ut(It,{flexDirection:"column",children:[Ut(ve,{bold:!0,children:["Artifacts (",d,") (Esc to go back)"]}),ue(It,{children:Ut(ve,{dimColor:!0,bold:!0,children:[" ",tt("#",3),tt("Source",12),tt("Role",12),tt("Mime",16),tt("Size",8),tt("Created",16),"Delivered"]})}),o.length===0?ue(It,{marginTop:1,children:ue(ve,{dimColor:!0,children:"No artifacts found."})}):o.map((M,ne)=>{let _=ne===v,se=M.mime??"unknown",Ce=M.producedByRole??M.roleId??"\u2014";return Ut(It,{children:[ue(ve,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),ue(ve,{color:_?"cyan":void 0,bold:_,children:tt(String(ne+1),3)}),ue(ve,{color:_?"cyan":void 0,children:tt(sl(M.sourceKind),12)}),ue(ve,{color:_?"cyan":void 0,children:tt(rl(Ce).slice(0,11),12)}),ue(ve,{color:_?"cyan":void 0,children:tt(se.slice(0,15),16)}),ue(ve,{color:_?"cyan":void 0,children:tt(ol(M.sizeBytes),8)}),ue(ve,{color:_?"cyan":void 0,children:tt(nl(M.createdAt),16)}),ue(ve,{color:_?"cyan":void 0,children:"\u2014"})]},M.id)}),W&&ue(It,{marginTop:1,children:Ut(ve,{color:"red",children:["Delete this ",fo(W.mime)," file? (y/n)"]})}),q&&!W&&ue(It,{marginTop:1,children:ue(ve,{color:"green",children:q})}),ue(It,{marginTop:1,children:ue(ve,{dimColor:!0,children:"j/k=navigate enter=detail d=delete r=redeliver c=copy t=task"})})]})}import{Fragment as ml,jsx as J,jsxs as cr}from"react/jsx-runtime";function cl(){let{state:e,dispatch:t}=Ye(),{session:r,sendMessage:a,createNewSession:o,archiveCurrentSession:u}=Zo(),[d,l]=al([]);io(()=>{t({type:"SET_SESSION",session:r})},[r,t]),Yo();let{latestMessage:i}=tn(r?.id??null),n=Wt(null),p=Wt(new Set),g=Wt(new Set),v=Wt(new Set),b=Wt(new Set),[,k]=ll(I=>I+1,0);io(()=>{if(!i||i.id===n.current)return;n.current=i.id;let I=!i.kind||i.kind==="result_delivery"||i.kind==="assistant_text";if(I&&i.taskId&&g.current.has(i.taskId)){p.current.add(i.taskId);return}I&&i.taskId&&p.current.add(i.taskId),l(H=>[...H,{id:i.id,role:"assistant",content:i.content,taskId:i.taskId,createdAt:i.createdAt,kind:i.kind,threadRoot:i.threadRoot,parentMessageId:i.parentMessageId,promptId:i.promptId,approvalShape:i.approvalShape,roleId:i.roleId,attachments:i.attachments,mirroredToTargets:i.mirroredToTargets,platformMessageId:i.platformMessageId,seq:i.seq}])},[i]);let{events:s,isStreaming:c,clearEvents:E}=Jo(e.activeTaskId),C=s[s.length-1],A=C?.type==="complete"&&!c,W=Wt(null),X=Wt("");io(()=>{X.current=s.filter(I=>I.type==="reasoning").map(I=>I.content).join("")},[s]),io(()=>{if(A&&e.activeTaskId!==W.current){if(W.current=e.activeTaskId,e.activeTaskId&&p.current.has(e.activeTaskId))return;let I=C?.content||X.current;I&&(e.activeTaskId&&g.current.add(e.activeTaskId),l(H=>[...H,{role:"assistant",content:I,taskId:e.activeTaskId??void 0,kind:"assistant_text"}]))}},[A,C,e.activeTaskId]);let N=async I=>{let H=I.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),I.startsWith("/")){let Q=I.slice(1),Re={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",artifacts:"artifacts",back:"chat"}[Q];if(Re){t({type:"SET_VIEW",view:Re});return}if(Q==="new"){if(await u()){let ne=await o();l([]),E(),p.current.clear(),g.current.clear(),v.current.clear(),b.current.clear(),ne&&l([{role:"assistant",content:`Session archived. New session started: ${ne.id.slice(0,8)}`}])}return}if(Q==="session"){let M=r?`Session: ${r.id}
13
+ Turns: ${r.messageCount}
14
+ Last active: ${new Date(r.lastActiveAt).toLocaleString()}`:"No active session";l(ne=>[...ne,{role:"assistant",content:M}]);return}}if(l(Q=>[...Q,{role:"user",content:I}]),E(),!await a(I)){l(Q=>[...Q,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},F=d.some(I=>I.kind==="approval_prompt"&&I.promptId&&!v.current.has(I.promptId)&&!b.current.has(I.promptId)),q=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval&&!F;return cr(Br,{flexDirection:"column",paddingX:1,children:[J(on,{}),cr(Br,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&cr(ml,{children:[J(vn,{messages:d,onApprovalSubmitted:I=>{v.current.add(I),k()},onApprovalFailed:I=>{b.current.add(I),k()}}),J(an,{events:s,isStreaming:c}),!e.connected&&!e.serverUnreachable&&J(Br,{children:J(lr,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&cr(Br,{flexDirection:"column",children:[J(lr,{color:"red",bold:!0,children:"Server unreachable after 15s."}),J(lr,{dimColor:!0,children:"Check: adam server logs"}),J(lr,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&J(es,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&J(zr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&J(Nn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&J(On,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&J(Yr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&J(Vn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&J(Jr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&J(jn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&J(zn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&J(Jn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&J(ss,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&J(as,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&J(ls,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&J(Qn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&J(rs,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="artifacts"&&J(hs,{onBack:()=>t({type:"SET_VIEW",view:"chat"}),onSelect:()=>{},onAction:()=>{}})]}),e.pendingPlanApproval?J(Sn,{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?J(Cn,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):q?J(sn,{onSubmit:N}):J(is,{}),e.planTimeoutNotice&&J(dl,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function dl({planId:e,onDismiss:t}){return il(r=>{r==="d"&&t()}),cr(Br,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[cr(lr,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),J(lr,{dimColor:!0,children:" [d] Dismiss"})]})}function ul(){return J(Ho,{children:J(cl,{})})}export{ul as default};
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c,f as d,g as e}from"./chunk-SCUPWMI5.js";import"./chunk-32LOJEHE.js";import"./chunk-LQVBWVLE.js";import"./chunk-6Y2DN2UH.js";import"./chunk-VVQ532U2.js";import"./chunk-AG5SADAI.js";import"./chunk-FYULPPFR.js";import"./chunk-AQAHVNNG.js";import"./chunk-K4IE6DPX.js";import"./chunk-L7JP7DUO.js";import"./chunk-MTQI6B7T.js";import"./chunk-OGY42NUN.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-LVHLUAZW.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.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{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-LVHLUAZW.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";r();export{n as appendArtifactToCollection,o as convertPrimaryFileToCollectionInTransaction,a as createArtifact,j as deleteArtifactById,h as deleteArtifactsByExecution,i as deleteArtifactsByExecutionAndStep,m as ensureUniqueArtifactKey,b as getArtifact,c as getArtifactById,l as isArtifactCollectionManifest,q as listArtifacts,f as listArtifactsByChatSession,d as listArtifactsByExecution,g as listArtifactsByRole,e as listArtifactsByTask,p as listExpiredExecutions,k as removeArtifact};
@@ -0,0 +1 @@
1
+ import{a,b,d as c}from"./chunk-FYULPPFR.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
@@ -0,0 +1 @@
1
+ import{I as a,J as b,K as c,L as d,M as e,N as f,O as g}from"./chunk-4234WJJD.js";import"./chunk-QMW7VEPC.js";import"./chunk-YNS5LQX5.js";import"./chunk-EWYXVBOG.js";import"./chunk-TCBGUVVU.js";import"./chunk-XYZVMTNN.js";import"./chunk-MNSZE3NV.js";import"./chunk-R24YRJRG.js";import"./chunk-HJICGOD4.js";import"./chunk-LQVBWVLE.js";import"./chunk-WVHN54MA.js";import"./chunk-C2XFPUFV.js";import"./chunk-HXDS4NWI.js";import"./chunk-AQAHVNNG.js";import"./chunk-3UR2PN5N.js";import"./chunk-K4IE6DPX.js";import"./chunk-L7JP7DUO.js";import"./chunk-3UZIEE2D.js";import"./chunk-FHESRUJY.js";import"./chunk-DRO3DG7X.js";import"./chunk-TJTH7LHX.js";import"./chunk-MTQI6B7T.js";import"./chunk-N2OLEUAQ.js";import"./chunk-OGY42NUN.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-LVHLUAZW.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-OXGWWSKT.js";import"./chunk-K2TZW4DU.js";import"./chunk-EWYXVBOG.js";import"./chunk-TCBGUVVU.js";import"./chunk-XYZVMTNN.js";import"./chunk-MNSZE3NV.js";import"./chunk-P5Q2UINT.js";import"./chunk-NUJSTEV4.js";import"./chunk-HJICGOD4.js";import"./chunk-NNMQGISW.js";import"./chunk-32LOJEHE.js";import"./chunk-LQVBWVLE.js";import"./chunk-6Y2DN2UH.js";import"./chunk-VVQ532U2.js";import"./chunk-AG5SADAI.js";import"./chunk-FYULPPFR.js";import"./chunk-C2XFPUFV.js";import"./chunk-HXDS4NWI.js";import"./chunk-AQAHVNNG.js";import"./chunk-3UR2PN5N.js";import"./chunk-K4IE6DPX.js";import"./chunk-L7JP7DUO.js";import"./chunk-DRO3DG7X.js";import"./chunk-TJTH7LHX.js";import"./chunk-MTQI6B7T.js";import"./chunk-OGY42NUN.js";import"./chunk-VKKDSXMR.js";import"./chunk-ASPPM7TQ.js";import"./chunk-TLMG5W3L.js";import"./chunk-Z6LHGA27.js";import"./chunk-LVHLUAZW.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -0,0 +1 @@
1
+ import{i as a,j as b,k as c}from"./chunk-HC34HJFF.js";import"./chunk-HJICGOD4.js";import"./chunk-NNMQGISW.js";import"./chunk-6Y2DN2UH.js";import"./chunk-VVQ532U2.js";import"./chunk-AG5SADAI.js";import"./chunk-FYULPPFR.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -0,0 +1 @@
1
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-VVQ532U2.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,g as getRecipientCap,d as listChannels,h as setRecipientCap,c as updateChannel,f as updateChannelStatus};
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-3BRHWRZ5.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
1
+ import{a,b,c}from"./chunk-I44JKROJ.js";import"./chunk-QL2ZOLMC.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
@@ -0,0 +1,32 @@
1
+ import{b as M,c as E,d as K}from"./chunk-LQVBWVLE.js";import{a as ee,e as te,g as re}from"./chunk-6Y2DN2UH.js";import{c as R,h as Z}from"./chunk-VVQ532U2.js";import{a as L,d as be}from"./chunk-FYULPPFR.js";import{b as G,h as X,i as Q}from"./chunk-AQAHVNNG.js";import{s as J}from"./chunk-K4IE6DPX.js";import{a as T}from"./chunk-L7JP7DUO.js";import{d as q,r as ve}from"./chunk-LVHLUAZW.js";import{n as D,p as _e}from"./chunk-QL2ZOLMC.js";import{c as H,h as Ie}from"./chunk-BLCNUT53.js";import{c as x,e as Y}from"./chunk-245WE5AF.js";import{existsSync as Se}from"fs";import{createHash as Ce}from"crypto";import{isAbsolute as Ue}from"path";be();_e();Y();import{v4 as Te}from"uuid";function ae(e){return{id:e.id,eventKey:e.event_key,sourceType:e.source_type,sourceId:e.source_id,taskId:e.task_id??void 0,templateId:e.template_id??void 0,templateName:e.template_name??void 0,messageType:e.message_type,viewerKey:e.viewer_key,title:e.title??void 0,contentPreview:e.content_preview,attachments:S(e.attachments_json),targets:S(e.targets_json),firstDeliveredAt:e.first_delivered_at,lastDeliveredAt:e.last_delivered_at,createdAt:e.created_at,traceId:e.trace_id??void 0}}function S(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function oe(e){if(!e.viewerKey||e.viewerKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires viewerKey");if(!e.eventKey||e.eventKey.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires eventKey");if(!e.sourceId||e.sourceId.trim().length===0)throw new Error("recordUserVisibleDeliveryEvent requires sourceId");let t=D(),r=Date.now(),n=e.deliveredAt??r,a=t.prepare("SELECT * FROM user_visible_events WHERE event_key = ?").get(e.eventKey);if(!a){let c=Te();return t.prepare(`
2
+ INSERT INTO user_visible_events (
3
+ id, event_key, source_type, source_id, task_id, template_id, template_name,
4
+ message_type, viewer_key, title, content_preview, attachments_json,
5
+ targets_json, first_delivered_at, last_delivered_at, created_at, trace_id
6
+ )
7
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
8
+ `).run(c,e.eventKey,e.sourceType,e.sourceId,e.taskId??null,e.templateId??null,e.templateName??null,e.messageType,e.viewerKey,e.title??null,e.contentPreview,JSON.stringify(e.attachments??[]),JSON.stringify(e.targets??[]),n,n,r,e.traceId??x()??null),ne(e.eventKey)}let s=we(S(a.targets_json),e.targets??[]),o=Ee(S(a.attachments_json),e.attachments??[]);return t.prepare(`
9
+ UPDATE user_visible_events
10
+ SET task_id = COALESCE(task_id, ?),
11
+ template_id = COALESCE(template_id, ?),
12
+ template_name = COALESCE(template_name, ?),
13
+ title = COALESCE(title, ?),
14
+ content_preview = CASE WHEN content_preview = '' THEN ? ELSE content_preview END,
15
+ attachments_json = ?,
16
+ targets_json = ?,
17
+ last_delivered_at = MAX(last_delivered_at, ?),
18
+ trace_id = COALESCE(trace_id, ?)
19
+ WHERE event_key = ?
20
+ `).run(e.taskId??null,e.templateId??null,e.templateName??null,e.title??null,e.contentPreview,JSON.stringify(o),JSON.stringify(s),n,e.traceId??x()??null,e.eventKey),ne(e.eventKey)}function ne(e){let t=D().prepare("SELECT * FROM user_visible_events WHERE event_key = ?").get(e);return t?ae(t):void 0}function qe(e){let t=D(),r=e.excludeSourceIds??[],n=[e.viewerKey,e.since,e.until],a=`
21
+ SELECT * FROM user_visible_events
22
+ WHERE viewer_key = ?
23
+ AND last_delivered_at >= ?
24
+ AND last_delivered_at <= ?
25
+ `;return r.length>0&&(a+=` AND source_id NOT IN (${r.map(()=>"?").join(",")})`,n.push(...r)),a+=" ORDER BY last_delivered_at ASC",e.limit!==void 0&&(a+=" LIMIT ?",n.push(e.limit)),t.prepare(a).all(...n).map(ae)}function we(e,t){let r=[...e];for(let n of t){let a=se(n);r.some(s=>se(s)===a)||r.push(n)}return r}function se(e){return[e.type,e.channelId??"",e.webhookUrl??"",e.chatId??"",e.sessionId??""].join("|")}function Ee(e,t){let r=[...e];for(let n of t){let a=ie(n),s=r.findIndex(o=>ie(o)===a);s>=0?r[s]={...r[s],...n}:r.push(n)}return r}function ie(e){return e.artifactId?`artifact:${e.artifactId}`:["file",e.filename??"",e.sizeBytes??"",e.mimeType??""].join("|")}Ie();import{v4 as F}from"uuid";Y();ve();import{basename as C,extname as de}from"path";function ce(e){return q(e).filter(t=>t.kind==="file"&&!!t.blobPath)}function ke(e){let t=e.mime??"";return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Ae(e){let t=C(e.key??"").replace(/[\\/]/g,"-");if(e.originalFilename){let r=C(e.originalFilename).replace(/[\\/]/g,"-");if(de(r))return r}if(de(t))return t;if(e.mime){let r=re(e.mime);if(r&&r!==".bin"&&t)return`${t}${r}`}return e.originalFilename?C(e.originalFilename).replace(/[\\/]/g,"-"):t||(e.blobPath?C(e.blobPath):e.id)}function le(e){return e.map(t=>({path:t.blobPath,mediaType:ke(t),filename:Ae(t),contentType:t.mime,mimeType:t.mime,artifactId:t.id,locator:t.locator,sizeBytes:t.sizeBytes,purpose:t.purpose,contentHash:t.contentHash}))}function N(e){if(e.priority!==void 0&&e.priority!==null)return e.priority;let t=e.mime??"";return t.startsWith("audio/")||t.startsWith("video/")?10:t==="text/markdown"||t==="text/plain"?50:t.startsWith("image/")?100:200}var ue=1.33;function me(e,t){if(e.length===0)return{included:[],dropped:[]};let r=[...e].sort((c,i)=>{let I=N(c),v=N(i);return I!==v?I-v:i.sizeBytes-c.sizeBytes}),n=r[0];if(n.sizeBytes*ue>t)return{firstItemOverflow:n};let a=[],s=[],o=0;for(let c of r){let i=c.sizeBytes*ue;o+i<=t?(a.push(c),o+=i):s.push(c)}return{included:a,dropped:s}}function pe(e,t,r,n){if(t.length===0)return e;let a=(r/(1024*1024)).toFixed(1),s=t.map(c=>`- ${c.filename} (${xe(c.sizeBytes)})`),o=e.endsWith(`---
26
+ `)||e.endsWith("---")?"":`
27
+
28
+ ---`;return`${e}${o}
29
+ \u26A0\uFE0F \u56E0 ${n} \u90AE\u7BB1 ${a}MB \u4E0A\u9650\uFF0C\u4EE5\u4E0B\u4EA7\u7269\u672A\u9644\uFF1A
30
+ ${s.join(`
31
+ `)}
32
+ `}function xe(e){return e<1024?`${e} bytes`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}var $=class extends Error{constructor(r,n,a,s){super(`OutboundFirstAttachmentExceedsCap: artifactKey=${r} sizeBytes=${n} capBytes=${a} recipientDomain=${s}`);this.artifactKey=r;this.sizeBytes=n;this.capBytes=a;this.recipientDomain=s;this.name="OutboundFirstAttachmentExceedsCap"}artifactKey;sizeBytes;capBytes;recipientDomain};function Oe(e){if(!e)return"";let t=e.lastIndexOf("@");return t<0||t===e.length-1?"":e.slice(t+1).toLowerCase().trim()}function De(e,t){return t.find(r=>r.id===e)?.key??e}function Re(e,t){return t.find(r=>r.artifactId===e)?.filename??e}function fe(e,t,r,n,a){let s=Oe(t),o=Z(e,s),c=r.map(l=>({id:l.id,sizeBytes:l.sizeBytes??0,priority:l.priority??void 0,mime:l.mime??void 0})),i=me(c,o);if("firstItemOverflow"in i){let l=i.firstItemOverflow,g=De(l.id,r);return{ok:!1,error:new $(g,l.sizeBytes,o,s).message}}let I=new Set(i.included.map(l=>l.id)),v=n.filter(l=>l.artifactId&&I.has(l.artifactId)),w=a;if(i.dropped.length>0){let l=i.dropped.map(g=>({filename:Re(g.id,n),sizeBytes:g.sizeBytes}));w=pe(a,l,o,s)}return{ok:!0,result:{perTargetAttachments:v,perTargetContent:w}}}var A=H("adam"),j=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;_laneTails=new Map;async _acquireLane(t,r){let n=`${t}:${r}`,a=this._laneTails.get(n)??Promise.resolve(),s,o=new Promise(c=>{s=c});return this._laneTails.set(n,o),o.then(()=>{this._laneTails.get(n)===o&&this._laneTails.delete(n)}),await a,s}isRecentlySent(t){return this._recentlySentIds.has(t)}async send(t){let{taskId:r,channelId:n,chatId:a,content:s,messageType:o,platform:c,webhookUrl:i,replyMarkup:I,replyToMessageId:v,quoteExcerpt:w,quoteTitle:l,mediaUrl:g,mediaType:k,attachments:O,dedupDiscriminator:W}=t,y=ge(o),ye=y!=="reply"&&!!r,u;if(ye){u=`${r}:${n??"none"}:${a??"none"}:${y}${W?`:${W}`:""}`;let f=this._dedupCache.get(u);if(f&&Date.now()-f.timestamp<300*1e3)return A.debug({dedupKey:u},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:f.logEntryId}}if(n){let f=Date.now(),h=6e4,p=this._rateLimitWindows.get(n);p||(p=[],this._rateLimitWindows.set(n,p));let V=f-h;for(;p.length>0&&p[0]<V;)p.shift();if(p.length>=60){let P=F();A.warn({channelId:n,count:p.length},"Rate limited, not sending");let _={type:"channel",channelId:n,chatId:a??""};return this._writeOutboundReceipt(t,_,s,"failure"),{success:!1,logEntryId:P,error:"rate_limited"}}p.push(f)}let he=c??(n?R(n)?.platform:void 0)??"unknown",z=i?s:ee(s,he,r),d=F(),m={id:d,ruleId:void 0,taskId:r??void 0,status:"pending",target:n&&a?{type:"channel",channelId:n,chatId:a}:i?{type:"webhook",webhookUrl:i}:{type:"channel",channelId:n??"",chatId:a??""},content:z,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:y};M(m),u&&this._dedupCache.set(u,{logEntryId:d,timestamp:Date.now()});try{let f=Fe(g);if(f)return E(d,"failed",f),u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"failed",error:f,messageType:y}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:d,error:f};if(i){let h=await fetch(i,{method:"POST",body:JSON.stringify({result:s,taskId:r,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(h.ok)return K(d),this._recordDeliveryLedgerAfterSuccess(t,m.target,y,s),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"delivered",messageType:y}),{success:!0,logEntryId:d};{let p=`Webhook returned ${h.status}`;return E(d,"failed",p),u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"failed",error:p,messageType:y}),{success:!1,logEntryId:d,error:p}}}else if(n&&a){let{getChannelManager:h}=await $e(),p=h();if(!p){let b="ChannelManager not available";return E(d,"failed",b),u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"failed",error:b,messageType:y}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:d,error:b}}let V={content:z,messageType:y,...I?{replyMarkup:I}:{},...v?{replyToMessageId:v}:{},...w?{quoteExcerpt:w}:{},...l?{quoteTitle:l}:{},...g?{mediaUrl:g}:{},...k?{mediaType:k}:{},...O?{attachments:O}:{}},P=await this._acquireLane(n,a),_;try{_=await p.sendMessage(n,a,V)}finally{P()}if(_===null){let b="Channel adapter send failed (returned null)";return E(d,"failed",b),u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"failed",error:b,messageType:y}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:d,error:b}}if(_&&(this._recentlySentIds.add(_),setTimeout(()=>this._recentlySentIds.delete(_),300*1e3)),_?.startsWith("queued-")){let b="queued_not_delivered";return u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"pending",error:b,messageType:y}),{success:!1,messageId:_,logEntryId:d,error:b}}return K(d),this._recordDeliveryLedgerAfterSuccess(t,m.target,y,s),this._writeOutboundReceipt(t,m.target,s,"success"),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"delivered",messageType:y}),{success:!0,messageId:_??void 0,logEntryId:d}}else{let h="No channelId/chatId or webhookUrl provided";return E(d,"failed",h),u&&this._dedupCache.delete(u),{success:!1,logEntryId:d,error:h}}}catch(f){let h=f instanceof Error?f.message:String(f);return E(d,"failed",h),u&&this._dedupCache.delete(u),T.emit({type:"delivery_status_change",logEntryId:d,taskId:r,target:m.target,status:"failed",error:h,messageType:y}),this._writeOutboundReceipt(t,m.target,s,"failure"),{success:!1,logEntryId:d,error:h}}}_writeOutboundReceipt(t,r,n,a){if(r.type!=="channel"||!r.channelId)return;let s=x();if(!s){A.debug({taskId:t.taskId,channelId:r.channelId,outcome:a},"Outbound receipt skipped: no active trace context");return}let o=(t.attachments??[]).map(i=>i.artifactId).filter(i=>typeof i=="string"&&i.length>0),c=t.actorToolName??"OutboundGateway.send";try{Q({traceId:s,taskId:t.taskId,sessionId:t.sessionId,effectCategory:"outbound_message",verb:"send",entityType:"channel_message",target:{channelId:r.channelId,chatId:r.chatId,platform:t.platform},payload:{textChars:n.length,attachmentCount:t.attachments?.length??0,attachmentRefs:o.length>0?o:void 0},actor:{traceId:s,toolName:c,taskId:t.taskId},outcome:a})}catch(i){i instanceof X?A.warn({errors:i.errors,taskId:t.taskId,channelId:r.channelId},"Outbound receipt validation failed"):A.warn({error:i instanceof Error?i.message:String(i),taskId:t.taskId},"Outbound receipt write failed")}}async redeliverExecutionTo(t){let r=t.includeArtifacts??!0,n=t.messageType??"result_delivery",a=t.dedupDiscriminator??`redelivery:${Date.now()}`,s=r?t.fileArtifacts??ce(t.executionId):[],o=s.length>0?le(s):void 0,c=[];for(let i of t.targets){let I=R(i.channelId);if(!I){c.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:"",status:"failed",attachmentCount:0,error:`Channel not found: ${i.channelId}`});continue}let v=o,w=t.content;if(I.platform==="email"&&o&&o.length>0){let g=fe(i.channelId,i.chatId,s,o,t.content);if(!g.ok){let k=F(),O={type:"channel",channelId:i.channelId,chatId:i.chatId??""};M({id:k,ruleId:void 0,taskId:t.executionId,status:"pending",target:O,content:t.content,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:ge(n)}),E(k,"failed",g.error),c.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:k,status:"failed",attachmentCount:0,error:g.error});continue}v=g.result.perTargetAttachments,w=g.result.perTargetContent}let l=await this.send({taskId:t.executionId,sessionId:t.sessionId,channelId:i.channelId,chatId:i.chatId,content:w,messageType:n,platform:I.platform,attachments:v,dedupDiscriminator:a,actorToolName:t.actorToolName});c.push({target:{channelId:i.channelId,chatId:i.chatId},deliveryLogId:l.logEntryId,status:l.success?"delivered":"failed",attachmentCount:v?.length??0,...l.error?{error:l.error}:{}})}return{deliveries:c}}_recordDeliveryLedgerAfterSuccess(t,r,n,a){if(Ve(n,t.taskId))try{let s=Pe(t,r);if(!s){L({source:"delivery_ledger",severity:"warning",sourceId:t.taskId,message:`Skipped user-visible delivery ledger write for ${n}: viewer identity unresolved`});return}let o=Me(t.taskId),c=Ne(a);oe({eventKey:`${s}|${o.sourceId}|${n}|${c}`,sourceType:o.sourceType,sourceId:o.sourceId,taskId:t.taskId,templateId:o.templateId,templateName:o.templateName,messageType:n,viewerKey:s,title:o.templateName,contentPreview:a,attachments:(t.attachments??[]).map(Ke),targets:[Le(r)]})}catch(s){let o=s instanceof Error?s.message:String(s);A.warn({error:o,taskId:t.taskId,messageType:n},"User-visible delivery ledger write failed");try{L({source:"delivery_ledger",severity:"error",sourceId:t.taskId,message:o})}catch{}}}};function Ve(e,t){return t?!["reply","assistant_text","user_message","approval","approval_prompt"].includes(e):!1}function Pe(e,t){if(e.viewerKey)return e.viewerKey;if(t.type==="channel"&&t.channelId)return te({type:"channel",channelId:t.channelId,chatId:t.chatId})}function Me(e){let t=G(e);if(!t)return{sourceType:"task",sourceId:e};let r=J(t.templateId);return{sourceType:"template_execution",sourceId:t.id,templateId:t.templateId,templateName:r?.name}}function Ke(e){return{artifactId:e.artifactId,locator:e.locator,filename:e.filename,mimeType:e.mimeType??e.contentType,sizeBytes:e.sizeBytes,purpose:e.purpose,contentHash:e.contentHash}}function Le(e){if(e.type==="webhook")return{type:"webhook",webhookUrl:e.webhookUrl};let t=e.channelId?R(e.channelId):void 0;return{type:"channel",channelId:e.channelId,chatId:e.chatId,label:t?.name}}function Ne(e){return Ce("sha256").update(e).digest("hex")}var U=null;function $e(){return U||(U=import("./channels-S4AAOOTN.js")),U}function kt(){U=null}function Fe(e){if(!e)return;if(e.includes("://")&&!e.startsWith("file://"))return"mediaUrl must be a local file path";let t=e.startsWith("file://")?new URL(e).pathname:e;if(!Ue(t))return"mediaUrl must be absolute";if(!Se(t))return"mediaUrl file does not exist"}function ge(e){return e==="report"?"status_report":e==="deliver"?"result_delivery":e}var B=null;function Be(){return B||(B=new j),B}function At(e){return Be().isRecentlySent(e)}export{qe as a,ce as b,ke as c,Ae as d,j as e,kt as f,Be as g,At as h};
@@ -1,4 +1,4 @@
1
- import{E as R,I as E}from"./chunk-KJNAORKM.js";import{d as h,h as A}from"./chunk-WBAPIPST.js";import{c as y,h as V}from"./chunk-BLCNUT53.js";import{c as v}from"./chunk-FCV2DPZQ.js";import{readFileSync as P,writeFileSync as I,existsSync as b}from"fs";import{join as x}from"path";function k(n){let e=x(m(n),".env");if(!b(e))return null;let s=P(e,"utf-8"),r={};for(let c of s.split(`
1
+ import{E as R,I as E}from"./chunk-MTQI6B7T.js";import{d as h,h as A}from"./chunk-WBAPIPST.js";import{c as y,h as V}from"./chunk-BLCNUT53.js";import{c as v}from"./chunk-FCV2DPZQ.js";import{readFileSync as P,writeFileSync as I,existsSync as b}from"fs";import{join as x}from"path";function k(n){let e=x(m(n),".env");if(!b(e))return null;let s=P(e,"utf-8"),r={};for(let c of s.split(`
2
2
  `)){let t=c.trim();if(!t||t.startsWith("#"))continue;let i=t.startsWith("export ")?t.slice(7).trim():t,a=i.indexOf("=");if(a===-1)continue;let d=i.slice(0,a).trim(),o=i.slice(a+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),!(o.includes("$")&&(o=o.replace(/\$\{(\w+)\}|\$(\w+)/g,(f,l,u)=>{let g=l??u;return r[g]??process.env[g]??""}),!o))&&(r[d]=o)}return r}function W(n,e){let s=k(n);if(!s)return e;let r={...e},c=0;for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_")){$.warn({roleName:n,key:t},"Role .env contains ANTHROPIC_* key; ignored (managed globally)");continue}t in r||(r[t]=i,c++)}return c>0&&$.info({roleName:n,seeded:c},"Seeded role envVars from .env file"),Object.keys(r).length>0?r:void 0}function U(n,e){let s=k(n);if(!s)return[];let r=e??{},c=[];for(let[t,i]of Object.entries(s)){if(t.startsWith("ANTHROPIC_"))continue;let a=r[t]??"";a!==i&&c.push({envKey:t,dbValue:a,envValue:i})}for(let[t,i]of Object.entries(r))t in s||c.push({envKey:t,dbValue:i,envValue:""});return c}function q(n,e){let s=x(m(n),".env"),r=e??{},c=[],t=new Set;if(b(s)){let a=P(s,"utf-8");for(let d of a.split(`
3
3
  `)){let o=d.trim();if(!o||o.startsWith("#")){c.push(d);continue}let f=o.startsWith("export ")?o.slice(7).trim():o,l=f.indexOf("=");if(l===-1){c.push(d);continue}let u=f.slice(0,l).trim(),g=o.startsWith("export ")?"export ":"";u in r&&(c.push(`${g}${u}=${r[u]}`),t.add(u))}}let i=0;for(let[a,d]of Object.entries(r)){if(t.has(a)){i++;continue}d&&d.length>0&&(c.push(`${a}=${d}`),i++)}return I(s,c.join(`
4
4
  `)+`
@@ -1,4 +1,4 @@
1
- import{c as T,d as w}from"./chunk-ISKCTUI7.js";import{a as b}from"./chunk-DRO3DG7X.js";import{d as C,l as S,n as k,o as M,p as x,r as B}from"./chunk-XIVFVKMB.js";import{d as g}from"./chunk-Z6LHGA27.js";function R(e){let t=(e.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g)||[]).length,n=e.length-t;return t+Math.ceil(n/4)}function F(e,t,n){let o=Math.max(0,t-e)/864e5;return Math.pow(.5,o/n)}function E(e){return e.useCount<=0?.5:e.successCount/e.useCount}function v(e,t,n){let s=g().memory,o=s.retrievalWeights,u=s.retrievalDecayDays,d=F(e.lastUsedAt,n,u),f=e.confidence,l=E(e),a=R(e.content),i=Math.min(1,a/s.globalBudgetTokens);return{score:o.cosSim*t+o.recency*d+o.confidence*f+o.successRate*l-o.tokenCost*i,tokenCost:a}}async function H(e,t,n={}){let s=n.topK??10,o=n.hybridConfig??x,u;try{u=await b(t)}catch{}let d=u??new Float32Array(384),f=B(e,d,t,s*2,o,{excludeSuperseded:!0}),l=e?M(e):S,a=f.map(({node:c,combinedRelevance:y})=>{let h=Math.min(.3,(c.retrievedCount??0)*.05),p=k(c.createdAt,y,c.importance,l)+h;return{...c,score:p}});a.sort((c,y)=>y.score-c.score);let i=a.slice(0,s);for(let c of i)C(c.id);return i}async function K(e,t,n){let s=g().memory,o=n?.topK??10,u=n?.budgetTokens??s.globalBudgetTokens,d;try{d=await b(e)}catch{d=new Float32Array(384)}let f=w(t,d,o);f.length===0&&(f=T(t,{includeSuperseded:!1}).slice(0,o).map(m=>({node:m,cosine:0})));let l=Date.now(),a=f.map(({node:r,cosine:m})=>{let{score:A,tokenCost:D}=v(r,m,l);return{belief:r,cosSim:m,score:A,tokenCost:D}});a.sort((r,m)=>m.score-r.score);let i=[],c=0,y=9;for(let r of a){let m=r.tokenCost+y;if(c+m>u)break;i.push(r),c+=r.tokenCost}if(i.length===0)return{selected:i,usedIds:[],contextString:""};let p=`[Memory Context \u2014 retrieved from prior interactions]
1
+ import{c as T,d as w}from"./chunk-FHESRUJY.js";import{a as b}from"./chunk-DRO3DG7X.js";import{d as C,l as S,n as k,o as M,p as x,r as B}from"./chunk-TJTH7LHX.js";import{d as g}from"./chunk-Z6LHGA27.js";function R(e){let t=(e.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g)||[]).length,n=e.length-t;return t+Math.ceil(n/4)}function F(e,t,n){let o=Math.max(0,t-e)/864e5;return Math.pow(.5,o/n)}function E(e){return e.useCount<=0?.5:e.successCount/e.useCount}function v(e,t,n){let s=g().memory,o=s.retrievalWeights,u=s.retrievalDecayDays,d=F(e.lastUsedAt,n,u),f=e.confidence,l=E(e),a=R(e.content),i=Math.min(1,a/s.globalBudgetTokens);return{score:o.cosSim*t+o.recency*d+o.confidence*f+o.successRate*l-o.tokenCost*i,tokenCost:a}}async function H(e,t,n={}){let s=n.topK??10,o=n.hybridConfig??x,u;try{u=await b(t)}catch{}let d=u??new Float32Array(384),f=B(e,d,t,s*2,o,{excludeSuperseded:!0}),l=e?M(e):S,a=f.map(({node:c,combinedRelevance:y})=>{let h=Math.min(.3,(c.retrievedCount??0)*.05),p=k(c.createdAt,y,c.importance,l)+h;return{...c,score:p}});a.sort((c,y)=>y.score-c.score);let i=a.slice(0,s);for(let c of i)C(c.id);return i}async function K(e,t,n){let s=g().memory,o=n?.topK??10,u=n?.budgetTokens??s.globalBudgetTokens,d;try{d=await b(e)}catch{d=new Float32Array(384)}let f=w(t,d,o);f.length===0&&(f=T(t,{includeSuperseded:!1}).slice(0,o).map(m=>({node:m,cosine:0})));let l=Date.now(),a=f.map(({node:r,cosine:m})=>{let{score:A,tokenCost:D}=v(r,m,l);return{belief:r,cosSim:m,score:A,tokenCost:D}});a.sort((r,m)=>m.score-r.score);let i=[],c=0,y=9;for(let r of a){let m=r.tokenCost+y;if(c+m>u)break;i.push(r),c+=r.tokenCost}if(i.length===0)return{selected:i,usedIds:[],contextString:""};let p=`[Memory Context \u2014 retrieved from prior interactions]
2
2
  ${i.map(r=>r.belief.isAnti?`- [anti-pattern] \u274C ${r.belief.content}`:`- [belief] ${r.belief.content}`).join(`
3
3
  `)}
4
4