adam-agent-server 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/{App-SIQUVFJY.js → App-522DTURQ.js} +10 -10
  2. package/dist/approval-handler-S3NV7OPO.js +1 -0
  3. package/dist/{artifacts-MAYKOTA2.js → artifacts-NFMM3ORE.js} +1 -1
  4. package/dist/audit-diagnostics-IHU3CJYZ.js +1 -0
  5. package/dist/audit-manager-MUMEEP3C.js +1 -0
  6. package/dist/bree-engine-EEKUQA3U.js +1 -0
  7. package/dist/channels-IDBWHLLE.js +1 -0
  8. package/dist/{channels-2TWTBE6Y.js → channels-ZHCTFSDA.js} +1 -1
  9. package/dist/chat-tool-calls-4BQWZCJH.js +1 -0
  10. package/dist/{chunk-Z2APBKIT.js → chunk-2JM3URDG.js} +1 -1
  11. package/dist/{chunk-OBD4245G.js → chunk-4G4CKAXY.js} +1 -1
  12. package/dist/{chunk-2CE2WUUZ.js → chunk-4ZESWP3J.js} +1 -1
  13. package/dist/{chunk-QYI44EP6.js → chunk-4ZG4UMAK.js} +1 -1
  14. package/dist/{chunk-BE653A45.js → chunk-6GYNUTPP.js} +1 -1
  15. package/dist/{chunk-JROGEBP5.js → chunk-76MMY2XC.js} +1 -1
  16. package/dist/{chunk-BMCNQGUH.js → chunk-7QT2ZX3K.js} +1 -1
  17. package/dist/{chunk-SGLZAIVL.js → chunk-A3YUIWLK.js} +1 -1
  18. package/dist/{chunk-HL373H4P.js → chunk-AMJJ2WGU.js} +1 -1
  19. package/dist/{chunk-NUOTFUNF.js → chunk-CN5NEJXG.js} +1 -1
  20. package/dist/{chunk-O6L4UVLV.js → chunk-DFTRUOT6.js} +1 -1
  21. package/dist/{chunk-JYZTIE2J.js → chunk-DRS5NOAA.js} +1 -1
  22. package/dist/{chunk-6WQFYV3N.js → chunk-EBZCHLYS.js} +1 -1
  23. package/dist/{chunk-SKHMWKJT.js → chunk-EPLSB63A.js} +1 -1
  24. package/dist/{chunk-V2MMQ3SH.js → chunk-FN64ZULV.js} +1 -1
  25. package/dist/chunk-FQHGIY3E.js +1 -0
  26. package/dist/{chunk-NSUXJ2VA.js → chunk-GQS3ED3B.js} +1 -1
  27. package/dist/{chunk-LKGYQJMS.js → chunk-HEHST2E2.js} +1 -1
  28. package/dist/chunk-IAGTZGGV.js +32 -0
  29. package/dist/chunk-ITVCPC7G.js +1 -0
  30. package/dist/{chunk-NXGR3PRY.js → chunk-J2VSAXVU.js} +1 -1
  31. package/dist/{chunk-5G64P4KE.js → chunk-JRRNGKDK.js} +1 -1
  32. package/dist/{chunk-KS24764D.js → chunk-JVYSSJKT.js} +2 -2
  33. package/dist/chunk-JXZCQ5XW.js +1 -0
  34. package/dist/{chunk-LCD5DVS6.js → chunk-KM4EFB4N.js} +1 -1
  35. package/dist/chunk-KQMKRRYW.js +143 -0
  36. package/dist/{chunk-4JHACUZY.js → chunk-L4APYD5A.js} +1 -1
  37. package/dist/{chunk-WY5BOCQP.js → chunk-LMQPGVM7.js} +16 -16
  38. package/dist/chunk-MMVDXKYS.js +14 -0
  39. package/dist/chunk-NKS7LEA7.js +182 -0
  40. package/dist/{chunk-VWX2B6OM.js → chunk-ORFLN4BF.js} +1 -1
  41. package/dist/{chunk-2JIQT2CI.js → chunk-PO66F7UQ.js} +1 -1
  42. package/dist/{chunk-XAPJJAJQ.js → chunk-QJXV4SQE.js} +1 -1
  43. package/dist/{chunk-UCUELFCS.js → chunk-R7Q6FSV4.js} +1 -1
  44. package/dist/{chunk-47HJPIUA.js → chunk-T7EKW3B7.js} +1 -1
  45. package/dist/{chunk-JZBXLN7M.js → chunk-VOH52UDS.js} +1 -1
  46. package/dist/{chunk-HRPMRWHD.js → chunk-VZL2DGC4.js} +1 -1
  47. package/dist/{chunk-IEBAOZED.js → chunk-WDMSZS4W.js} +1 -1
  48. package/dist/{chunk-2A2TXYT3.js → chunk-WG3C43QS.js} +3 -3
  49. package/dist/{chunk-TA5PFK5C.js → chunk-YEGUFMLJ.js} +1 -1
  50. package/dist/{chunk-ZQN6JZIJ.js → chunk-ZGA52HRD.js} +1 -1
  51. package/dist/cli.js +2 -2
  52. package/dist/{config-U624HJKI.js → config-GOJLI3X2.js} +1 -1
  53. package/dist/config-Z6KFEFJO.js +1 -0
  54. package/dist/db-ROXIYW5B.js +1 -0
  55. package/dist/{delivery-log-QMQQHES4.js → delivery-log-TGJZ5HU7.js} +1 -1
  56. package/dist/engine-GN7PJPGQ.js +1 -0
  57. package/dist/{evolution-audit-XF4KZZMP.js → evolution-audit-TFJF666X.js} +1 -1
  58. package/dist/execution-tools-BQD2O25X.js +1 -0
  59. package/dist/{external-api-435WH6V3.js → external-api-DSLQDRZ2.js} +1 -1
  60. package/dist/index.js +41 -39
  61. package/dist/{learner-4CJ7BSCN.js → learner-ACBX3GI7.js} +1 -1
  62. package/dist/{memories-NJFKSOL5.js → memories-RAIR5O2F.js} +1 -1
  63. package/dist/{memory-extractor-UQI75BBK.js → memory-extractor-A6CAOFOX.js} +1 -1
  64. package/dist/{memory-gc-NTZVUGJX.js → memory-gc-W63MGSDH.js} +1 -1
  65. package/dist/memory-service-H4OFUNCF.js +1 -0
  66. package/dist/outbound-gateway-LKRQYPA2.js +1 -0
  67. package/dist/presets-FO6RSGDN.js +1 -0
  68. package/dist/{reflection-job-F4BZA2E3.js → reflection-job-XC2F7GTT.js} +1 -1
  69. package/dist/role-presets-SDA664QG.js +1 -0
  70. package/dist/role-workspace-NGJEJG3H.js +1 -0
  71. package/dist/{roles-WDMUBWQP.js → roles-LZCJ7QFS.js} +1 -1
  72. package/dist/{session-manager-XFUKWEC7.js → session-manager-PU4GH3E4.js} +1 -1
  73. package/dist/skill-registry-XKLE2LXU.js +1 -0
  74. package/dist/{task-templates-BIVCRNXA.js → task-templates-52LAC6OA.js} +1 -1
  75. package/dist/template-dispatch-PJFSWEO2.js +1 -0
  76. package/package.json +1 -1
  77. package/web/dist/assets/{ChannelDetail-D0FBZoAX.js → ChannelDetail-CSq9o5fq.js} +1 -1
  78. package/web/dist/assets/{Channels-Cztxvsa2.js → Channels-CAxTh1Bp.js} +1 -1
  79. package/web/dist/assets/Chat-PUz41HFr.js +2 -0
  80. package/web/dist/assets/{Cost-K8-4xqBe.js → Cost-BHcsPz5T.js} +1 -1
  81. package/web/dist/assets/{Dashboard-BXqFb_Vr.js → Dashboard-BT39_iWc.js} +1 -1
  82. package/web/dist/assets/{EnvVarEditor-FiiJazzp.js → EnvVarEditor-D_1d7bTJ.js} +1 -1
  83. package/web/dist/assets/{EventDefDetail-C3S1G0K8.js → EventDefDetail-jKN3gO_7.js} +1 -1
  84. package/web/dist/assets/{Events-BKxqZ9j6.js → Events-CpeHg3fh.js} +1 -1
  85. package/web/dist/assets/{Evolution-DFcSm6Rw.js → Evolution-DsWyv2_a.js} +1 -1
  86. package/web/dist/assets/{ExtensionDetail-C8aPpyLv.js → ExtensionDetail-CJHNaNii.js} +1 -1
  87. package/web/dist/assets/{Extensions-MLZk05j0.js → Extensions-Pg2vx_ZK.js} +1 -1
  88. package/web/dist/assets/{FeatureRequests-D_4XaQ7F.js → FeatureRequests-3Yl8wTNT.js} +1 -1
  89. package/web/dist/assets/{GoalDetail-DVU7c0aR.js → GoalDetail-L3T1zqqs.js} +1 -1
  90. package/web/dist/assets/{Goals-D3h4WMjU.js → Goals-B-__r-Yq.js} +1 -1
  91. package/web/dist/assets/{Logs-D5MQv6Yw.js → Logs-CMkjUkmu.js} +1 -1
  92. package/web/dist/assets/{Memories-Dls71I2i.js → Memories-Q1eKfPQ2.js} +1 -1
  93. package/web/dist/assets/{Mistakes-BZcTg0vP.js → Mistakes-BROkixt_.js} +1 -1
  94. package/web/dist/assets/{Plugins-CwCHGzI6.js → Plugins-v17MyPVe.js} +1 -1
  95. package/web/dist/assets/{RoleDetail-B2M6ALSl.js → RoleDetail-DCGFBLP1.js} +2 -2
  96. package/web/dist/assets/{Roles-FEHqm_Jf.js → Roles-C7SNebvY.js} +1 -1
  97. package/web/dist/assets/{Settings-rdVQMfqX.js → Settings-QuKwKbKg.js} +1 -1
  98. package/web/dist/assets/{Strategies-CwJ9JQ-X.js → Strategies-CXQYvCkc.js} +1 -1
  99. package/web/dist/assets/{Switch-1JjR4Imr.js → Switch--h1rqagh.js} +1 -1
  100. package/web/dist/assets/{TaskDetail-h12WxjfG.js → TaskDetail-B0G5ZjDD.js} +1 -1
  101. package/web/dist/assets/{Work-CfzFRSZX.js → Work-DbFst_9-.js} +1 -1
  102. package/web/dist/assets/index-D35OGE0z.css +2 -0
  103. package/web/dist/assets/{index-CXEJd-0s.js → index-Dd3NDYZR.js} +2 -2
  104. package/web/dist/assets/{usePluginsWithUsage-4iLJAPjH.js → usePluginsWithUsage-DpTxJuFQ.js} +1 -1
  105. package/web/dist/index.html +2 -2
  106. package/dist/approval-handler-BWA7UIKN.js +0 -1
  107. package/dist/audit-diagnostics-K3LUWXTI.js +0 -1
  108. package/dist/audit-manager-6WL2V6JG.js +0 -1
  109. package/dist/bree-engine-KYD4GKQK.js +0 -1
  110. package/dist/channels-PWDSTYNR.js +0 -1
  111. package/dist/chat-tool-calls-WJDFQ54U.js +0 -1
  112. package/dist/chunk-3UFEOB6P.js +0 -143
  113. package/dist/chunk-MTRLUW7Z.js +0 -1
  114. package/dist/chunk-QTGAK62Z.js +0 -14
  115. package/dist/chunk-TWOJVEO7.js +0 -32
  116. package/dist/chunk-VO24C673.js +0 -1
  117. package/dist/chunk-VPMHZJS2.js +0 -1
  118. package/dist/chunk-ZJ3TS4FL.js +0 -182
  119. package/dist/config-X7A6NA73.js +0 -1
  120. package/dist/db-XODNIJSJ.js +0 -1
  121. package/dist/engine-OQXDHA2R.js +0 -1
  122. package/dist/execution-tools-BR4T4MMW.js +0 -1
  123. package/dist/memory-service-3RLVOF2C.js +0 -1
  124. package/dist/outbound-gateway-NJNSN2ZX.js +0 -1
  125. package/dist/presets-SUJRFRJC.js +0 -1
  126. package/dist/role-presets-VEYTGYA4.js +0 -1
  127. package/dist/role-workspace-AIVHPX5P.js +0 -1
  128. package/dist/skill-registry-LARMNUT5.js +0 -1
  129. package/dist/template-dispatch-6FPJQN6A.js +0 -1
  130. package/web/dist/assets/Chat-Ce72TtUi.js +0 -2
  131. package/web/dist/assets/index-CarTGiGO.css +0 -2
@@ -1,14 +1,14 @@
1
- import{a as To}from"./chunk-NS6WVZMS.js";import{b as v,d as Vr,e as zo}from"./chunk-HL373H4P.js";import{a as qr,f as Ko,h as Ho}from"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";import{Box as Mr,Text as pr,useInput as il}from"ink";import{useState as al,useEffect as go,useRef as Qt,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 Xo=Rs(null);function Yo({children:e}){let[t,r]=Ms(Ns,$s);return _s(Xo.Provider,{value:{state:t,dispatch:r},children:e})}function tt(){let e=Ds(Xo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Qo,useRef as Jo}from"react";var Ls=15e3;function Zo(){let{state:e,dispatch:t}=tt(),r=Jo(null),a=Jo(null);Qo(()=>{a.current=e.session?.id??null},[e.session?.id]),Qo(()=>{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 Vr("/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 b=await v(`/tasks/${p.taskId}`);o&&b.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 v("/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 en,useCallback as qs}from"react";function tn(e){let[t,r]=en([]),[a,o]=en(!1),u=Os(null),d=qs(()=>{r([]),o(!1)},[]);return Fs(()=>{if(!e)return;let l=!0;r([]),o(!0);try{let i=new zo(e);return u.current=i,i.on("reasoning",n=>{if(!l)return;let g=n.content??"";r(b=>{let y=b[b.length-1];if(y?.type==="reasoning"){let w=[...b];return w[w.length-1]={...y,content:y.content+g},w}return[...b,{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 ho,useEffect as Vs,useCallback as yr}from"react";function yo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function rn(){let[e,t]=ho(null),[r,a]=ho(!0),[o,u]=ho(null),d=yr(async()=>{try{let b=(await v("/chat/sessions?status=active")).sessions.find(y=>y.source.type==="tui");return b?yo(b):null}catch{return null}},[]),l=yr(async()=>{try{let g=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),b=yo(g.session);return t(b),b}catch{return u("Failed to create session"),null}},[]),i=yr(async g=>{try{let b=await v("/chat/messages",{method:"POST",body:{content:g,source:{type:"tui"}}});return t(y=>y&&{...y,messageCount:y.messageCount+1,lastActiveAt:Date.now()}),b}catch{return null}},[]),n=yr(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),p=yr(async()=>{if(e)try{let g=await v(`/chat/sessions/${e.id}`);t(yo(g.session))}catch{t(null)}},[e]);return Vs(()=>{let g=!1;async function b(){a(!0);let y=await d();g||(y?t(y):await l(),g||a(!1))}return b(),()=>{g=!0}},[]),{session:e,loading:r,error:o,sendMessage:i,createNewSession:l,archiveCurrentSession:n,refreshSession:p,setSession:t}}import{useEffect as on,useRef as Us,useState as Ws}from"react";function nn(e){let[t,r]=Ws(null),a=Us(new Set);return on(()=>{if(!e)return;let o=!0,u=null;try{u=new Vr("/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]),on(()=>{a.current.clear(),r(null)},[e]),{latestMessage:t}}import{Box as bo,Text as We}from"ink";import{Fragment as Ur,jsx as Ee,jsxs as tr}from"react/jsx-runtime";var Gs=90;function sn({children:e}){return Ee(bo,{children:e})}function an(){let{state:e}=tt(),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=tr(Ur,{children:[Ee(We,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),Ee(We,{children:` ${o}`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:u.toLowerCase()})]}),p=tr(Ur,{children:[Ee(We,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:d}),a&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:"yellow",children:"timeout"})]})]})]});return i?tr(bo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[Ee(sn,{children:n}),Ee(sn,{children:p})]}):tr(bo,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[n,Ee(We,{dimColor:!0,children:" | "}),p]})}import{Box as Wr,Text as Gr,useInput as Ks}from"ink";import{useState as Co,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 vo(e){let t=e.toLowerCase();return js.filter(r=>r.name.startsWith(t))}function ln(e){let t=vo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as jr,jsxs as br}from"react/jsx-runtime";function cn({onSubmit:e}){let[t,r]=Co(""),[a,o]=Co(0),[u,d]=Co(!1),l=t.startsWith("/")&&t.length>=1,i=t.slice(1),n=Hs(()=>l?vo(i):[],[l,i]),p=y=>{r(y),y.startsWith("/")?(d(!0),o(0)):d(!1)},g=()=>{let y=t.trim();if(y){if(y.startsWith("/")){let w=y.slice(1),s=ln(w);e(s?`/${s.name}`:y)}else e(y);r(""),d(!1)}},b=y=>{e(`/${y.name}`),r(""),d(!1)};return Ks((y,w)=>{if(!(!u||!l||n.length===0)){if(w.upArrow){o(s=>s<=0?n.length-1:s-1);return}if(w.downArrow){o(s=>s>=n.length-1?0:s+1);return}if(w.tab){let s=n[a];s&&b(s);return}if(w.escape){d(!1),r("");return}}},{isActive:u&&l&&n.length>0}),br(Wr,{flexDirection:"column",children:[u&&l&&n.length>0&&jr(Wr,{flexDirection:"column",marginBottom:0,paddingX:1,children:n.map((y,w)=>{let s=w===a;return br(Wr,{children:[jr(Gr,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),br(Gr,{color:s?"cyan":"white",bold:s,children:["/",y.name]}),br(Gr,{dimColor:!0,children:[" \u2014 ",y.description]})]},y.name)})}),br(Wr,{borderStyle:"round",borderDimColor:!0,children:[jr(Gr,{bold:!0,children:"\u25B8 "}),jr(zs,{value:t,onChange:p,onSubmit:g,placeholder:"Type a message or / for commands..."})]})]})}import{Box as rr,Text as _e,useInput as Xs}from"ink";import{useState as Ys}from"react";import{jsx as ze,jsxs as pt}from"react/jsx-runtime";function Qs({content:e,expanded:t}){let r=e.split(`
2
- `);return r.length<=5?ze(_e,{color:"green",children:e}):t?ze(_e,{color:"green",children:e}):pt(_e,{color:"green",children:[r.slice(0,3).join(`
1
+ import{a as ho}from"./chunk-NS6WVZMS.js";import{b as v,d as Vr,e as Xo}from"./chunk-AMJJ2WGU.js";import{a as qr,f as Ho,h as zo,i as To}from"./chunk-ITVCPC7G.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";import{Box as Mr,Text as pr,useInput as ml}from"ink";import{useState as fl,useEffect as go,useRef as Qt,useReducer as gl}from"react";import{createContext as Ns,useContext as Ls,useReducer as _s}from"react";import{jsx as qs}from"react/jsx-runtime";var Fs={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 Os(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 Yo=Ns(null);function Qo({children:e}){let[t,r]=_s(Os,Fs);return qs(Yo.Provider,{value:{state:t,dispatch:r},children:e})}function tt(){let e=Ls(Yo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Jo,useRef as Zo}from"react";var Vs=15e3;function en(){let{state:e,dispatch:t}=tt(),r=Zo(null),a=Zo(null);Jo(()=>{a.current=e.session?.id??null},[e.session?.id]),Jo(()=>{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})},Vs)};return(()=>{try{u=new Vr("/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 b=await v(`/tasks/${p.taskId}`);o&&b.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 v("/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 Us,useRef as Ws,useState as tn,useCallback as Gs}from"react";function rn(e){let[t,r]=tn([]),[a,o]=tn(!1),u=Ws(null),d=Gs(()=>{r([]),o(!1)},[]);return Us(()=>{if(!e)return;let l=!0;r([]),o(!0);try{let i=new Xo(e);return u.current=i,i.on("reasoning",n=>{if(!l)return;let g=n.content??"";r(b=>{let y=b[b.length-1];if(y?.type==="reasoning"){let w=[...b];return w[w.length-1]={...y,content:y.content+g},w}return[...b,{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 yo,useEffect as js,useCallback as yr}from"react";function bo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function on(){let[e,t]=yo(null),[r,a]=yo(!0),[o,u]=yo(null),d=yr(async()=>{try{let b=(await v("/chat/sessions?status=active")).sessions.find(y=>y.source.type==="tui");return b?bo(b):null}catch{return null}},[]),l=yr(async()=>{try{let g=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),b=bo(g.session);return t(b),b}catch{return u("Failed to create session"),null}},[]),i=yr(async g=>{try{let b=await v("/chat/messages",{method:"POST",body:{content:g,source:{type:"tui"}}});return t(y=>y&&{...y,messageCount:y.messageCount+1,lastActiveAt:Date.now()}),b}catch{return null}},[]),n=yr(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),p=yr(async()=>{if(e)try{let g=await v(`/chat/sessions/${e.id}`);t(bo(g.session))}catch{t(null)}},[e]);return js(()=>{let g=!1;async function b(){a(!0);let y=await d();g||(y?t(y):await l(),g||a(!1))}return b(),()=>{g=!0}},[]),{session:e,loading:r,error:o,sendMessage:i,createNewSession:l,archiveCurrentSession:n,refreshSession:p,setSession:t}}import{useEffect as nn,useRef as Ks,useState as Hs}from"react";function sn(e){let[t,r]=Hs(null),a=Ks(new Set);return nn(()=>{if(!e)return;let o=!0,u=null;try{u=new Vr("/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]),nn(()=>{a.current.clear(),r(null)},[e]),{latestMessage:t}}import{Box as vo,Text as We}from"ink";import{Fragment as Ur,jsx as Ee,jsxs as tr}from"react/jsx-runtime";var zs=90;function an({children:e}){return Ee(vo,{children:e})}function ln(){let{state:e}=tt(),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)<zs,n=tr(Ur,{children:[Ee(We,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),Ee(We,{children:` ${o}`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:u.toLowerCase()})]}),p=tr(Ur,{children:[Ee(We,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:d}),a&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:"yellow",children:"timeout"})]})]})]});return i?tr(vo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[Ee(an,{children:n}),Ee(an,{children:p})]}):tr(vo,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[n,Ee(We,{dimColor:!0,children:" | "}),p]})}import{Box as Wr,Text as Gr,useInput as Ys}from"ink";import{useState as So,useMemo as Qs}from"react";import Js from"ink-text-input";var Xs=[{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 Co(e){let t=e.toLowerCase();return Xs.filter(r=>r.name.startsWith(t))}function cn(e){let t=Co(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as jr,jsxs as br}from"react/jsx-runtime";function dn({onSubmit:e}){let[t,r]=So(""),[a,o]=So(0),[u,d]=So(!1),l=t.startsWith("/")&&t.length>=1,i=t.slice(1),n=Qs(()=>l?Co(i):[],[l,i]),p=y=>{r(y),y.startsWith("/")?(d(!0),o(0)):d(!1)},g=()=>{let y=t.trim();if(y){if(y.startsWith("/")){let w=y.slice(1),s=cn(w);e(s?`/${s.name}`:y)}else e(y);r(""),d(!1)}},b=y=>{e(`/${y.name}`),r(""),d(!1)};return Ys((y,w)=>{if(!(!u||!l||n.length===0)){if(w.upArrow){o(s=>s<=0?n.length-1:s-1);return}if(w.downArrow){o(s=>s>=n.length-1?0:s+1);return}if(w.tab){let s=n[a];s&&b(s);return}if(w.escape){d(!1),r("");return}}},{isActive:u&&l&&n.length>0}),br(Wr,{flexDirection:"column",children:[u&&l&&n.length>0&&jr(Wr,{flexDirection:"column",marginBottom:0,paddingX:1,children:n.map((y,w)=>{let s=w===a;return br(Wr,{children:[jr(Gr,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),br(Gr,{color:s?"cyan":"white",bold:s,children:["/",y.name]}),br(Gr,{dimColor:!0,children:[" \u2014 ",y.description]})]},y.name)})}),br(Wr,{borderStyle:"round",borderDimColor:!0,children:[jr(Gr,{bold:!0,children:"\u25B8 "}),jr(Js,{value:t,onChange:p,onSubmit:g,placeholder:"Type a message or / for commands..."})]})]})}import{Box as rr,Text as Le,useInput as Zs}from"ink";import{useState as ei}from"react";import{jsx as ze,jsxs as pt}from"react/jsx-runtime";function ti({content:e,expanded:t}){let r=e.split(`
2
+ `);return r.length<=5?ze(Le,{color:"green",children:e}):t?ze(Le,{color:"green",children:e}):pt(Le,{color:"green",children:[r.slice(0,3).join(`
3
3
  `),`
4
- `,pt(_e,{dimColor:!0,children:["(",r.length," lines) [Ctrl+O] expand"]})]})}function Js({event:e,expanded:t}){switch(e.type){case"reasoning":return ze(rr,{children:ze(_e,{color:"gray",children:e.content})});case"tool_call":return ze(rr,{children:pt(_e,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return pt(rr,{flexDirection:"column",children:[ze(_e,{color:"blue",dimColor:!0,children:"[result]"}),ze(Qs,{content:e.content,expanded:t})]});case"error":return ze(rr,{children:pt(_e,{color:"red",children:["[error] ",e.content]})});case"complete":return pt(rr,{flexDirection:"column",marginTop:1,children:[e.content&&ze(_e,{children:e.content}),ze(_e,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&pt(_e,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&pt(_e,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&pt(_e,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function dn({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:pt(rr,{flexDirection:"column",children:[t&&e.length===0&&ze(_e,{dimColor:!0,children:"Waiting for response..."}),e.map((u,d)=>ze(Js,{event:u,expanded:r},d)),o&&ze(_e,{dimColor:!0,children:r?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as Sn,Text as Jr}from"ink";import{Box as Zs,Text as Kr}from"ink";import ei from"ink-spinner";import{jsx as Hr,jsxs as un}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 mn({content:e,phase:t,taskShortId:r}){let a=ti[t];return un(Zs,{children:[Hr(Kr,{color:a.color,children:t==="running"?Hr(ei,{type:"dots"}):a.glyph}),Hr(Kr,{children:" "}),r&&un(Kr,{dimColor:!0,children:["[",r,"] "]}),Hr(Kr,{dimColor:!0,children:e})]})}import{Box as vr,Text as Yr}from"ink";var fn=["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 zr(e){return e?fn[ri(e)%fn.length]:"cyan"}function Xr(e){return e?`T-${e.replace(/-/g,"").slice(0,8).toUpperCase()}`:""}import{jsx as Cr,jsxs as Qr}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 gn(e){let t=zr(e.roleId),r=e.roleName??"?",a=e.taskShortIdLabel?` \xB7 ${e.taskShortIdLabel}`:"";return Qr(vr,{flexDirection:"column",borderStyle:"round",borderColor:t,paddingX:1,children:[Cr(vr,{children:Qr(Yr,{bold:!0,color:t,children:["[",r,a,"]"]})}),Cr(vr,{marginTop:1,children:Cr(Yr,{children:e.content})}),e.attachments&&e.attachments.length>0&&Cr(vr,{flexDirection:"column",marginTop:1,children:e.attachments.map(o=>{let u=o.purpose?`purpose=${o.purpose}, `:"";return Qr(Yr,{dimColor:!0,children:["[file] ",o.filename," (",u,oi(o.size),") \u2192 ",o.locator]},o.artifactId)})}),e.mirroredToTargets&&e.mirroredToTargets.length>0&&Cr(vr,{marginTop:1,children:Qr(Yr,{dimColor:!0,italic:!0,children:["(also delivered to: ",si(e.mirroredToTargets)," @ ",ni(e.createdAt),")"]})})]})}import{Box as Wt,Text as or}from"ink";import ii from"ink-select-input";import{useState as pn}from"react";import{jsx as Bt,jsxs as Sr}from"react/jsx-runtime";var ai=[{label:"\u6279\u51C6 / Yes",value:"\u6279\u51C6"},{label:"\u62D2\u7EDD / No",value:"\u62D2\u7EDD"}];function xn({promptId:e,content:t,shape:r,choices:a,onSubmitted:o,onSubmitFailure:u}){let[d,l]=pn(null),[i,n]=pn(null),p=r==="yes_no"?ai:r==="choose_one"&&a&&a.length>0?a.map(b=>({label:b,value:b})):[],g=async b=>{try{await v("/chat/messages",{method:"POST",body:{content:b.value,source:{type:"tui"},buttonPayload:{promptId:e,value:b.value}}}),l(b.value),o?.(b.value)}catch{n(`Failed to submit. Try again or type "#${e} ${b.value}" in the input bar.`),u?.()}};return Sr(Wt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Sr(or,{bold:!0,color:"yellow",children:["\u26A0 #",e]}),Bt(Wt,{marginTop:1,children:Bt(or,{children:t})}),d?Bt(Wt,{marginTop:1,children:Sr(or,{color:"green",children:["[\u5DF2\u63D0\u4EA4: ",d," \u2713]"]})}):r==="free_input"?Bt(Wt,{marginTop:1,children:Sr(or,{dimColor:!0,children:["Free-input shape: \u8BF7\u56DE\u590D #",e," \u4F60\u7684\u7B54\u590D"]})}):p.length>0?Bt(Wt,{marginTop:1,children:Bt(ii,{items:p,onSelect:g})}):Bt(Wt,{marginTop:1,children:Sr(or,{color:"red",dimColor:!0,children:["(no choices configured for shape=",r,")"]})}),i&&Bt(Wt,{marginTop:1,children:Bt(or,{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 Tn({content:e}){return ui(li,{children:di(ci,{dimColor:!0,children:["\xB7 ",e]})})}import{Box as So,Text as mi}from"ink";import{jsx as yn,jsxs as hn}from"react/jsx-runtime";function bn({threadRoot:e,roleId:t,roleName:r,taskShortIdLabel:a,brief:o,children:u}){let d=zr(t),l=[a,r,o].filter(Boolean),i=l.length>0?l.join(" / "):e.slice(0,8);return hn(So,{flexDirection:"column",borderStyle:"round",borderColor:d,paddingX:1,marginBottom:1,children:[yn(So,{children:hn(mi,{bold:!0,color:d,children:["[Thread ",i,"]"]})}),yn(So,{flexDirection:"column",marginTop:1,children:u})]})}import{useEffect as fi,useState as vn}from"react";function Cn(){let[e,t]=vn(new Map),[r,a]=vn(!1);return fi(()=>{let o=!1;async function u(){try{let d=await v("/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 Lt,jsxs as wo}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 wo(Sn,{flexDirection:"column",marginBottom:1,children:[Lt(Jr,{dimColor:!0,bold:!0,children:o.role==="user"?"You:":"Adam:"}),Lt(Jr,{children:o.content})]},u);if(o.kind==="status_report")return Lt(mn,{content:o.content,phase:gi(o.content),taskShortId:Xr(o.taskId)},u);if(o.kind==="result_delivery")return Lt(gn,{content:o.content,roleId:o.roleId,roleName:e(o.roleId),taskShortIdLabel:Xr(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 Lt(xn,{promptId:d,content:o.content,shape:o.approvalShape,onSubmitted:()=>t?.(d),onSubmitFailure:()=>r?.(d)},u)}return o.kind==="system_note"?Lt(Tn,{content:o.content},u):Lt(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 wn({messages:e,onApprovalSubmitted:t,onApprovalFailed:r}){let{getName:a}=Cn(),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 wo(Sn,{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 Lt(bn,{threadRoot:l,roleId:n.roleId,roleName:a(n.roleId),taskShortIdLabel:Xr(n.taskId),brief:n.content.slice(0,30),children:p.map((g,b)=>"__synthetic"in g?wo(Jr,{dimColor:!0,children:["\u2026 ",g.count," \u6761\u8FDB\u5C55\uFF08\u6700\u8FD1: ",g.lastContent.slice(0,40),"\uFF09"]},`compressed-${b}`):o(g,`${l}-${g.id??b}`))},`thread-${l}`)})]})}import{Box as wr,Text as xt,useInput as Ti}from"ink";import{jsx as Tt,jsxs as kr}from"react/jsx-runtime";function kn({approval:e,onResolved:t}){return Ti(r=>{r==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):r==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),kr(wr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),kr(wr,{marginTop:1,children:[Tt(xt,{children:"Tool: "}),Tt(xt,{bold:!0,children:e.toolName})]}),kr(wr,{children:[Tt(xt,{children:"Input: "}),Tt(xt,{children:JSON.stringify(e.toolInput)})]}),kr(wr,{children:[Tt(xt,{children:"Pattern: "}),Tt(xt,{dimColor:!0,children:e.matchedPattern})]}),kr(wr,{marginTop:1,children:[Tt(xt,{color:"green",children:"[a] Approve"}),Tt(xt,{children:" "}),Tt(xt,{color:"red",children:"[r] Reject"})]})]})}import{Box as Br,Text as Le,useInput as hi}from"ink";import{useState as yi,useEffect as bi}from"react";import{jsx as It,jsxs as at}from"react/jsx-runtime";var vi=300;function Bn({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"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):d==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):d==="p"&&v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let u=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return at(Br,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[It(Le,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),at(Le,{dimColor:!0,children:["Plan ID: ",e.planId]}),at(Le,{dimColor:!0,children:["Time remaining: ",a,"s"]}),at(Br,{marginTop:1,children:[It(Le,{children:"Overall Risk: "}),It(Le,{bold:!0,color:u,children:e.plan.overallRisk.toUpperCase()})]}),at(Le,{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 at(Br,{paddingLeft:2,children:[at(Le,{children:["[",d.index,"] "]}),It(Le,{children:d.description}),at(Le,{dimColor:!0,children:[" (",d.toolsNeeded.join(", "),")"]}),at(Le,{color:l,children:[" [",d.riskLevel,"]"]})]},d.index)}),at(Br,{marginTop:1,children:[It(Le,{dimColor:!0,children:"Permissions: "}),It(Le,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),at(Br,{marginTop:1,children:[It(Le,{color:"green",children:"[a] Allow once "}),It(Le,{color:"green",children:"[p] Allow permanent "}),It(Le,{color:"red",children:"[r] Deny"})]})]})}import{Box as Ae,Text as re,useInput as Pi}from"ink";import{useEffect as Ri,useState as Ft,useCallback as Dn}from"react";import{Box as Be,Text as H,useInput as Ci}from"ink";import{useEffect as Si,useState as nr}from"react";import{jsx as xe,jsxs as J}from"react/jsx-runtime";var In={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 Rn({taskId:e,onBack:t}){let[r,a]=nr(null),[o,u]=nr([]),[d,l]=nr([]),[i,n]=nr(null),[p,g]=nr(In),[b,y]=nr(!1);Si(()=>{let C=!1;return a(null),u([]),l([]),n(null),g(In),y(!1),v(`/tasks/${e}`).then(({task:E})=>{C||a(E)}).catch(E=>{C||n(E instanceof Error?E.message:String(E))}),v(`/tasks/${e}/plan`).then(({plans:E})=>{C||u(E)}).catch(()=>{C||u([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:E})=>{C||l(E)}).catch(()=>{C||l([])}),()=>{C=!0}},[e]);let w=C=>{g(E=>({...E,[C]:!E[C]}))};if(Ci((C,E)=>{if(C==="b"||E.escape){t();return}C==="1"&&w("plan"),C==="2"&&w("result"),C==="3"&&w("routing"),C==="4"&&w("error"),C==="5"&&y(G=>!G)}),i)return J(Be,{flexDirection:"column",children:[J(H,{color:"red",children:["Task detail failed: ",i]}),xe(H,{dimColor:!0,children:"[b] Back"})]});if(!r)return J(H,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let s=o[0],c=Ei(r.deliverTo,r.reportTo),I=d.length>0?`${d.length} delivery event${d.length===1?"":"s"}`:"No delivery events";return J(Be,{flexDirection:"column",children:[J(Be,{children:[J(H,{bold:!0,color:"cyan",children:["Task ",r.id.slice(0,8)]}),xe(H,{dimColor:!0,children:" \u2022 "}),xe(H,{color:wi[r.status]??"white",bold:!0,children:r.status.toUpperCase()})]}),J(H,{dimColor:!0,children:[r.roleId?`role ${r.roleId}`:"no role"," \u2022 ",Pn(r.createdAt)," \u2022 ",Ii(r.totalDurationMs)]}),J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{bold:!0,children:"Summary"}),xe(H,{children:b?r.prompt:ki(r.prompt,240)}),r.prompt.length>240&&J(H,{dimColor:!0,children:["[5] ",b?"collapse prompt":"expand prompt"]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{dimColor:!0,children:["Cost: ",Bi(r.costUsd)]}),J(H,{dimColor:!0,children:["Turns: ",r.numTurns??"\u2014"]}),J(H,{dimColor:!0,children:["Template: ",r.templateId??"\u2014"]}),J(H,{dimColor:!0,children:["Source Session: ",r.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[1] Plan ",p.plan?"hide":"show"]}),xe(H,{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&&J(Be,{marginTop:1,flexDirection:"column",children:[s.plan.steps.map(C=>J(Be,{flexDirection:"column",marginBottom:1,children:[J(H,{children:[C.index,". ",C.description]}),J(H,{dimColor:!0,children:[C.riskLevel," risk \u2022 ",C.toolsNeeded.join(", ")||"no tools listed"]}),C.expectedOutput?J(H,{dimColor:!0,children:["Expected: ",C.expectedOutput]}):null]},C.index)),s.learnedRules&&s.learnedRules.length>0&&J(Be,{flexDirection:"column",children:[xe(H,{color:"blue",bold:!0,children:"Learned Rules"}),s.learnedRules.map((C,E)=>J(H,{dimColor:!0,children:["\u2022 ",C]},E))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[2] Result ",p.result?"hide":"show"]}),xe(H,{dimColor:!0,children:r.result?"Execution produced output.":"No result captured yet."}),p.result&&xe(Be,{marginTop:1,children:xe(H,{children:r.result?An(r.result,18):"No result yet."})})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[3] Routing ",p.routing?"hide":"show"]}),J(H,{dimColor:!0,children:[c," \u2022 ",I]}),p.routing&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Deliver To"}),En(r.deliverTo),xe(H,{color:"cyan",children:"Report To"}),En(r.reportTo),d.length>0&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Recent Delivery"}),d.map(C=>J(H,{dimColor:!0,children:[C.status," \u2022 ",Ai(C)," \u2022 ",Pn(C.createdAt)]},C.id))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[4] Error ",p.error?"hide":"show"]}),xe(H,{dimColor:!0,children:r.error?"Execution returned an error condition.":"No error recorded."}),p.error&&r.error&&xe(Be,{marginTop:1,children:xe(H,{color:"red",children:An(r.error,16)})})]}),xe(Be,{marginTop:1,children:xe(H,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function En(e){return!e||e.length===0?xe(H,{dimColor:!0,children:" none"}):xe(Be,{flexDirection:"column",children:e.map((t,r)=>xe(H,{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 An(e,t){let r=e.split(`
4
+ `,pt(Le,{dimColor:!0,children:["(",r.length," lines) [Ctrl+O] expand"]})]})}function ri({event:e,expanded:t}){switch(e.type){case"reasoning":return ze(rr,{children:ze(Le,{color:"gray",children:e.content})});case"tool_call":return ze(rr,{children:pt(Le,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return pt(rr,{flexDirection:"column",children:[ze(Le,{color:"blue",dimColor:!0,children:"[result]"}),ze(ti,{content:e.content,expanded:t})]});case"error":return ze(rr,{children:pt(Le,{color:"red",children:["[error] ",e.content]})});case"complete":return pt(rr,{flexDirection:"column",marginTop:1,children:[e.content&&ze(Le,{children:e.content}),ze(Le,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&pt(Le,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&pt(Le,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&pt(Le,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function un({events:e,isStreaming:t}){let[r,a]=ei(!1),o=e.some(u=>u.type==="tool_result"&&u.content.split(`
5
+ `).length>5);return Zs((u,d)=>{d.ctrl&&u==="o"&&a(l=>!l)},{isActive:o}),e.length===0&&!t?null:pt(rr,{flexDirection:"column",children:[t&&e.length===0&&ze(Le,{dimColor:!0,children:"Waiting for response..."}),e.map((u,d)=>ze(ri,{event:u,expanded:r},d)),o&&ze(Le,{dimColor:!0,children:r?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as In,Text as Jr}from"ink";import{Box as oi,Text as Kr}from"ink";import ni from"ink-spinner";import{jsx as Hr,jsxs as mn}from"react/jsx-runtime";var si={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 fn({content:e,phase:t,taskShortId:r}){let a=si[t];return mn(oi,{children:[Hr(Kr,{color:a.color,children:t==="running"?Hr(ni,{type:"dots"}):a.glyph}),Hr(Kr,{children:" "}),r&&mn(Kr,{dimColor:!0,children:["[",r,"] "]}),Hr(Kr,{dimColor:!0,children:e})]})}import{Box as vr,Text as Yr}from"ink";var gn=["cyan","magenta","green","yellow","blue","red"];function ii(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r);return Math.abs(t)}function zr(e){return e?gn[ii(e)%gn.length]:"cyan"}function Xr(e){return e?`T-${e.replace(/-/g,"").slice(0,8).toUpperCase()}`:""}import{jsx as Cr,jsxs as Qr}from"react/jsx-runtime";function ai(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function li(e){if(!e)return"";let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function ci(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 pn(e){let t=zr(e.roleId),r=e.roleName??"?",a=e.taskShortIdLabel?` \xB7 ${e.taskShortIdLabel}`:"";return Qr(vr,{flexDirection:"column",borderStyle:"round",borderColor:t,paddingX:1,children:[Cr(vr,{children:Qr(Yr,{bold:!0,color:t,children:["[",r,a,"]"]})}),Cr(vr,{marginTop:1,children:Cr(Yr,{children:e.content})}),e.attachments&&e.attachments.length>0&&Cr(vr,{flexDirection:"column",marginTop:1,children:e.attachments.map(o=>{let u=o.purpose?`purpose=${o.purpose}, `:"";return Qr(Yr,{dimColor:!0,children:["[file] ",o.filename," (",u,ai(o.size),") \u2192 ",o.locator]},o.artifactId)})}),e.mirroredToTargets&&e.mirroredToTargets.length>0&&Cr(vr,{marginTop:1,children:Qr(Yr,{dimColor:!0,italic:!0,children:["(also delivered to: ",ci(e.mirroredToTargets)," @ ",li(e.createdAt),")"]})})]})}import{Box as Wt,Text as or}from"ink";import di from"ink-select-input";import{useState as xn}from"react";import{jsx as Bt,jsxs as Sr}from"react/jsx-runtime";var ui=[{label:"\u6279\u51C6 / Yes",value:"\u6279\u51C6"},{label:"\u62D2\u7EDD / No",value:"\u62D2\u7EDD"}];function Tn({promptId:e,content:t,shape:r,choices:a,onSubmitted:o,onSubmitFailure:u}){let[d,l]=xn(null),[i,n]=xn(null),p=r==="yes_no"?ui:r==="choose_one"&&a&&a.length>0?a.map(b=>({label:b,value:b})):[],g=async b=>{try{await v("/chat/messages",{method:"POST",body:{content:b.value,source:{type:"tui"},buttonPayload:{promptId:e,value:b.value}}}),l(b.value),o?.(b.value)}catch{n(`Failed to submit. Try again or type "#${e} ${b.value}" in the input bar.`),u?.()}};return Sr(Wt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Sr(or,{bold:!0,color:"yellow",children:["\u26A0 #",e]}),Bt(Wt,{marginTop:1,children:Bt(or,{children:t})}),d?Bt(Wt,{marginTop:1,children:Sr(or,{color:"green",children:["[\u5DF2\u63D0\u4EA4: ",d," \u2713]"]})}):r==="free_input"?Bt(Wt,{marginTop:1,children:Sr(or,{dimColor:!0,children:["Free-input shape: \u8BF7\u56DE\u590D #",e," \u4F60\u7684\u7B54\u590D"]})}):p.length>0?Bt(Wt,{marginTop:1,children:Bt(di,{items:p,onSelect:g})}):Bt(Wt,{marginTop:1,children:Sr(or,{color:"red",dimColor:!0,children:["(no choices configured for shape=",r,")"]})}),i&&Bt(Wt,{marginTop:1,children:Bt(or,{color:"red",children:i})})]})}import{Box as mi,Text as fi}from"ink";import{jsx as pi,jsxs as gi}from"react/jsx-runtime";function hn({content:e}){return pi(mi,{children:gi(fi,{dimColor:!0,children:["\xB7 ",e]})})}To();import{Box as xi,Text as yn}from"ink";import{jsx as Ti,jsxs as bn}from"react/jsx-runtime";function vn({content:e}){return bn(xi,{flexDirection:"column",children:[bn(yn,{color:"yellow",children:["\u26A0\uFE0F ",zo]}),Ti(yn,{dimColor:!0,children:e})]})}import{Box as wo,Text as hi}from"ink";import{jsx as Sn,jsxs as Cn}from"react/jsx-runtime";function wn({threadRoot:e,roleId:t,roleName:r,taskShortIdLabel:a,brief:o,children:u}){let d=zr(t),l=[a,r,o].filter(Boolean),i=l.length>0?l.join(" / "):e.slice(0,8);return Cn(wo,{flexDirection:"column",borderStyle:"round",borderColor:d,paddingX:1,marginBottom:1,children:[Sn(wo,{children:Cn(hi,{bold:!0,color:d,children:["[Thread ",i,"]"]})}),Sn(wo,{flexDirection:"column",marginTop:1,children:u})]})}import{useEffect as yi,useState as kn}from"react";function Bn(){let[e,t]=kn(new Map),[r,a]=kn(!1);return yi(()=>{let o=!1;async function u(){try{let d=await v("/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 It,jsxs as ko}from"react/jsx-runtime";function bi(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 vi(e,t,r){return function(o,u){if(!o.kind||o.kind==="user_message"||o.kind==="assistant_text")return ko(In,{flexDirection:"column",marginBottom:1,children:[It(Jr,{dimColor:!0,bold:!0,children:o.role==="user"?"You:":"Adam:"}),It(Jr,{children:o.content})]},u);if(o.kind==="status_report")return It(fn,{content:o.content,phase:bi(o.content),taskShortId:Xr(o.taskId)},u);if(o.kind==="result_delivery")return It(pn,{content:o.content,roleId:o.roleId,roleName:e(o.roleId),taskShortIdLabel:Xr(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 It(Tn,{promptId:d,content:o.content,shape:o.approvalShape,onSubmitted:()=>t?.(d),onSubmitFailure:()=>r?.(d)},u)}return o.kind==="system_note"?It(hn,{content:o.content},u):o.kind==="audit_note"?It(vn,{content:o.content},u):It(Jr,{dimColor:!0,children:o.content},u)}}function Ci(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 En({messages:e,onApprovalSubmitted:t,onApprovalFailed:r}){let{getName:a}=Bn(),o=vi(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 ko(In,{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=Ci(i);return It(wn,{threadRoot:l,roleId:n.roleId,roleName:a(n.roleId),taskShortIdLabel:Xr(n.taskId),brief:n.content.slice(0,30),children:p.map((g,b)=>"__synthetic"in g?ko(Jr,{dimColor:!0,children:["\u2026 ",g.count," \u6761\u8FDB\u5C55\uFF08\u6700\u8FD1: ",g.lastContent.slice(0,40),"\uFF09"]},`compressed-${b}`):o(g,`${l}-${g.id??b}`))},`thread-${l}`)})]})}import{Box as wr,Text as xt,useInput as Si}from"ink";import{jsx as Tt,jsxs as kr}from"react/jsx-runtime";function An({approval:e,onResolved:t}){return Si(r=>{r==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):r==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),kr(wr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),kr(wr,{marginTop:1,children:[Tt(xt,{children:"Tool: "}),Tt(xt,{bold:!0,children:e.toolName})]}),kr(wr,{children:[Tt(xt,{children:"Input: "}),Tt(xt,{children:JSON.stringify(e.toolInput)})]}),kr(wr,{children:[Tt(xt,{children:"Pattern: "}),Tt(xt,{dimColor:!0,children:e.matchedPattern})]}),kr(wr,{marginTop:1,children:[Tt(xt,{color:"green",children:"[a] Approve"}),Tt(xt,{children:" "}),Tt(xt,{color:"red",children:"[r] Reject"})]})]})}import{Box as Br,Text as _e,useInput as wi}from"ink";import{useState as ki,useEffect as Bi}from"react";import{jsx as Et,jsxs as at}from"react/jsx-runtime";var Ii=300;function Pn({approval:e,onResolved:t,onTimeout:r}){let[a,o]=ki(Ii);Bi(()=>{let d=setInterval(()=>{o(l=>l<=1?(clearInterval(d),r(),0):l-1)},1e3);return()=>clearInterval(d)},[r]),wi(d=>{d==="a"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):d==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):d==="p"&&v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let u=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return at(Br,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Et(_e,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),at(_e,{dimColor:!0,children:["Plan ID: ",e.planId]}),at(_e,{dimColor:!0,children:["Time remaining: ",a,"s"]}),at(Br,{marginTop:1,children:[Et(_e,{children:"Overall Risk: "}),Et(_e,{bold:!0,color:u,children:e.plan.overallRisk.toUpperCase()})]}),at(_e,{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 at(Br,{paddingLeft:2,children:[at(_e,{children:["[",d.index,"] "]}),Et(_e,{children:d.description}),at(_e,{dimColor:!0,children:[" (",d.toolsNeeded.join(", "),")"]}),at(_e,{color:l,children:[" [",d.riskLevel,"]"]})]},d.index)}),at(Br,{marginTop:1,children:[Et(_e,{dimColor:!0,children:"Permissions: "}),Et(_e,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),at(Br,{marginTop:1,children:[Et(_e,{color:"green",children:"[a] Allow once "}),Et(_e,{color:"green",children:"[p] Allow permanent "}),Et(_e,{color:"red",children:"[r] Deny"})]})]})}import{Box as Ae,Text as re,useInput as Li}from"ink";import{useEffect as _i,useState as Ft,useCallback as Ln}from"react";import{Box as Be,Text as H,useInput as Ei}from"ink";import{useEffect as Ai,useState as nr}from"react";import{jsx as xe,jsxs as J}from"react/jsx-runtime";var Rn={plan:!0,result:!1,routing:!0,error:!0},Pi={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function Nn({taskId:e,onBack:t}){let[r,a]=nr(null),[o,u]=nr([]),[d,l]=nr([]),[i,n]=nr(null),[p,g]=nr(Rn),[b,y]=nr(!1);Ai(()=>{let C=!1;return a(null),u([]),l([]),n(null),g(Rn),y(!1),v(`/tasks/${e}`).then(({task:E})=>{C||a(E)}).catch(E=>{C||n(E instanceof Error?E.message:String(E))}),v(`/tasks/${e}/plan`).then(({plans:E})=>{C||u(E)}).catch(()=>{C||u([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:E})=>{C||l(E)}).catch(()=>{C||l([])}),()=>{C=!0}},[e]);let w=C=>{g(E=>({...E,[C]:!E[C]}))};if(Ei((C,E)=>{if(C==="b"||E.escape){t();return}C==="1"&&w("plan"),C==="2"&&w("result"),C==="3"&&w("routing"),C==="4"&&w("error"),C==="5"&&y(G=>!G)}),i)return J(Be,{flexDirection:"column",children:[J(H,{color:"red",children:["Task detail failed: ",i]}),xe(H,{dimColor:!0,children:"[b] Back"})]});if(!r)return J(H,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let s=o[0],c=$i(r.deliverTo,r.reportTo),I=d.length>0?`${d.length} delivery event${d.length===1?"":"s"}`:"No delivery events";return J(Be,{flexDirection:"column",children:[J(Be,{children:[J(H,{bold:!0,color:"cyan",children:["Task ",r.id.slice(0,8)]}),xe(H,{dimColor:!0,children:" \u2022 "}),xe(H,{color:Pi[r.status]??"white",bold:!0,children:r.status.toUpperCase()})]}),J(H,{dimColor:!0,children:[r.roleId?`role ${r.roleId}`:"no role"," \u2022 ",$n(r.createdAt)," \u2022 ",Mi(r.totalDurationMs)]}),J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{bold:!0,children:"Summary"}),xe(H,{children:b?r.prompt:Ri(r.prompt,240)}),r.prompt.length>240&&J(H,{dimColor:!0,children:["[5] ",b?"collapse prompt":"expand prompt"]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{dimColor:!0,children:["Cost: ",Di(r.costUsd)]}),J(H,{dimColor:!0,children:["Turns: ",r.numTurns??"\u2014"]}),J(H,{dimColor:!0,children:["Template: ",r.templateId??"\u2014"]}),J(H,{dimColor:!0,children:["Source Session: ",r.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[1] Plan ",p.plan?"hide":"show"]}),xe(H,{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&&J(Be,{marginTop:1,flexDirection:"column",children:[s.plan.steps.map(C=>J(Be,{flexDirection:"column",marginBottom:1,children:[J(H,{children:[C.index,". ",C.description]}),J(H,{dimColor:!0,children:[C.riskLevel," risk \u2022 ",C.toolsNeeded.join(", ")||"no tools listed"]}),C.expectedOutput?J(H,{dimColor:!0,children:["Expected: ",C.expectedOutput]}):null]},C.index)),s.learnedRules&&s.learnedRules.length>0&&J(Be,{flexDirection:"column",children:[xe(H,{color:"blue",bold:!0,children:"Learned Rules"}),s.learnedRules.map((C,E)=>J(H,{dimColor:!0,children:["\u2022 ",C]},E))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[2] Result ",p.result?"hide":"show"]}),xe(H,{dimColor:!0,children:r.result?"Execution produced output.":"No result captured yet."}),p.result&&xe(Be,{marginTop:1,children:xe(H,{children:r.result?Mn(r.result,18):"No result yet."})})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[3] Routing ",p.routing?"hide":"show"]}),J(H,{dimColor:!0,children:[c," \u2022 ",I]}),p.routing&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Deliver To"}),Dn(r.deliverTo),xe(H,{color:"cyan",children:"Report To"}),Dn(r.reportTo),d.length>0&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Recent Delivery"}),d.map(C=>J(H,{dimColor:!0,children:[C.status," \u2022 ",Ni(C)," \u2022 ",$n(C.createdAt)]},C.id))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[4] Error ",p.error?"hide":"show"]}),xe(H,{dimColor:!0,children:r.error?"Execution returned an error condition.":"No error recorded."}),p.error&&r.error&&xe(Be,{marginTop:1,children:xe(H,{color:"red",children:Mn(r.error,16)})})]}),xe(Be,{marginTop:1,children:xe(H,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function Dn(e){return!e||e.length===0?xe(H,{dimColor:!0,children:" none"}):xe(Be,{flexDirection:"column",children:e.map((t,r)=>xe(H,{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 Mn(e,t){let r=e.split(`
6
6
  `);return r.length<=t?e:`${r.slice(0,t).join(`
7
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 Pn(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 de,jsxs as ue}from"react/jsx-runtime";var Mn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},Zr=["all","pending","queued","running","completed","failed","cancelled","blocked"],ko=15;function to({onBack:e}){let[t,r]=Ft([]),[a,o]=Ft(!0),[u,d]=Ft("list"),[l,i]=Ft(0),[n,p]=Ft("all"),[g,b]=Ft(0),[y,w]=Ft(0),[s,c]=Ft(null),I=Dn(async()=>{o(!0);try{let N=new URLSearchParams({limit:"100"});n!=="all"&&N.set("status",n);let O=await v(`/tasks?${N}`);r(O.tasks)}catch{r([])}finally{o(!1)}},[n]);Ri(()=>{I()},[I]);let C=Math.max(1,Math.ceil(t.length/ko)),E=t.slice(y*ko,(y+1)*ko),G=Dn(async()=>{let N=E[l];if(N)try{await v(`/tasks/${N.id}/cancel`,{method:"POST"}),c(`Cancelled: ${N.id.slice(0,8)}`),d("list"),I()}catch(O){c(`Failed: ${O instanceof Error?O.message:String(O)}`),d("list")}},[E,l,I]);if(Pi((N,O)=>{if(u==="detail"){(O.escape||O.return||N==="q")&&d("list");return}if(u==="cancelling"){N==="y"?G():d("list");return}if(u==="filter"){if(O.escape){d("list");return}O.upArrow&&g>0&&b(V=>V-1),O.downArrow&&g<Zr.length-1&&b(V=>V+1),O.return&&(p(Zr[g]),w(0),i(0),d("list"));return}if(O.escape||N==="q"){e();return}if(O.upArrow&&l>0&&i(V=>V-1),O.downArrow&&l<E.length-1&&i(V=>V+1),O.return&&E[l]&&d("detail"),N==="x"&&E[l]){let V=E[l];["running","pending","queued","paused"].includes(V.status)?(d("cancelling"),c(null)):c(`Cannot cancel task in status: ${V.status}`)}N==="f"&&(b(Zr.indexOf(n)),d("filter")),N==="r"&&I(),(O.pageDown||N==="n")&&y<C-1&&(w(V=>V+1),i(0)),(O.pageUp||N==="p")&&y>0&&(w(V=>V-1),i(0))}),a)return de(re,{dimColor:!0,children:"Loading tasks..."});if(u==="filter")return ue(Ae,{flexDirection:"column",children:[de(re,{bold:!0,children:"Filter by status:"}),Zr.map((N,O)=>de(Ae,{children:ue(re,{color:O===g?"cyan":"white",children:[O===g?"> ":" ",N,N===n?" (current)":""]})},N)),de(re,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(u==="detail"&&E[l])return de(Rn,{taskId:E[l].id,onBack:()=>d("list")});if(u==="cancelling"&&E[l])return ue(Ae,{flexDirection:"column",children:[ue(re,{color:"red",children:['Cancel task "',E[l].id.slice(0,8),'"? (y/n)']}),s&&de(re,{color:"red",children:s})]});let Y=E[l]??null;return ue(Ae,{flexDirection:"column",children:[ue(Ae,{children:[ue(re,{bold:!0,children:["Tasks (",t.length,")"]}),n!=="all"&&ue(re,{dimColor:!0,children:[" [filter: ",n,"]"]}),ue(re,{dimColor:!0,children:[" \u2022 Page ",y+1,"/",C]})]}),s&&de(re,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?ue(re,{dimColor:!0,children:["No tasks found",n!=="all"?` with status "${n}"`:"","."]}):ue(Ae,{marginTop:1,flexDirection:"row",gap:2,children:[de(Ae,{flexDirection:"column",flexGrow:3,children:E.map((N,O)=>{let V=O===l,B=Mn[N.status]??"white";return ue(Ae,{flexDirection:"column",marginBottom:1,children:[ue(Ae,{children:[de(re,{color:V?"cyan":"gray",bold:V,children:V?"\u276F ":" "}),de(re,{color:B,bold:!0,children:N.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${N.id.slice(0,8)}`})]}),de(Ae,{paddingLeft:2,children:de(re,{color:V?"white":void 0,children:eo(N.prompt,V?72:56)})}),de(Ae,{paddingLeft:2,children:ue(re,{dimColor:!0,children:[_n(N.createdAt)," \u2022 ",$n(N)," \u2022 ",Nn(N.costUsd)]})})]},N.id)})}),de(Ae,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?ue(Mi,{children:[de(re,{bold:!0,children:"Preview"}),ue(Ae,{marginTop:1,children:[de(re,{color:Mn[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),de(re,{children:eo(Y.prompt,220)}),ue(Ae,{marginTop:1,flexDirection:"column",children:[ue(re,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),ue(re,{dimColor:!0,children:["Created: ",_n(Y.createdAt)]}),ue(re,{dimColor:!0,children:["Duration: ",$n(Y)]}),ue(re,{dimColor:!0,children:["Cost: ",Nn(Y.costUsd)]}),ue(re,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"red",bold:!0,children:"Error"}),de(re,{color:"red",children:eo(Y.error,180)})]}):Y.result?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"green",bold:!0,children:"Latest Result"}),de(re,{children:eo(Y.result,180)})]}):null,de(Ae,{marginTop:1,children:de(re,{dimColor:!0,children:"Enter opens full detail"})})]}):de(re,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Di(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function eo(e,t){return Di(e.replace(/\s+/g," ").trim(),t)}function $n(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 Nn(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function _n(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`}Ho();import{Box as Gt,Text as Ge,useInput as $i}from"ink";import{useEffect as Ni,useState as Ln}from"react";import{readFileSync as _i,existsSync as Li}from"fs";import{parse as Fi}from"yaml";import{Fragment as qi,jsx as Fe,jsxs as Xe}from"react/jsx-runtime";function Fn({onBack:e}){let[t,r]=Ln(null),[a,o]=Ln(null);return $i((u,d)=>{(d.escape||u==="q")&&e()}),Ni(()=>{try{let u=Ko;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?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{color:"red",children:a}),Fe(Ge,{dimColor:!0,children:"Press Esc to go back"})]}):t?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{bold:!0,children:"Configuration (Esc to go back)"}),Fe(Gt,{marginTop:1,flexDirection:"column",children:Fe(Bo,{obj:t,indent:0})})]}):Fe(Ge,{dimColor:!0,children:"Loading config..."})}function Bo({obj:e,indent:t}){let r=" ".repeat(t);return Fe(qi,{children:Object.entries(e).map(([a,o])=>Fe(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)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),t.length===0?Xe(Ge,{dimColor:!0,children:[o," []"]}):t.map((u,d)=>Fe(On,{value:u,indent:r+1,parentKey:a,index:d},`${e}-${d}`))]}):t&&typeof t=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),Fe(Bo,{obj:t,indent:r+1})]}):Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),": ",qn(a,Vn(t))]})}function On({value:e,indent:t,parentKey:r,index:a}){let o=" ".repeat(t);return Array.isArray(e)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"- [",a,"]"]}),e.map((u,d)=>Fe(On,{value:u,indent:t+1,parentKey:r,index:d},`${a}-${d}`))]}):e&&typeof e=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"-"]}),Fe(Bo,{obj:e,indent:t+1})]}):Xe(Ge,{children:[o,"- ",qn(r,Vn(e))]})}function qn(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 Vn(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as ro,Text as lt,useInput as Vi}from"ink";import{useEffect as Ui,useState as Io}from"react";import{jsx as Ir,jsxs as ht}from"react/jsx-runtime";function Un({onBack:e}){let[t,r]=Io([]),[a,o]=Io(!0),[u,d]=Io(null);return Vi((l,i)=>{(i.escape||l==="q")&&e()}),Ui(()=>{v("/evolution-audit?limit=20").then(l=>{r(l),o(!1)}).catch(l=>{d(l.message),o(!1)})},[]),a?Ir(lt,{dimColor:!0,children:"Loading evolution log..."}):u?ht(ro,{flexDirection:"column",children:[Ir(lt,{color:"red",children:u}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?ht(ro,{flexDirection:"column",children:[Ir(lt,{dimColor:!0,children:"No evolution records yet"}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):ht(ro,{flexDirection:"column",children:[ht(lt,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(l=>ht(ro,{flexDirection:"column",marginTop:1,children:[ht(lt,{bold:!0,children:["[",new Date(l.timestamp).toLocaleString(),"]"]}),l.triggerTaskId&&ht(lt,{dimColor:!0,children:[" Task: ",l.triggerTaskId.slice(0,8)]}),l.diff.split(`
9
- `).map((i,n)=>i.startsWith("+")?ht(lt,{color:"green",children:[" ",i]},n):i.startsWith("-")?ht(lt,{color:"red",children:[" ",i]},n):ht(lt,{dimColor:!0,children:[" ",i]},n))]},l.id))]})}import{Box as Et,Text as Te,useInput as Wi}from"ink";import Gi from"ink-text-input";import{useEffect as ji,useState as sr}from"react";import{jsx as je,jsxs as Pe}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 oo({onBack:e}){let[t,r]=sr([]),[a,o]=sr(null),[u,d]=sr("list"),[l,i]=sr(""),[n,p]=sr(!1),[g,b]=sr(null);Wi((s,c)=>{if(u==="create"){c.escape&&(d("list"),i(""),b(null));return}(c.escape||s==="q")&&e(),s==="c"&&(d("create"),b(null)),s==="r"&&y()});let y=()=>{v("/goals?limit=20").then(({goals:s})=>r(s)).catch(s=>o(s.message))};ji(()=>{y()},[]);let w=async s=>{if(s.trim()){p(!0),b(null);try{let c=await v("/goals",{method:"POST",body:{input:s.trim()}});b(`Goal created: ${c.goal.name}`),i(""),d("list"),y()}catch(c){b(`Failed: ${c instanceof Error?c.message:String(c)}`)}finally{p(!1)}}};return a?Pe(Et,{flexDirection:"column",children:[Pe(Te,{color:"red",children:["Failed to load goals: ",a]}),je(Te,{dimColor:!0,children:"Press Esc or q to return"})]}):u==="create"?Pe(Et,{flexDirection:"column",children:[je(Te,{bold:!0,children:"Create Goal"}),je(Te,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Pe(Et,{marginTop:1,children:[je(Te,{color:"cyan",children:"> "}),je(Gi,{value:l,onChange:i,onSubmit:w})]}),n&&je(Te,{color:"yellow",children:"Creating goal..."}),g&&je(Te,{color:g.startsWith("Failed")?"red":"green",children:g}),je(Te,{dimColor:!0,children:"Press Esc to cancel"})]}):Pe(Et,{flexDirection:"column",children:[Pe(Te,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?je(Te,{dimColor:!0,children:"No goals found. Press c to create one."}):je(Et,{marginTop:1,flexDirection:"column",children:t.map(s=>{let c=s.targetValue>0?s.currentValue/s.targetValue:0,I=Ki[s.status]??"white";return Pe(Et,{marginBottom:1,flexDirection:"column",children:[Pe(Et,{children:[je(Te,{bold:!0,color:I,children:s.name}),Pe(Te,{dimColor:!0,children:[" (",s.role,")"]}),je(Te,{dimColor:!0,children:" \u2014 "}),je(Te,{color:I,children:s.status})]}),Pe(Et,{children:[Pe(Te,{dimColor:!0,children:[" ",Hi(c)," "]}),Pe(Te,{color:c>=1?"green":"white",children:[Math.round(c*100),"%"]}),Pe(Te,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),Pe(Et,{children:[Pe(Te,{dimColor:!0,children:[" \u23F0 ",zi(s.deadline)," left"]}),Pe(Te,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),Pe(Te,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),je(Te,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as ir,Text as rt,useInput as Xi}from"ink";import{useEffect as Yi,useState as Wn}from"react";import{jsx as Pt,jsxs as At}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 Gn({onBack:e}){let[t,r]=Wn([]),[a,o]=Wn(null);if(Xi((d,l)=>{(l.escape||d==="q")&&e()}),Yi(()=>{v("/strategies?limit=50").then(d=>r(d.strategies??[])).catch(d=>o(d.message))},[]),a)return At(ir,{flexDirection:"column",children:[At(rt,{color:"red",children:["Failed to load strategies: ",a]}),Pt(rt,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return At(ir,{flexDirection:"column",children:[Pt(rt,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Pt(rt,{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 At(ir,{flexDirection:"column",children:[Pt(rt,{bold:!0,children:"Strategy Lab"}),Pt(rt,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Pt(ir,{marginTop:1,flexDirection:"column",children:Array.from(u.entries()).map(([d,l])=>At(ir,{marginBottom:1,flexDirection:"column",children:[Pt(rt,{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 At(ir,{children:[Pt(rt,{dimColor:!0,children:" "}),At(rt,{children:[Qi(i.alpha,i.beta)," "]}),At(rt,{color:n>.6?"green":n>.4?"yellow":"red",children:[(n*100).toFixed(0),"%"]}),At(rt,{dimColor:!0,children:[" ",i.name," (\u03B1=",i.alpha.toFixed(1)," \u03B2=",i.beta.toFixed(1)," trials=",i.totalTrials,")"]})]},i.id)})]},d))}),Pt(rt,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as ye,Text as W,useInput as ra}from"ink";import Eo from"ink-text-input";import{useEffect as oa,useState as Oe,useCallback as yt}from"react";import{CronExpressionParser as na}from"cron-parser";import{useState as Ji,useEffect as Zi,useCallback as jn,useRef as ea}from"react";var ta=3e3;function ot(){let[e,t]=Ji(null),r=ea(null),a=jn(()=>{r.current&&(clearTimeout(r.current),r.current=null),t(null)},[]),o=jn((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 Z,jsxs as Q}from"react/jsx-runtime";var Ao=["manual","cron","once","template_complete"],Kn=["cron","once","template_complete"],no={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function sa(e){try{return na.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function so({onBack:e}){let[t,r]=Oe([]),[a,o]=Oe(!0),[u,d]=Oe(0),[l,i]=Oe("list"),[n,p]=Oe({...no}),[g,b]=Oe("name"),[y,w]=Oe(null),{message:s,setMessage:c,clearMessage:I}=ot(),[C,E]=Oe(!1),[G,Y]=Oe(!1),[N,O]=Oe({}),[V,B]=Oe(null),[z,se]=Oe(!1),[ne,$e]=Oe(!1),[ge,D]=Oe([]),[ie,L]=Oe({}),ae=yt(async S=>{try{let A=await v(`/template-executions?templateId=${S}&limit=5`);D(A.executions??[])}catch{D([])}},[]),Ce=yt(async(S,A)=>{try{await v(`/executions/${S}/feedback`,{method:"POST",body:{rating:A}}),L($=>({...$,[S]:A}))}catch($){c(`Feedback failed: ${$ instanceof Error?$.message:String($)}`,"error")}},[c]),_=yt(()=>{o(!0),v("/task-templates").then(({templates:S})=>{r(S),new Set(S.flatMap($=>$.steps?.map(le=>le.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:$})=>{if(!Array.isArray($)){O({});return}O(Object.fromEntries($.map(le=>[le.id,le.name])))}).catch(()=>O({})):O({}),o(!1)}).catch(()=>o(!1))},[]);oa(()=>{_()},[_]);let K=l==="create"||l==="edit",ee=yt(async()=>{let S=t[u];if(!(!S||C)){E(!0),c(`Triggering ${S.name}...`,"loading");try{let A=await v(`/task-templates/${S.id}/run`,{method:"POST"});c(`Triggered: ${S.name} (${A.executionId})`,"success")}catch(A){c(`Trigger failed: ${A instanceof Error?A.message:String(A)}`,"error")}finally{E(!1)}}},[t,u,C,c]),pe=yt(async()=>{let S=t[u];if(!S||G)return;if(!Kn.includes(S.trigger?.type??"manual")){c("Toggle not applicable for manual triggers","error");return}let A=!S.enabled;Y(!0),c(`${S.name} \u2192 ${A?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${S.id}`,{method:"PATCH",body:{enabled:A}}),r($=>$.map(le=>le.id===S.id?{...le,enabled:A}:le)),c(`${S.name} ${A?"enabled":"disabled"}`,"success")}catch($){c(`Toggle failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{Y(!1)}},[t,u,G,c]),St=yt(async()=>{if(z)return;let S=t[u];if(S){se(!0);try{let A=await v(`/task-templates/${S.id}/dependents`,{method:"GET"});B({templateId:S.id,templateName:S.name,executionCount:A.dependents.executionCount,taskCount:A.dependents.taskCount}),A.dependents.taskCount===0&&A.dependents.executionCount===0?c(`Delete "${S.name}"? Press d to confirm, Esc to cancel.`,"loading"):c(`"${S.name}" has ${A.dependents.executionCount} template execution${A.dependents.executionCount===1?"":"s"}, ${A.dependents.taskCount} task${A.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(A){c(`Failed to inspect dependents: ${A instanceof Error?A.message:String(A)}`,"error")}finally{se(!1)}}},[t,u,c,z]),gt=yt(async S=>{let A=V;if(A){B(null);try{let $=await v(`/task-templates/${A.templateId}?mode=${S}`,{method:"DELETE"}),le=[];$.deletedCounts.templateExecutions>0&&le.push(`${$.deletedCounts.templateExecutions} template exec`),$.deletedCounts.tasks>0&&le.push(`${$.deletedCounts.tasks} task${$.deletedCounts.tasks===1?"":"s"}`);let Ue=le.length?` (+${le.join(", ")})`:"";c(`Deleted: ${A.templateName}${Ue}`,"success"),_(),d(Ne=>Math.max(0,Math.min(Ne,t.length-2)))}catch($){c(`Delete failed: ${$ instanceof Error?$.message:String($)}`,"error")}}},[V,_,c,t.length]),et=yt(()=>{B(null),I()},[I]),Ut=yt(()=>{let S=t[u];S&&(w(S.id),p({name:S.name,triggerType:S.trigger?.type??"manual",cron:S.trigger?.cron??"",targetTemplateId:S.trigger?.type==="template_complete"?S.trigger.event?.split(":")[1]??"":"",stepPrompt:S.steps?.[0]?.prompt??""}),b("name"),i("edit"))},[t,u]),Jt=yt(async()=>{let S={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 v("/task-templates",{method:"POST",body:S}),c(`Created: ${n.name}`,"success")):l==="edit"&&y&&(await v(`/task-templates/${y}`,{method:"PATCH",body:S}),c(`Updated: ${n.name}`,"success"))}catch(A){c(`Save failed: ${A instanceof Error?A.message:String(A)}`,"error")}i("list"),p({...no}),w(null),_()},[n,l,y,_]);return ra((S,A)=>{if(K){if(A.escape){i("list"),p({...no}),w(null);return}if(A.return){let $=["name","triggerType","cron","stepPrompt"],Ue=n.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:$.filter(M=>M!=="targetTemplateId"),Ne=Ue.indexOf(g);if(Ne<Ue.length-1){let M=Ne+1;if(Ue[M]==="cron"&&n.triggerType!=="cron"&&M++,M<Ue.length){b(Ue[M]);return}}Jt();return}if(A.tab&&g==="triggerType"){p($=>{let le=Ao.indexOf($.triggerType);return{...$,triggerType:Ao[(le+1)%Ao.length]}});return}if(A.tab&&g==="targetTemplateId"){p($=>{let le=t.filter(M=>M.id!==y),Ue=le.findIndex(M=>M.id===$.targetTemplateId),Ne=le[(Ue+1)%le.length];return{...$,targetTemplateId:Ne?.id??""}});return}return}if(V){if(A.escape){et();return}if(S==="D"&&A.shift){gt("with_tasks");return}if(S==="d"&&!A.shift){gt("template_only");return}return}if(A.escape||S==="q"){e();return}if(A.upArrow){d($=>Math.max(0,$-1));return}if(A.downArrow){d($=>Math.min(t.length-1,$+1));return}if(S==="t"){ee();return}if(S==="d"&&!A.shift){St();return}if(S==="e"){Ut();return}if(S==="c"){p({...no}),b("name"),i("create");return}if(S==="s"||S===" "){pe();return}if(S==="r"&&(_(),I()),S==="x"){let $=t[u];if(!$)return;ne?($e(!1),D([])):($e(!0),ae($.id));return}if(S==="g"&&ne&&ge.length>0){Ce(ge[0].id,"good");return}if(S==="b"&&ne&&ge.length>0){Ce(ge[0].id,"bad");return}}),a?Z(W,{dimColor:!0,children:"Loading templates..."}):K?Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:[l==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),Q(ye,{marginTop:1,flexDirection:"column",children:[Q(ye,{children:[Q(W,{bold:g==="name",color:g==="name"?"cyan":void 0,children:["Name:"," "]}),g==="name"?Z(Eo,{value:n.name,onChange:S=>p(A=>({...A,name:S})),placeholder:"template name"}):Z(W,{children:n.name||"(empty)"})]}),Q(ye,{children:[Q(W,{bold:g==="triggerType",color:g==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),Z(W,{children:n.triggerType}),g==="triggerType"&&Z(W,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),n.triggerType==="cron"&&Q(ye,{children:[Q(W,{bold:g==="cron",color:g==="cron"?"cyan":void 0,children:["Cron:"," "]}),g==="cron"?Z(Eo,{value:n.cron,onChange:S=>p(A=>({...A,cron:S})),placeholder:"*/5 * * * *"}):Z(W,{children:n.cron||"(empty)"})]}),n.triggerType==="template_complete"&&Q(ye,{children:[Q(W,{bold:g==="targetTemplateId",color:g==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),Z(W,{children:(()=>{let S=t.find(A=>A.id===n.targetTemplateId);return S?S.name:n.targetTemplateId?`(id: ${n.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),g==="targetTemplateId"&&Z(W,{dimColor:!0,children:" (Tab to cycle)"})]}),Q(ye,{children:[Q(W,{bold:g==="stepPrompt",color:g==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),g==="stepPrompt"?Z(Eo,{value:n.stepPrompt,onChange:S=>p(A=>({...A,stepPrompt:S})),placeholder:"What should this template do?"}):Z(W,{children:n.stepPrompt||"(empty)"})]})]}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&Z(ye,{marginTop:1,children:Q(W,{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?Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"No templates found. Press c to create one."})}):Z(ye,{marginTop:1,flexDirection:"column",children:t.map((S,A)=>{let $=A===u,le=S.trigger?.type==="cron"&&S.trigger?.cron?sa(S.trigger.cron):"",Ue=new Set(S.steps?.filter(M=>M.roleId).map(M=>M.roleId)),Ne=S.steps?.length>1?`${S.steps.length} steps${Ue.size>0?` / ${Ue.size} roles`:""}`:`${S.steps?.length??0} step`;return Q(ye,{flexDirection:"column",children:[Q(ye,{children:[Z(W,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),Z(W,{color:$?"cyan":void 0,bold:$,children:Er(S.name,24)}),Z(W,{dimColor:!0,children:Er(S.trigger?.type,10)}),Kn.includes(S.trigger?.type??"manual")?Z(W,{color:S.enabled?"green":"gray",children:Er(S.enabled?"on":"off",6)}):Z(W,{dimColor:!0,children:Er("\u2014",6)}),Z(W,{dimColor:!0,children:Er(Ne,18)}),le&&Q(W,{dimColor:!0,children:["next: ",le]})]}),$&&Q(ia,{children:[S.config?.delivery&&Z(ye,{marginLeft:4,marginTop:0,children:Q(W,{dimColor:!0,children:[" Delivery: ",S.config.delivery.mode,S.config.delivery.mode==="primary-artifact"&&S.config.delivery.primaryArtifact&&` (${S.config.delivery.primaryArtifact.stepId}/${S.config.delivery.primaryArtifact.key})`]})}),S.steps&&S.steps.length>1&&Z(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:S.steps.map((M,Zt)=>Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt+1,". "]}),Z(W,{dimColor:!0,children:M.id}),M.roleId&&Q(W,{color:"yellow",children:[" @",N[M.roleId]??M.roleId]}),M.dependsOn&&M.dependsOn.length>0&&Q(W,{dimColor:!0,children:[" (after: ",M.dependsOn.join(", "),")"]}),M.consumesFrom&&M.consumesFrom.length>0&&Q(W,{dimColor:!0,children:[" [consumes: ",M.consumesFrom.join(", "),"]"]}),M.consumesFromOptional&&M.consumesFromOptional.length>0&&Q(W,{dimColor:!0,children:[" [consumes?: ",M.consumesFromOptional.join(", "),"]"]}),M.persona&&Q(W,{dimColor:!0,children:[" [speak as: ",M.persona.speakAs,M.persona.voiceConstraints?` / ${M.persona.voiceConstraints}`:"","]"]}),M.outputContract&&Q(W,{dimColor:!0,children:[" [",(M.outputContract.contractRules??[]).map(wt=>wt.kind).join(" "),M.outputContract.mustReferenceArtifacts?" ref-artifacts":"","]"]}),M.config&&Q(W,{dimColor:!0,children:[" ","[",[M.config.timeout!==void 0?`timeout:${M.config.timeout}s`:"",M.config.maxTurns!==void 0?`turns:${M.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},M.id))}),$&&ne&&Q(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:[ge.length===0?Z(W,{dimColor:!0,children:" No recent executions"}):ge.map((M,Zt)=>{let wt=ie[M.id];return Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt===0?">":" "," "]}),Z(W,{color:M.status==="completed"?"green":M.status==="failed"?"red":"gray",children:M.status.padEnd(10)}),Z(W,{dimColor:!0,children:new Date(M.startedAt).toLocaleString().slice(0,16)}),Q(W,{dimColor:!0,children:[" ",M.id.slice(0,8)]}),wt&&Z(W,{color:wt==="good"?"green":"red",children:wt==="good"?" \u{1F44D}":" \u{1F44E}"})]},M.id)}),ge.length>0&&Z(W,{dimColor:!0,children:" g:good b:bad (rates most recent)"})]})]})]},S.id)})}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh x:executions"})})]})}function Er(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ot,Text as Ye,useInput as aa}from"ink";import la from"ink-text-input";import{useEffect as ca,useState as ar,useCallback as Hn}from"react";import{jsx as qe,jsxs as jt}from"react/jsx-runtime";function zn({onBack:e}){let[t,r]=ar([]),[a,o]=ar(""),[u,d]=ar(!0),[l,i]=ar(!1),[n,p]=ar(""),[g,b]=ar(null),y=Hn(()=>{d(!0),v("/webhooks").then(({webhooks:s,auth:c})=>{r(s),o(c),d(!1)}).catch(()=>d(!1))},[]);ca(()=>{y()},[y]);let w=Hn(async s=>{if(s.trim())try{let c=await v(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});b(`Triggered: ${c.executionId}`)}catch(c){b(`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){w(n),i(!1),p("");return}return}if(c.escape||s==="q"){e();return}if(s==="t"){i(!0),p(""),b(null);return}s==="r"&&(y(),b(null))}),u?qe(Ye,{dimColor:!0,children:"Loading webhooks..."}):jt(Ot,{flexDirection:"column",children:[jt(Ye,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),jt(Ye,{dimColor:!0,children:["Auth: ",a]}),g&&qe(Ot,{marginTop:1,children:qe(Ye,{color:"yellow",children:g})}),l&&jt(Ot,{marginTop:1,children:[qe(Ye,{bold:!0,color:"cyan",children:"Trigger webhook: "}),qe(la,{value:n,onChange:p,placeholder:"webhook name or ID"}),qe(Ye,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):jt(Ot,{marginTop:1,flexDirection:"column",children:[qe(Ot,{children:jt(Ye,{bold:!0,children:[lr("NAME",24),lr("DESCRIPTION",36),lr("TRIGGER",28),"TAGS"]})}),t.map(s=>jt(Ot,{children:[qe(Ye,{children:lr(s.displayName,24)}),qe(Ye,{dimColor:!0,children:lr(da(s.description??"",34),36)}),qe(Ye,{dimColor:!0,children:lr(s.trigger,28)}),qe(Ye,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function lr(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 bt,Text as Se,useInput as ua}from"ink";import ma from"ink-text-input";import{useEffect as Xn,useState as Rt,useCallback as Po}from"react";import{jsx as we,jsxs as ct}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 Qn({onBack:e}){let[t,r]=Rt([]),[a,o]=Rt(0),[u,d]=Rt([]),[l,i]=Rt(!0),[n,p]=Rt(!1),[g,b]=Rt(""),[y,w]=Rt("all"),[s,c]=Rt(null),[I,C]=Rt(!1),E=Po(()=>{v("/agents").then(({agents:B})=>{r(B),i(!1)}).catch(()=>i(!1))},[]);Xn(()=>{E()},[E]);let G=t[a],Y=Po(()=>{G&&(C(!1),v(`/memories/${G.id}`).then(({memories:B})=>{d(B),c(null)}).catch(B=>c(`Failed: ${B instanceof Error?B.message:String(B)}`)))},[G]);Xn(()=>{G&&Y()},[G,Y]);let N=Po(async B=>{if(!(!G||!B.trim()))try{let z=await v("/memories/query",{method:"POST",body:{agentId:G.id,prompt:B.trim()}});d(z.memories),C(!0),c(`Search: ${z.count} results`)}catch(z){c(`Search failed: ${z instanceof Error?z.message:String(z)}`)}},[G]),O=n,V=u.filter(B=>y==="all"?!0:y==="high"?B.importance>3:y==="medium"?B.importance===3:B.importance<3);return ua((B,z)=>{if(O){if(z.escape){p(!1),b("");return}if(z.return){N(g),p(!1),b("");return}return}if(z.escape||B==="q"){e();return}if(B==="a"){o(se=>(se+1)%Math.max(1,t.length));return}if(z.leftArrow){o(se=>(se-1+t.length)%Math.max(1,t.length));return}if(z.rightArrow){o(se=>(se+1)%Math.max(1,t.length));return}if(B==="s"){p(!0),b(""),c(null);return}if(B==="h"){w(se=>se==="high"?"all":"high");return}if(B==="m"){w(se=>se==="medium"?"all":"medium");return}if(B==="l"){w(se=>se==="low"?"all":"low");return}B==="r"&&Y()}),l?we(Se,{dimColor:!0,children:"Loading agents..."}):t.length===0?ct(bt,{flexDirection:"column",children:[we(Se,{dimColor:!0,children:"No agents found"}),we(Se,{dimColor:!0,children:"Press Esc to go back"})]}):ct(bt,{flexDirection:"column",children:[we(Se,{bold:!0,children:"Memories (Esc to go back)"}),ct(bt,{marginTop:1,children:[we(Se,{children:"Agent: "}),we(Se,{bold:!0,color:"cyan",children:G?.name??"?"}),ct(Se,{dimColor:!0,children:[" (",a+1,"/",t.length,") [a/arrows to switch]"]})]}),we(bt,{children:ct(Se,{dimColor:!0,children:["Filter: ",y==="all"?"all":y," | ",I?"search results":"all memories"," (",V.length,")"]})}),s&&we(bt,{children:we(Se,{color:"yellow",children:s})}),n&&ct(bt,{marginTop:1,children:[we(Se,{bold:!0,color:"cyan",children:"Search: "}),we(ma,{value:g,onChange:b,placeholder:"search query..."}),we(Se,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),V.length===0?we(bt,{marginTop:1,children:ct(Se,{dimColor:!0,children:["No memories",y!=="all"?` matching filter '${y}'`:""]})}):we(bt,{marginTop:1,flexDirection:"column",children:V.map(B=>ct(bt,{marginBottom:0,children:[ct(Se,{color:fa(B.importance),bold:!0,children:[ga(B.importance)," "]}),we(Se,{dimColor:!0,children:Yn(B.type??"?",12)}),we(Se,{dimColor:!0,children:Yn(`\xD7${B.retrievedCount??0}`,5)}),ct(Se,{children:[xa(B.content,55)," "]}),we(Se,{dimColor:!0,children:pa(B.createdAt)}),B.score!==void 0&&ct(Se,{dimColor:!0,children:[" (",B.score.toFixed(2),")"]})]},B.id))}),we(bt,{marginTop:1,children:we(Se,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Yn(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 dt,Text as be,useInput as Ta}from"ink";import io from"ink-text-input";import{useState as Ke,useEffect as Jn,useCallback as Ro}from"react";import{jsx as Re,jsxs as Ie}from"react/jsx-runtime";var Zn={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 es({onBack:e}){let{state:t}=tt(),[r,a]=Ke({}),[o,u]=Ke([]),[d,l]=Ke(null),[i,n]=Ke("view"),[p,g]=Ke(0),[b,y]=Ke(""),[w,s]=Ke(null),[c,I]=Ke(!1),[C,E]=Ke([]),[G,Y]=Ke({}),[N,O]=Ke(0),[V,B]=Ke(""),[z,se]=Ke(""),[ne,$e]=Ke(""),ge=Object.values(Zn).flat(),D=Ro(()=>{v("/config").then(_=>{a(_.config),u(_.mutable)}).catch(_=>l(_.message)),v("/config/env-diff").then(_=>{E(_.diffs)}).catch(()=>{}),v("/config/env").then(_=>Y(_.env??{})).catch(()=>{})},[]);Jn(()=>{D()},[D]),Jn(()=>{t.configVersion>0&&D()},[t.configVersion,D]);let ie=Ro(async()=>{let _=ge[p];if(_){I(!0),s(null);try{let K=b,ee=r[_];if(ee&&typeof ee.value=="number"&&(K=Number(b),isNaN(K))){s("Invalid number"),I(!1);return}let pe=await v("/config",{method:"PATCH",body:{[_]:K}});pe.updated.length>0&&(s(`Updated: ${_}`),D()),pe.errors.length>0&&s(pe.errors[0]),n("view")}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}finally{I(!1)}}},[ge,p,b,r,D]),L=Object.keys(G),ae=Ro(async _=>{try{await v("/config/env",{method:"PUT",body:_}),s("Env vars saved"),D()}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}},[D]);if(Ta((_,K)=>{if(i==="edit"){if(K.escape){n("view");return}return}if(i==="env-list"){if(K.escape){n("view");return}if(K.upArrow&&N>0&&O(ee=>ee-1),K.downArrow&&N<L.length-1&&O(ee=>ee+1),_==="a"){B(""),n("env-add-key");return}if(_==="d"&&L.length>0){let ee=L[N],pe={...G};delete pe[ee],ae(pe),N>=L.length-1&&N>0&&O(St=>St-1);return}if(K.return&&L.length>0){$e(G[L[N]]??""),n("env-edit-value");return}return}if(i==="env-add-key"){if(K.escape){n("env-list");return}return}if(i==="env-add-value"){if(K.escape){n("env-list");return}return}if(i==="env-edit-value"){if(K.escape){n("env-list");return}return}if(K.escape||_==="q"){e();return}if(K.upArrow&&p>0&&g(ee=>ee-1),K.downArrow&&p<ge.length-1&&g(ee=>ee+1),K.return||_==="e"){let ee=ge[p],pe=r[ee];pe&&pe.mutable?(y(String(pe.value??"")),n("edit"),s(null)):pe&&!pe.mutable&&s("This setting requires a restart to change")}_==="v"&&(O(0),n("env-list"),s(null)),_==="r"&&(D(),s("Refreshed")),_==="s"&&C.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),E([]),D()}),_==="l"&&C.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),D()})}),d)return Ie(dt,{flexDirection:"column",children:[Ie(be,{color:"red",children:["Failed to load config: ",d]}),Re(be,{dimColor:!0,children:"Press Esc or q to return"})]});let Ce=0;return Ie(dt,{flexDirection:"column",children:[Re(be,{bold:!0,children:"Settings"}),w&&Re(be,{color:w.startsWith("Failed")||w.startsWith("This setting")?"yellow":"green",children:w}),C&&C.length>0&&Ie(dt,{flexDirection:"column",marginBottom:1,children:[Ie(be,{color:"yellow",children:[".env differs from DB (",C.length," key(s)): ",C.map(_=>_.envKey).join(", ")]}),Re(be,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Re(dt,{marginTop:1,flexDirection:"column",children:Object.entries(Zn).map(([_,K])=>Ie(dt,{marginBottom:1,flexDirection:"column",children:[Re(be,{bold:!0,color:"cyan",children:_}),K.map(ee=>{let pe=r[ee],gt=Ce++===p,et=o.includes(ee),Ut=ha[ee]??ee,Jt=pe?String(pe.value??""):"...";return i==="edit"&&gt?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",Ut,": "]}),Re(io,{value:b,onChange:y,onSubmit:()=>{ie()}}),c&&Re(be,{color:"yellow",children:" saving..."})]},ee):Ie(dt,{children:[Ie(be,{color:gt?"cyan":"white",children:[gt?"> ":" ",et?" ":"\u{1F512} ",Ut,": "," "]}),Re(be,{color:et?"white":"gray",children:Jt}),!et&&Re(be,{dimColor:!0,children:" (restart required)"})]},ee)})]},_))}),Re(be,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),i.startsWith("env")&&Ie(dt,{flexDirection:"column",marginTop:1,children:[Ie(be,{bold:!0,color:"cyan",children:["Environment Variables (",L.length,")"]}),L.length===0&&i==="env-list"&&Re(be,{dimColor:!0,children:" No env vars. Press a to add."}),L.map((_,K)=>{let ee=K===N;return i==="env-edit-value"&&ee?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",_," = "]}),Re(io,{value:ne,onChange:$e,onSubmit:()=>{ae({...G,[_]:ne}),n("env-list")}})]},_):Ie(be,{color:ee&&i==="env-list"?"cyan":"white",children:[ee&&i==="env-list"?"> ":" ",_," = ",G[_]]},_)}),i==="env-add-key"&&Ie(dt,{children:[Re(be,{color:"green",children:" New key: "}),Re(io,{value:V,onChange:B,onSubmit:()=>{V.trim()&&(se(""),n("env-add-value"))}})]}),i==="env-add-value"&&Ie(dt,{children:[Ie(be,{color:"green",children:[" ",V," = "]}),Re(io,{value:z,onChange:se,onSubmit:()=>{ae({...G,[V.trim()]:z}),n("env-list")}})]}),Re(be,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as Kt,Text as Ve,useInput as ya}from"ink";import{useEffect as ba,useState as Do,useCallback as va}from"react";import{jsx as Me,jsxs as dr}from"react/jsx-runtime";function ts({onBack:e}){let[t,r]=Do([]),[a,o]=Do(!0),[u,d]=Do(0),{message:l,setMessage:i,clearMessage:n}=ot(),p=va(()=>{o(!0),v("/plugins").then(({plugins:g})=>{r(g),o(!1)}).catch(()=>o(!1))},[]);return ba(()=>{p()},[p]),ya((g,b)=>{if(b.escape||g==="q"){e();return}if(b.upArrow){d(y=>Math.max(0,y-1));return}if(b.downArrow){d(y=>Math.min(t.length-1,y+1));return}g==="r"&&(p(),n())}),a?Me(Ve,{dimColor:!0,children:"Loading plugins..."}):dr(Kt,{flexDirection:"column",children:[dr(Ve,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),l&&Me(Kt,{marginTop:1,children:dr(Ve,{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?Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"No plugins installed."})}):dr(Kt,{marginTop:1,flexDirection:"column",children:[dr(Kt,{children:[Me(Ve,{dimColor:!0,children:" "}),Me(Ve,{dimColor:!0,children:cr("Name",24)}),Me(Ve,{dimColor:!0,children:cr("Scope",8)}),Me(Ve,{dimColor:!0,children:cr("User",6)}),Me(Ve,{dimColor:!0,children:"Path"})]}),t.map((g,b)=>{let y=b===u,w=g.id.split("@")[0];return dr(Kt,{children:[Me(Ve,{color:y?"cyan":void 0,bold:y,children:y?"> ":" "}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(w,24)}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(g.scope,8)}),Me(Ve,{color:g.globalEnabled?"green":"gray",children:cr(g.globalEnabled?"on":"off",6)}),Me(Ve,{dimColor:!0,children:g.installPath})]},g.id)})]}),Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"r:refresh"})})]})}function cr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Mo,Text as $o,useInput as Ca}from"ink";import{useState as Sa}from"react";import{jsx as Ht,jsxs as rs}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 os({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}}),rs(Mo,{flexDirection:"column",children:[Ht($o,{bold:!0,children:"Work Surface"}),Ht($o,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Ht(Mo,{gap:3,marginBottom:1,marginTop:1,children:wa.map(a=>{let o=t===a.id;return Ht(Mo,{children:rs($o,{color:o?"cyan":"gray",bold:o,children:[o?"\u25CF":"\u25CB"," ",a.key,". ",a.label]})},a.id)})}),t==="tasks"&&Ht(to,{onBack:e}),t==="automations"&&Ht(so,{onBack:e}),t==="goals"&&Ht(oo,{onBack:e})]})}import{Box as me,Text as oe,useInput as ka}from"ink";import{useEffect as Ba,useState as Ar}from"react";import{jsx as j,jsxs as De}from"react/jsx-runtime";var ns={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function ss({onBack:e}){let[t,r]=Ar([]),[a,o]=Ar(!0),[u,d]=Ar(0),[l,i]=Ar(null),[n,p]=Ar("");Ba(()=>{g()},[]);async function g(){try{let w=await v("/channels");r(w.channels)}catch{}o(!1)}async function b(w){if(t.find(c=>c.id===w)?.platform==="wechat")try{p("Starting WeChat QR login...");let c=await v(`/channels/${w}/wechat/qr-start`,{method:"POST"});if(c.qrcodeUrl){p(`Scan QR: ${c.qrcodeUrl}
10
- Waiting for scan...`);let I=await v(`/channels/${w}/wechat/qr-wait`,{method:"POST",body:{sessionKey:c.sessionKey,timeoutMs:12e4}});p(I.message)}else p(c.message);g()}catch{p("WeChat connect failed")}else try{await v(`/channels/${w}/connect`,{method:"POST"}),p("Connecting..."),g()}catch{p("Connect failed")}}async function y(w){try{await v(`/channels/${w}/disconnect`,{method:"POST"}),p("Disconnected"),g()}catch{p("Disconnect failed")}}return ka((w,s)=>{if(l){if(s.escape||w==="q"){i(null);return}if(w==="c"){b(l.id);return}if(w==="d"){y(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?j(me,{flexDirection:"column",children:j(oe,{dimColor:!0,children:"Loading channels..."})}):l?De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[De(oe,{bold:!0,children:["Channel: ",l.name]}),j(oe,{dimColor:!0,children:" (Esc to go back)"})]}),De(me,{flexDirection:"column",gap:0,children:[De(oe,{children:["ID: ",l.id]}),De(oe,{children:["Platform: ",l.platform]}),De(oe,{children:["Status: ",j(oe,{color:ns[l.status]??"white",children:l.status})]}),De(oe,{children:["Enabled: ",l.enabled?"yes":"no"]}),De(oe,{children:["Messages: ",l.messageCount]}),De(oe,{children:["Config: ",JSON.stringify(l.config)]})]}),j(me,{marginTop:1,children:j(oe,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),n&&j(oe,{color:"yellow",children:n})]}):De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[j(oe,{bold:!0,children:"Channels"}),De(oe,{dimColor:!0,children:[" (",t.length," total) "]}),j(oe,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?j(oe,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):De(me,{flexDirection:"column",children:[De(me,{children:[j(me,{width:3,children:j(oe,{dimColor:!0,children:" "})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"ID"})}),j(me,{width:16,children:j(oe,{bold:!0,dimColor:!0,children:"Name"})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"Platform"})}),j(me,{width:14,children:j(oe,{bold:!0,dimColor:!0,children:"Status"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Enabled"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((w,s)=>De(me,{children:[j(me,{width:3,children:j(oe,{children:s===u?">":" "})}),j(me,{width:12,children:j(oe,{inverse:s===u,children:w.id.slice(0,8)})}),j(me,{width:16,children:j(oe,{children:w.name})}),j(me,{width:12,children:j(oe,{children:w.platform})}),j(me,{width:14,children:De(oe,{color:ns[w.status]??"white",children:[w.status==="connected"?"\u25CF":w.status==="error"?"\u2717":"\u25CB"," ",w.status]})}),j(me,{width:10,children:j(oe,{color:w.enabled?"green":"gray",children:w.enabled?"yes":"no"})}),j(me,{width:10,children:j(oe,{children:w.messageCount})})]},w.id))]})]})}import{Box as ur,Text as mt,useInput as Aa}from"ink";import{useEffect as Pa,useState as Pr,useCallback as Ra}from"react";import{Box as R,Text as x,useInput as Ia}from"ink";import ut from"ink-text-input";import{useEffect as is,useState as X,useCallback as vt}from"react";Ho();import{Fragment as ao,jsx as h,jsxs as k}from"react/jsx-runtime";var Ea=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function as({roleId:e,onBack:t}){let[r,a]=X(null),[o,u]=X([]),[d,l]=X(!0),[i,n]=X("view"),[p,g]=X(""),[b,y]=X(0),[w,s]=X(""),[c,I]=X([]),[C,E]=X(0),[G,Y]=X(new Set),[N,O]=X("inline"),[V,B]=X(""),[z,se]=X(""),[ne,$e]=X(""),[ge,D]=X([]),[ie,L]=X(new Set),[ae,Ce]=X(0),[_,K]=X("default"),[ee,pe]=X(""),[St,gt]=X(""),[et,Ut]=X("mode"),[Jt,S]=X([]),[A,$]=X(null),[le,Ue]=X([]),[Ne,M]=X([]),[Zt,wt]=X(""),[_t,$r]=X(0),[Nr,Oo]=X(""),[qo,Vo]=X(""),[Uo,Wo]=X(""),[_r,po]=X(0),[Tr,Go]=X([]),[Lr,xo]=X(0),[Fr,Or]=X(!1),[er,Cs]=X(""),{message:F,setMessage:q}=ot(),ce=vt(()=>{l(!0),v(`/roles/${e}`).then(({role:m,projectPlugins:T,workspacePath:f})=>{a(m),u(T??[]),Cs(f??""),g(m.cagPrompt??""),Y(new Set(m.allowedTools??[])),O(m.executionMode??"inline"),B(m.model??""),se(m.effortTier??""),$e(m.maxBudgetUsd!=null?String(m.maxBudgetUsd):""),l(!1)}).catch(()=>l(!1))},[e]);is(()=>{ce(),v("/config").then(m=>{let T=m.config["defaults.deniedReadPaths"]?.value;Array.isArray(T)&&S(T),$(m.sandbox),Ue(m.osCapabilities?.registry??[])}).catch(()=>{})},[ce]),is(()=>{O(r?.executionMode??"inline"),B(r?.model??""),se(r?.effortTier??""),$e(r?.maxBudgetUsd!=null?String(r?.maxBudgetUsd):""),K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),M(r?.osCapabilities??[]);let m=r?.osCapabilities?.find(T=>T.id==="automation")?.targets??[];wt(m.join(", "))},[r?.id,r?.executionMode,r?.model,r?.effortTier,r?.maxBudgetUsd,r?.permissionMode,r?.allowedBashPatterns,r?.deniedBashPatterns,r?.osCapabilities]);let Ss=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{cagPrompt:p}}),q("CAG prompt saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,p,ce,q]),ws=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{additionalDirectories:it}}),q("Directories saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,ce,q]),ks=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{allowedTools:Array.from(G)}}),q("Tool permissions saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,G,ce,q]),Bs=vt(async()=>{if(!r)return;let m={executionMode:N};V!==void 0&&(m.model=V),m.effortTier=z===""?null:z;let T=parseFloat(ne);isNaN(T)||(m.maxBudgetUsd=T);try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Execution config saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,N,V,z,ne,ce,q]),Is=vt(async()=>{if(!r)return;let m={permissionMode:_},T=ee.split(",").map(P=>P.trim()).filter(Boolean),f=St.split(",").map(P=>P.trim()).filter(Boolean);m.allowedBashPatterns=T.length>0?T:[],m.deniedBashPatterns=f.length>0?f:[];try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Permission config saved","success"),n("view"),ce()}catch(P){q(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[r,_,ee,St,ce,q]),jo=vt(m=>{let T=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)))),T.set(f.id,P)}return Array.from(T.values()).sort((f,P)=>f.id.localeCompare(P.id))},[]),Es=vt(async()=>{if(!r)return;let m=jo(Ne),T=m.find(f=>f.id==="automation")?.targets??[];if(m.some(f=>f.id==="automation")&&(T.length===0||T.some(f=>!Ea.test(f)))){q("Automation requires valid bundle id targets","error");return}try{await v(`/roles/${r.id}`,{method:"PATCH",body:{osCapabilities:m}}),q("OS capabilities saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,Ne,jo,ce,q]),As=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/install/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Bound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Bind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),Ps=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/uninstall/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Unbound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Unbind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),it=r?.additionalDirectories??[];if(Ia((m,T)=>{if(T.escape){n("view");return}if(m==="r"){ce();return}switch(i){case"view":{if(m==="c"){n("edit-cag");return}if(m==="d"){n("edit-dirs"),y(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"){v("/channels?enabled=true").then(({channels:f})=>{D(f.map(P=>({name:P.name,id:P.id}))),L(new Set(r?.allowedChannels??[])),Ce(0),n("edit-channels")}).catch(()=>q("Failed to load channels","error"));return}if(m==="p"){K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),Ut("mode"),n("edit-permissions");return}if(m==="v"){$r(0),n("edit-env");return}if(m==="b"){po(0),n("edit-plugins");return}if(m==="i"){if(!r)return;let f=!r.inheritUserSettings;v(`/roles/${r.id}`,{method:"PATCH",body:{inheritUserSettings:f}}).then(()=>{q(`Inherit user settings: ${f?"ON":"OFF"}`,"success"),ce()}).catch(()=>q("Failed to toggle","error"));return}if(m==="R"&&r?.presetId){v(`/presets/role/${r.presetId}/restore`,{method:"POST"}).then(()=>{q("Preset restored","success"),ce()}).catch(f=>q(`Restore failed: ${f instanceof Error?f.message:String(f)}`,"error"));return}break}case"edit-cag":{if(T.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"&&it.length>0){let f=it[b];if(f){a(U=>U&&{...U,additionalDirectories:U.additionalDirectories?.map((he,kt)=>kt===b?{...typeof he=="string"?{path:he}:he,mode:he.mode==="ro"?"rw":"ro"}:he)});let P=f.mode==="ro"?"rw":"ro";q(`Mode set to ${P.toUpperCase()}`,"success")}return}if(m==="x"&&it.length>0){a(f=>f&&{...f,additionalDirectories:it.filter((P,U)=>U!==b)}),y(f=>Math.max(0,Math.min(f,it.length-2)));return}if(T.upArrow){y(f=>Math.max(0,f-1));return}if(T.downArrow){y(f=>Math.min(it.length-1,f+1));return}break}case"edit-dirs-add":{if(T.escape){n("edit-dirs"),s(""),I([]);return}if(T.return&&c.length>0){let f=c[C];f&&(s(f.endsWith("/")?f:f+"/"),I([]));return}if(T.return){let f=w.trim();f&&f.startsWith("/")?(a(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:f,mode:"rw"}]}),s(""),I([]),n("edit-dirs")):q("Path must be absolute (must start with /)","error");return}if(T.tab){let f=w.trim();if(!f||!f.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(f)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),I([])):P.length>1&&(I(P),E(0))}).catch(()=>{I([])});return}if(T.upArrow&&c.length>0){E(f=>Math.max(0,f-1));return}if(T.downArrow&&c.length>0){E(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<qr.length){let P=qr[f];Y(U=>{let he=new Set(U);return he.has(P)?he.delete(P):he.add(P),he});return}break}case"edit-oscaps":{if(m==="s"){Es();return}if(m==="a"&&Ne.some(U=>U.id==="automation")){let U=Ne.find(he=>he.id==="automation")?.targets??[];wt(U.join(", ")),n("edit-oscaps-targets");return}let f=le.filter(U=>U.editable),P=parseInt(m,10)-1;if(!isNaN(P)&&P>=0&&P<f.length){let U=f[P];M(he=>he.some(hr=>hr.id===U.id)?he.filter(hr=>hr.id!==U.id):[...he,{id:U.id,targets:U.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(T.return){let f=Zt.split(",").map(P=>P.trim()).filter(Boolean);M(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(T.tab){O(f=>f==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(m==="s"){Is();return}if(T.tab){Ut(f=>f==="mode"?"allowed":f==="allowed"?"denied":"mode");return}if(et==="mode"&&(T.upArrow||T.downArrow)){let f=["default","acceptEdits","dontAsk","bypassPermissions"],P=f.indexOf(_);T.upArrow&&K(f[Math.max(0,P-1)]),T.downArrow&&K(f[Math.min(f.length-1,P+1)]);return}break}case"edit-channels":{if(m==="s"){if(!r)return;let f=ie.size>0?Array.from(ie):[];v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:f}}).then(()=>{q("Channels saved","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m==="u"){if(!r)return;v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{q("Channels: unrestricted","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m===" "){let f=ge[ae];f&&L(P=>{let U=new Set(P);return U.has(f.name)?U.delete(f.name):U.add(f.name),U});return}if(T.upArrow){Ce(f=>Math.max(0,f-1));return}if(T.downArrow){Ce(f=>Math.min(ge.length-1,f+1));return}break}case"edit-env":{let f=Object.keys(r?.envVars??{});if(m==="a"){Oo(""),n("edit-env-add-key");return}if(m==="d"&&f.length>0){let P=f[_t],U={...r?.envVars??{}};delete U[P],v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Deleted","success"),ce()}).catch(()=>q("Delete failed","error")),_t>=f.length-1&&_t>0&&$r(he=>he-1);return}if(T.return&&f.length>0){Wo((r?.envVars??{})[f[_t]]??""),n("edit-env-edit-value");return}T.upArrow&&_t>0&&$r(P=>P-1),T.downArrow&&_t<f.length-1&&$r(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break;case"edit-plugins":{if(Fr)return;if(m==="a"){v("/plugins").then(({plugins:f})=>{let P=new Set(o.map(U=>U.id));Go(f.filter(U=>!P.has(U.id))),xo(0),n("edit-plugins-add")}).catch(()=>q("Failed to load plugins","error"));return}if(m==="x"&&o.length>0){let f=o[_r];f&&Ps(f.id);return}if(T.upArrow){po(f=>Math.max(0,f-1));return}if(T.downArrow){po(f=>Math.min(o.length-1,f+1));return}break}case"edit-plugins-add":{if(Fr)return;if(T.escape){n("edit-plugins"),Go([]);return}if(T.return&&Tr.length>0){let f=Tr[Lr];f&&As(f.id);return}if(T.upArrow){xo(f=>Math.max(0,f-1));return}if(T.downArrow){xo(f=>Math.min(Tr.length-1,f+1));return}break}}}),d)return h(x,{dimColor:!0,children:"Loading role..."});if(!r)return h(x,{dimColor:!0,children:"Role not found."});if(i==="edit-plugins")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Plugins (\u2191\u2193 navigate, x:unbind a:add Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),o.length===0?h(x,{dimColor:!0,children:"No plugins bound. Press a to add."}):o.map((m,T)=>k(R,{children:[k(x,{color:T===_r?"cyan":void 0,bold:T===_r,children:[T===_r?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-plugins-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Plugin (\u2191\u2193 navigate, Enter:bind Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),Tr.length===0?h(x,{dimColor:!0,children:"No available plugins."}):Tr.map((m,T)=>k(R,{children:[k(x,{color:T===Lr?"cyan":void 0,bold:T===Lr,children:[T===Lr?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-cag")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(ut,{value:p,onChange:g,placeholder:"Character And Guidance prompt..."}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(ut,{value:w,onChange:m=>{s(m),I([])},placeholder:"/absolute/path/to/directory"}),c.length>0&&k(R,{flexDirection:"column",marginTop:1,children:[c.map((m,T)=>k(x,{color:T===C?"cyan":void 0,dimColor:T!==C,children:[T===C?"> ":" ",m,"/"]},m)),h(x,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),it.length===0?h(x,{dimColor:!0,children:"No directories. Press a to add one."}):it.map((m,T)=>{let f=typeof m=="string"?{path:m,mode:"rw"}:m,P=f.mode!=="ro";return k(R,{children:[h(x,{color:T===b?"cyan":void 0,bold:T===b,children:T===b?"> ":" "}),k(x,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),h(x,{color:T===b?"cyan":void 0,children:f.path})]},f.path)})]});if(i==="edit-tools")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),qr.map((m,T)=>{let f=G.has(m);return k(R,{children:[k(x,{dimColor:!0,children:[T+1,". "]}),h(x,{color:f?"green":"red",children:f?"[ON] ":"[OFF] "}),h(x,{children:m})]},m)})]});if(i==="edit-oscaps"){let m=le.filter(T=>T.editable);return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),A&&k(x,{dimColor:!0,children:["Platform: ",A.platform," ",A.available?"(sandbox active)":"(sandbox unavailable)"]}),le.map(T=>{let f=m.findIndex(kt=>kt.id===T.id),P=Ne.some(kt=>kt.id===T.id),U=f>=0?`${f+1}.`:" -",he=T.id==="automation"?(()=>{let kt=Ne.find(hr=>hr.id===T.id)?.targets??[];return kt.length>0?` targets: ${kt.join(", ")}`:" targets: (none)"})():"";return k(R,{flexDirection:"column",marginBottom:1,children:[k(x,{color:P?"green":T.editable?"red":"gray",children:[U," ",P?"[ON]":"[OFF]"," ",T.label," [",T.availability,"]"]}),k(x,{dimColor:!0,children:[" ",T.description,he]}),T.effectiveDisabledReason&&!T.editable&&k(x,{dimColor:!0,children:[" ",T.effectiveDisabledReason]})]},T.id)}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]})}if(i==="edit-oscaps-targets")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),h(ut,{value:Zt,onChange:wt,placeholder:"com.apple.mail, com.apple.systemevents"}),h(x,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-exec")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,children:" Mode: "}),h(x,{color:"cyan",children:N}),h(x,{dimColor:!0,children:" (Tab to toggle)"})]}),k(R,{children:[h(x,{bold:!0,children:" Model: "}),h(ut,{value:V,onChange:B,placeholder:"sonnet, opus, haiku, or blank"})]}),k(R,{children:[h(x,{bold:!0,children:" Effort Tier: "}),h(ut,{value:z,onChange:se,placeholder:"low, medium, high, or blank to inherit"})]}),k(R,{children:[h(x,{bold:!0,children:" Max Budget (USD): "}),h(ut,{value:ne,onChange:$e,placeholder:"0 = unlimited"})]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-permissions")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,color:et==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(T=>k(x,{color:T===_?"green":"gray",children:[T===_?`[${T}]`:` ${T} `," "]},T))]}),k(R,{children:[h(x,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?h(ut,{value:ee,onChange:pe,placeholder:"git add *, pnpm test*"}):h(x,{children:ee||"(none)"})]}),k(R,{children:[h(x,{bold:!0,color:et==="denied"?"cyan":void 0,children:" Denied Bash: "}),et==="denied"?h(ut,{value:St,onChange:gt,placeholder:"rm -rf *, ssh *"}):h(x,{children:St||"(none)"})]}),h(x,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-channels")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),ge.length===0?h(x,{dimColor:!0,children:"No channels available"}):ge.map((m,T)=>k(R,{children:[k(x,{children:[T===ae?">":" "," "]}),k(x,{color:ie.has(m.name)?"green":"gray",children:["[",ie.has(m.name)?"x":" ","] ",m.name]})]},m.id)),k(x,{dimColor:!0,children:["Selected: ",ie.size>0?Array.from(ie).join(", "):"none (= block all)"]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i.startsWith("edit-env")){let m=Object.keys(r.envVars??{});return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Environment Variables (",m.length,")"]}),m.length===0&&i==="edit-env"&&h(x,{dimColor:!0,children:" No env vars. Press a to add."}),m.map((T,f)=>{let P=f===_t;return i==="edit-env-edit-value"&&P?k(R,{children:[k(x,{color:"cyan",children:["> ",T," = "]}),h(ut,{value:Uo,onChange:Wo,onSubmit:()=>{let U={...r.envVars??{},[T]:Uo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Saved","success"),ce(),n("edit-env")}).catch(()=>q("Save failed","error"))}})]},T):k(x,{color:P&&i==="edit-env"?"cyan":"white",children:[P&&i==="edit-env"?"> ":" ",T," = ",(r.envVars??{})[T]]},T)}),i==="edit-env-add-key"&&k(R,{children:[h(x,{color:"green",children:" New key: "}),h(ut,{value:Nr,onChange:Oo,onSubmit:()=>{Nr.trim()&&(Vo(""),n("edit-env-add-value"))}})]}),i==="edit-env-add-value"&&k(R,{children:[k(x,{color:"green",children:[" ",Nr," = "]}),h(ut,{value:qo,onChange:Vo,onSubmit:()=>{let T={...r.envVars??{},[Nr.trim()]:qo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:T}}).then(()=>{q("Added","success"),ce(),n("edit-env")}).catch(()=>q("Add failed","error"))}})]}),h(x,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),F&&h(x,{color:F.type==="error"?"red":"green",children:F.text})]})}return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Role: ",r.name]}),k(R,{children:[h(x,{dimColor:!0,children:"ID: "}),h(x,{children:r.id})]}),k(R,{children:[h(x,{dimColor:!0,children:"Status: "}),h(x,{color:r.status==="active"?"green":r.status==="probation"?"yellow":"red",children:r.status})]}),r.performanceScore!=null&&k(R,{children:[h(x,{dimColor:!0,children:"Score: "}),k(x,{children:[(r.performanceScore*100).toFixed(0),"%"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Created: "}),h(x,{children:new Date(r.createdAt).toLocaleString()})]}),k(R,{children:[h(x,{dimColor:!0,children:"Execution: "}),k(x,{children:[r.executionMode??"inline"," / tier:",r.effortTier??"\u2014"," / model:",r.model??"inherit"," / ",r.maxBudgetUsd!=null?`$${r.maxBudgetUsd}`:"no limit"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"OS Capabilities: "}),h(x,{children:(r.osCapabilities?.length??0)>0?r.osCapabilities.map(m=>m.id==="automation"&&m.targets?.length?`automation(${m.targets.join(",")})`:m.id).join(", "):"None"})]}),A&&k(R,{children:[h(x,{dimColor:!0,children:"Sandbox Platform: "}),k(x,{children:[A.platform," ",A.available?"(active)":"(unavailable)"]})]}),it.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Additional Directories:"}),it.map(m=>k(x,{dimColor:!0,children:[" ",m.path]},m.path))]}),k(R,{children:[h(x,{dimColor:!0,children:"Permission: "}),h(x,{children:r.permissionMode??"default"})]}),(r.allowedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Allow: "}),h(x,{children:r.allowedBashPatterns.join(", ")})]}),(r.deniedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Deny: "}),h(x,{children:r.deniedBashPatterns.join(", ")})]}),Jt.length>0&&k(R,{flexDirection:"column",children:[h(x,{dimColor:!0,children:"Denied Read Paths (global):"}),Jt.map(m=>k(x,{dimColor:!0,children:[" ",m]},m)),k(x,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Channels: "}),h(x,{children:r.allowedChannels===void 0?"Unrestricted":r.allowedChannels.length===0?"Blocked":r.allowedChannels.join(", ")})]}),k(R,{children:[h(x,{dimColor:!0,children:"Inherit User Settings: "}),h(x,{color:r.inheritUserSettings?"green":"gray",children:r.inheritUserSettings?"Yes":"No"})]}),r.learnedRules.stylePreferences.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Style Preferences:"}),r.learnedRules.stylePreferences.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.avoidedActions.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Avoided Actions:"}),r.learnedRules.avoidedActions.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.pinnedParameters.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Pinned Parameters:"}),r.learnedRules.pinnedParameters.map(m=>{let T=Object.entries(m.params).map(([P,U])=>`${P}=${JSON.stringify(U)}`).join(", "),f=m.condition?` [when: ${m.condition}]`:"";return k(x,{dimColor:!0,children:[" - ",m.tool," \u2192 ",T,f]},`${m.tool}-${m.pinnedAt}`)})]}),k(R,{children:[h(x,{dimColor:!0,children:"Plugins: "}),o.length===0?h(x,{dimColor:!0,children:"None"}):o.map(m=>k(x,{children:[m.name," "]},m.id))]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),h(R,{marginTop:1,children:k(x,{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 Qe,jsxs as Rr}from"react/jsx-runtime";function ls({onBack:e}){let[t,r]=Pr([]),[a,o]=Pr(!0),[u,d]=Pr(0),[l,i]=Pr("list"),[n,p]=Pr(null),{message:g,setMessage:b,clearMessage:y}=ot(),w=Ra(()=>{o(!0),v("/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(()=>{w()},[w]),Aa((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(I=>Math.max(0,I-1));return}if(c.downArrow){d(I=>Math.min(t.length-1,I+1));return}if(s==="r"&&(w(),y()),s===`
11
- `||s==="o"||s==="e"){t.length>0&&(p(t[u].id),i("detail"));return}}),a?Qe(mt,{dimColor:!0,children:"Loading roles..."}):l==="detail"&&n?Qe(as,{roleId:n,onBack:()=>i("list")}):Rr(ur,{flexDirection:"column",children:[Rr(mt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),g&&Qe(ur,{marginTop:1,children:Rr(mt,{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?Qe(ur,{marginTop:1,children:Qe(mt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Qe(ur,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014",E=s.contractComplianceEma!=null?`[\u5951\u7EA6 ${s.contractComplianceEma.toFixed(2)}]`:"[\u5951\u7EA6 \u2014]";return Rr(ur,{children:[Qe(mt,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Qe(mt,{color:I?"cyan":void 0,bold:I,children:No(s.name,24)}),s.presetId&&Rr(mt,{dimColor:!0,children:["[",s.presetId,"]"]}),Qe(mt,{color:Da(s.status),children:No(s.status,12)}),Qe(mt,{dimColor:!0,children:No(C,8)}),Qe(mt,{dimColor:!0,children:E})]},s.id)})}),Qe(ur,{marginTop:1,children:Qe(mt,{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 No(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ma,Text as _o}from"ink";import $a from"react";import{jsx as lo,jsxs as _a}from"react/jsx-runtime";var He={key:"Esc",label:"back"},Na={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},He],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},He],config:[He],evolution:[He],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},He],strategies:[He],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"},He],webhooks:[He],memories:[He],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},He],roles:[He],settings:[He],channels:[He]};function cs(){let{state:e}=tt(),t=Na[e.view]??[He];return lo(Ma,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((r,a)=>_a($a.Fragment,{children:[a>0&&lo(_o,{dimColor:!0,children:" "}),lo(_o,{color:"cyan",children:r.key}),lo(_o,{dimColor:!0,children:` ${r.label}`})]},`${r.key}-${r.label}`))})}import{Box as mr,Text as nt,useInput as La}from"ink";import{useEffect as Fa,useState as co,useCallback as Oa}from"react";import{jsx as Mt,jsxs as Dt}from"react/jsx-runtime";function ds({onBack:e}){let[t,r]=co([]),[a,o]=co(!0),[u,d]=co(0),[l,i]=co("all"),{message:n,setMessage:p}=ot(),g=Oa(()=>{o(!0);let c=l!=="all"?`?status=${l}`:"";v(`/feature-requests${c}`).then(({featureRequests:I})=>{r(I),d(0),o(!1)}).catch(()=>o(!1))},[l]);Fa(()=>{g()},[g]);let b=async(c,I)=>{try{await v(`/feature-requests/${c}/status`,{method:"PATCH",body:{status:I}}),p(`Marked as ${I}`,"success"),await g()}catch(C){p(`Failed: ${C instanceof Error?C.message:String(C)}`,"error")}},y=t;La((c,I)=>{if(I.escape||c==="q"){e();return}if(I.upArrow){d(E=>Math.max(0,E-1));return}if(I.downArrow){d(E=>Math.min(y.length-1,E+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"&&y.length>0){let E=y[u];if(E&&E.status==="new"){b(E.id,"reviewed");return}}if(c==="d"&&y.length>0){let E=y[u];if(E){b(E.id,"dismissed");return}}if(c==="c"&&y.length>0){let E=y[u];if(E){b(E.id,"converted");return}}});let w=c=>c==="new"?"cyan":c==="reviewed"?"green":c==="dismissed"?"gray":c==="converted"?"yellow":"white",s=c=>{let I=Date.now()-c;if(Math.floor(I/6e4)<1)return"now";let E=Math.floor(I/36e5);return E<24?`${E}h ago`:`${Math.floor(E/24)}d ago`};return Dt(mr,{flexDirection:"column",children:[Dt(nt,{bold:!0,children:["Feature Requests (",y.length,") (Esc:back q:quit r:refresh)"]}),n&&Mt(mr,{marginTop:1,children:Dt(nt,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),Mt(nt,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),Mt(nt,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),a?Mt(nt,{dimColor:!0,children:"Loading..."}):y.length===0?Mt(nt,{dimColor:!0,children:"No feature requests found."}):Mt(mr,{marginTop:1,flexDirection:"column",children:y.map((c,I)=>{let C=I===u,E=c.content.length>80?c.content.slice(0,80)+"...":c.content;return Dt(mr,{flexDirection:"column",children:[Dt(mr,{children:[Mt(nt,{color:C?"cyan":void 0,bold:C,children:C?"> ":" "}),Dt(nt,{color:w(c.status),children:["[",c.status,"]"]}),Dt(nt,{dimColor:!0,children:[" ",s(c.extractedAt)]}),c.tags&&c.tags.length>0&&Dt(nt,{dimColor:!0,children:[" ",c.tags.slice(0,3).join(", ")]})]}),Dt(mr,{paddingLeft:4,flexDirection:"column",children:[c.summary&&Mt(nt,{color:C?"cyan":"white",children:c.summary}),Mt(nt,{dimColor:!0,children:E})]})]},c.id)})})]})}import{Box as fr,Text as Je,useInput as qa}from"ink";import{useEffect as Va,useState as uo,useCallback as Ua}from"react";import{jsx as $t,jsxs as Ct}from"react/jsx-runtime";function us({onBack:e}){let[t,r]=uo([]),[a,o]=uo(!0),[u,d]=uo(0),[l,i]=uo("all"),{message:n,setMessage:p}=ot(),g=Ua(()=>{o(!0);let s=l!=="all"?`?status=${l}`:"";v(`/mistake-patterns${s}`).then(({mistakePatterns:c})=>{r(c),d(0),o(!1)}).catch(()=>o(!1))},[l]);Va(()=>{g()},[g]);let b=async(s,c)=>{try{await v(`/mistake-patterns/${s}`,{method:"PATCH",body:{status:c}}),p(`Marked as ${c}`,"success"),await g()}catch(I){p(`Failed: ${I instanceof Error?I.message:String(I)}`,"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 I={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(I[s]){i(I[s]);return}if(s==="a"&&t.length>0){let C=t[u];if(C&&C.status!=="acknowledged"){b(C.id,"acknowledged");return}}if(s==="d"&&t.length>0){let C=t[u];if(C&&C.status!=="dismissed"){b(C.id,"dismissed");return}}if(s==="n"&&t.length>0){let C=t[u];if(C&&C.status!=="new"){b(C.id,"new");return}}});let y=s=>s==="new"?"cyan":s==="acknowledged"?"green":s==="dismissed"?"gray":"white",w=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 Ct(fr,{flexDirection:"column",children:[Ct(Je,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),n&&$t(fr,{marginTop:1,children:Ct(Je,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),$t(Je,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),$t(Je,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),a?$t(Je,{dimColor:!0,children:"Loading..."}):t.length===0?$t(Je,{dimColor:!0,children:"No mistake patterns found."}):$t(fr,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.dimensionValue.length>80?s.dimensionValue.slice(0,80)+"...":s.dimensionValue;return Ct(fr,{flexDirection:"column",children:[Ct(fr,{children:[$t(Je,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Ct(Je,{color:y(s.status),children:["[",s.status,"]"]}),Ct(Je,{dimColor:!0,children:[" ",w(s.lastSeen)]}),Ct(Je,{dimColor:!0,children:[" [",s.dimensionType,"]"]}),Ct(Je,{dimColor:!0,children:[" ",s.roleIds.length," role(s)"]}),Ct(Je,{dimColor:!0,children:[" x",s.count]})]}),$t(fr,{paddingLeft:4,flexDirection:"column",children:$t(Je,{color:I?"cyan":"white",children:C})})]},s.id)})})]})}import{Box as Nt,Text as ke,useInput as hs}from"ink";import{useEffect as tl,useState as ft,useCallback as ys,useRef as bs}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 mo(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 ms(e={}){let t=new URLSearchParams(Object.entries(e).map(([r,a])=>[r,String(a)])).toString();return mo(`/artifacts${t?"?"+t:""}`)}function fs(e){return mo(`/artifacts/${encodeURIComponent(e)}`)}function Lo(e,t=!1){return mo(`/artifacts/${encodeURIComponent(e)}${t?"?confirm=true":""}`,{method:"DELETE"})}function gs(e,t){return mo(`/artifacts/${encodeURIComponent(e)}/redeliver`,{method:"POST",body:JSON.stringify(t)})}import{spawn as Xa}from"child_process";async function ps(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 gr,Text as qt,useInput as Ya}from"ink";import{jsx as ve,jsxs as zt}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 Ze({label:e,value:t}){return zt(gr,{children:[ve(qt,{dimColor:!0,children:e.padEnd(20)}),ve(qt,{color:"cyan",children:t})]})}function xs({artifact:e,deliveryLog:t,onBack:r}){return Ya((a,o)=>{o.escape&&r()}),zt(gr,{flexDirection:"column",children:[ve(qt,{bold:!0,children:"Artifact Detail (Esc to go back)"}),zt(gr,{flexDirection:"column",marginTop:1,children:[ve(Ze,{label:"ID",value:e.id}),ve(Ze,{label:"Source",value:e.sourceKind}),ve(Ze,{label:"Role",value:e.producedByRole??e.roleId??"\u2014"}),ve(Ze,{label:"Mime",value:e.mime??"\u2014"}),ve(Ze,{label:"Kind",value:e.kind}),ve(Ze,{label:"Size",value:Qa(e.sizeBytes)}),ve(Ze,{label:"Created",value:Ja(e.createdAt)}),ve(Ze,{label:"Key",value:e.key??"\u2014"}),ve(Ze,{label:"Blob path",value:e.blobPath??"\u2014"}),e.executionId&&ve(Ze,{label:"Execution ID",value:e.executionId}),e.taskId&&ve(Ze,{label:"Task ID",value:e.taskId}),e.chatSessionId&&ve(Ze,{label:"Chat Session",value:e.chatSessionId}),e.originalFilename&&ve(Ze,{label:"Filename",value:e.originalFilename})]}),t.length>0&&zt(gr,{flexDirection:"column",marginTop:1,children:[zt(qt,{bold:!0,dimColor:!0,children:["Delivery Log (",t.length,")"]}),t.map((a,o)=>zt(gr,{children:[ve(qt,{dimColor:!0,children:" "}),ve(qt,{color:a.status==="delivered"?"green":a.status==="failed"?"red":"yellow",children:a.status}),zt(qt,{dimColor:!0,children:[" \u2192 ",a.target?.channelId??"\u2014",a.createdAt?` (${new Date(a.createdAt).toLocaleTimeString()})`:""]})]},o))]}),t.length===0&&ve(gr,{marginTop:1,children:ve(qt,{dimColor:!0,children:"No delivery log entries."})})]})}import{Box as fo,Text as Vt,useInput as Za}from"ink";import{useEffect as el,useState as Fo}from"react";import{jsx as Xt,jsxs as Dr}from"react/jsx-runtime";function Ts({onSelect:e,onCancel:t,fetchChannels:r}){let[a,o]=Fo([]),[u,d]=Fo(!0),[l,i]=Fo(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 b=a[g-1];b&&e(b.id)}}),u?Xt(fo,{children:Xt(Vt,{dimColor:!0,children:"Loading channels..."})}):l?Dr(fo,{children:[Xt(Vt,{color:"red",children:l}),Xt(Vt,{dimColor:!0,children:" (Esc to cancel)"})]}):Dr(fo,{flexDirection:"column",children:[Xt(Vt,{bold:!0,children:"Select channel to redeliver (Esc to cancel):"}),a.length===0?Xt(Vt,{dimColor:!0,children:"No channels configured."}):a.map((n,p)=>Dr(fo,{children:[Dr(Vt,{children:["[",p+1,"] "]}),Xt(Vt,{color:"cyan",children:n.name}),Dr(Vt,{dimColor:!0,children:[" (",n.platform,")"]})]},n.id))]})}import{jsx as fe,jsxs as Yt}from"react/jsx-runtime";function rl(e){return e?e.replace(/[\x00-\x1F\x7F]/g,""):""}function st(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 vs({onBack:e,onSelect:t,onAction:r}){let{dispatch:a}=tt(),[o,u]=ft([]),[d,l]=ft(0),[i,n]=ft(!0),[p,g]=ft(null),[b,y]=ft(0),[w,s]=ft("list"),[c,I]=ft(null),[C,E]=ft([]),[G,Y]=ft(null),[N,O]=ft(null),[V,B]=ft(null),z=bs(null),se=bs(null);function ne(D){B(D),se.current&&clearTimeout(se.current),se.current=setTimeout(()=>B(null),2e3)}let $e=ys(()=>{z.current&&z.current.abort(),z.current=new AbortController,n(!0),g(null),ms({limit:100}).then(D=>{u(D.artifacts),l(D.total),y(0),n(!1)}).catch(D=>{D.name!=="AbortError"&&(g(`Failed to load: ${D instanceof Error?D.message:String(D)}`),n(!1))})},[]);tl(()=>($e(),()=>{z.current&&z.current.abort(),se.current&&clearTimeout(se.current)}),[$e]),hs((D,ie)=>{if(G)if(D==="y"){let L=G;Y(null),Lo(L.id,!0).then(()=>{ne("Deleted"),$e()}).catch(ae=>ne(`Delete failed: ${ae instanceof Error?ae.message:String(ae)}`))}else(D==="n"||ie.escape)&&Y(null)}),hs((D,ie)=>{if(G||N)return;if(ie.escape||D==="q"){e();return}if(ie.upArrow||D==="k"){y(ae=>Math.max(0,ae-1));return}if(ie.downArrow||D==="j"){y(ae=>Math.min(Math.max(0,o.length-1),ae+1));return}if(D==="\r"||D===`
12
- `||D==="o"){if(o.length>0&&o[b]){let ae=o[b];t(ae),fs(ae.id).then(Ce=>{I(Ce.artifact),E(Ce.deliveryLog),s("detail")}).catch(()=>{I(ae),E([]),s("detail")})}return}let L=o.length>0?o[b]:void 0;if(L){if(D==="d"){r("d",L),To(L.mime)?Y(L):Lo(L.id,!1).then(()=>{ne("Deleted"),$e()}).catch(Ce=>ne(`Delete failed: ${Ce instanceof Error?Ce.message:String(Ce)}`));return}if(D==="r"){r("r",L),O(L);return}if(D==="c"){r("c",L);let ae=L.blobPath??"";ps(ae).then(Ce=>{ne(Ce?`Copied: ${ae.slice(-40)}`:"Clipboard unavailable")}).catch(()=>ne("Clipboard unavailable"));return}if(D==="t"){r("t",L);let ae=L.taskId??L.executionId;a({type:"SET_VIEW",view:"tasks",selectedTaskId:ae});return}}});let ge=ys(()=>{let{getApiKey:D,getPort:ie}={getApiKey:()=>process.env.ADAM_API_KEY??"",getPort:()=>Number(process.env.ADAM_PORT??7100)};return fetch(`http://localhost:${ie()}/channels`,{headers:{"x-api-key":D()}}).then(L=>L.json())},[]);if(w==="detail"&&c)return fe(xs,{artifact:c,deliveryLog:C,onBack:()=>s("list")});if(N){let D=N;return fe(Ts,{fetchChannels:ge,onSelect:ie=>{O(null),gs(D.id,{channelId:ie}).then(L=>ne(`Redeliver queued: ${L.status}`)).catch(L=>ne(`Redeliver failed: ${L instanceof Error?L.message:String(L)}`))},onCancel:()=>O(null)})}return i?Yt(Nt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{dimColor:!0,children:"Loading..."})]}):p?Yt(Nt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{color:"red",children:p}),fe(ke,{dimColor:!0,children:"Press Esc to go back or r to retry"})]}):Yt(Nt,{flexDirection:"column",children:[Yt(ke,{bold:!0,children:["Artifacts (",d,") (Esc to go back)"]}),fe(Nt,{children:Yt(ke,{dimColor:!0,bold:!0,children:[" ",st("#",3),st("Source",12),st("Role",12),st("Mime",16),st("Size",8),st("Created",16),"Delivered"]})}),o.length===0?fe(Nt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"No artifacts found."})}):o.map((D,ie)=>{let L=ie===b,ae=D.mime??"unknown",Ce=D.producedByRole??D.roleId??"\u2014";return Yt(Nt,{children:[fe(ke,{color:L?"cyan":void 0,bold:L,children:L?"> ":" "}),fe(ke,{color:L?"cyan":void 0,bold:L,children:st(String(ie+1),3)}),fe(ke,{color:L?"cyan":void 0,children:st(sl(D.sourceKind),12)}),fe(ke,{color:L?"cyan":void 0,children:st(rl(Ce).slice(0,11),12)}),fe(ke,{color:L?"cyan":void 0,children:st(ae.slice(0,15),16)}),fe(ke,{color:L?"cyan":void 0,children:st(ol(D.sizeBytes),8)}),fe(ke,{color:L?"cyan":void 0,children:st(nl(D.createdAt),16)}),fe(ke,{color:L?"cyan":void 0,children:"\u2014"})]},D.id)}),G&&fe(Nt,{marginTop:1,children:Yt(ke,{color:"red",children:["Delete this ",To(G.mime)," file? (y/n)"]})}),V&&!G&&fe(Nt,{marginTop:1,children:fe(ke,{color:"green",children:V})}),fe(Nt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"j/k=navigate enter=detail d=delete r=redeliver c=copy t=task"})})]})}import{Fragment as ml,jsx as te,jsxs as xr}from"react/jsx-runtime";function cl(){let{state:e,dispatch:t}=tt(),{session:r,sendMessage:a,createNewSession:o,archiveCurrentSession:u}=rn(),[d,l]=al([]);go(()=>{t({type:"SET_SESSION",session:r})},[r,t]),Zo();let{latestMessage:i}=nn(r?.id??null),n=Qt(null),p=Qt(new Set),g=Qt(new Set),b=Qt(new Set),y=Qt(new Set),[,w]=ll(B=>B+1,0);go(()=>{if(!i||i.id===n.current)return;n.current=i.id;let B=!i.kind||i.kind==="result_delivery"||i.kind==="assistant_text";if(B&&i.taskId&&g.current.has(i.taskId)){p.current.add(i.taskId);return}B&&i.taskId&&p.current.add(i.taskId),l(z=>[...z,{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:I}=tn(e.activeTaskId),C=s[s.length-1],E=C?.type==="complete"&&!c,G=Qt(null),Y=Qt("");go(()=>{Y.current=s.filter(B=>B.type==="reasoning").map(B=>B.content).join("")},[s]),go(()=>{if(E&&e.activeTaskId!==G.current){if(G.current=e.activeTaskId,e.activeTaskId&&p.current.has(e.activeTaskId))return;let B=C?.content||Y.current;B&&(e.activeTaskId&&g.current.add(e.activeTaskId),l(z=>[...z,{role:"assistant",content:B,taskId:e.activeTaskId??void 0,kind:"assistant_text"}]))}},[E,C,e.activeTaskId]);let N=async B=>{let z=B.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(z)&&process.exit(0),B.startsWith("/")){let ne=B.slice(1),ge={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"}[ne];if(ge){t({type:"SET_VIEW",view:ge});return}if(ne==="new"){if(await u()){let ie=await o();l([]),I(),p.current.clear(),g.current.clear(),b.current.clear(),y.current.clear(),ie&&l([{role:"assistant",content:`Session archived. New session started: ${ie.id.slice(0,8)}`}])}return}if(ne==="session"){let D=r?`Session: ${r.id}
8
+ \u2026`}function Ri(e,t){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}\u2026`}function Di(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Mi(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 $n(e){return new Date(e).toLocaleString()}function $i(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 Ni(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 Oi,jsx as de,jsxs as ue}from"react/jsx-runtime";var _n={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},Zr=["all","pending","queued","running","completed","failed","cancelled","blocked"],Bo=15;function to({onBack:e}){let[t,r]=Ft([]),[a,o]=Ft(!0),[u,d]=Ft("list"),[l,i]=Ft(0),[n,p]=Ft("all"),[g,b]=Ft(0),[y,w]=Ft(0),[s,c]=Ft(null),I=Ln(async()=>{o(!0);try{let N=new URLSearchParams({limit:"100"});n!=="all"&&N.set("status",n);let O=await v(`/tasks?${N}`);r(O.tasks)}catch{r([])}finally{o(!1)}},[n]);_i(()=>{I()},[I]);let C=Math.max(1,Math.ceil(t.length/Bo)),E=t.slice(y*Bo,(y+1)*Bo),G=Ln(async()=>{let N=E[l];if(N)try{await v(`/tasks/${N.id}/cancel`,{method:"POST"}),c(`Cancelled: ${N.id.slice(0,8)}`),d("list"),I()}catch(O){c(`Failed: ${O instanceof Error?O.message:String(O)}`),d("list")}},[E,l,I]);if(Li((N,O)=>{if(u==="detail"){(O.escape||O.return||N==="q")&&d("list");return}if(u==="cancelling"){N==="y"?G():d("list");return}if(u==="filter"){if(O.escape){d("list");return}O.upArrow&&g>0&&b(V=>V-1),O.downArrow&&g<Zr.length-1&&b(V=>V+1),O.return&&(p(Zr[g]),w(0),i(0),d("list"));return}if(O.escape||N==="q"){e();return}if(O.upArrow&&l>0&&i(V=>V-1),O.downArrow&&l<E.length-1&&i(V=>V+1),O.return&&E[l]&&d("detail"),N==="x"&&E[l]){let V=E[l];["running","pending","queued","paused"].includes(V.status)?(d("cancelling"),c(null)):c(`Cannot cancel task in status: ${V.status}`)}N==="f"&&(b(Zr.indexOf(n)),d("filter")),N==="r"&&I(),(O.pageDown||N==="n")&&y<C-1&&(w(V=>V+1),i(0)),(O.pageUp||N==="p")&&y>0&&(w(V=>V-1),i(0))}),a)return de(re,{dimColor:!0,children:"Loading tasks..."});if(u==="filter")return ue(Ae,{flexDirection:"column",children:[de(re,{bold:!0,children:"Filter by status:"}),Zr.map((N,O)=>de(Ae,{children:ue(re,{color:O===g?"cyan":"white",children:[O===g?"> ":" ",N,N===n?" (current)":""]})},N)),de(re,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(u==="detail"&&E[l])return de(Nn,{taskId:E[l].id,onBack:()=>d("list")});if(u==="cancelling"&&E[l])return ue(Ae,{flexDirection:"column",children:[ue(re,{color:"red",children:['Cancel task "',E[l].id.slice(0,8),'"? (y/n)']}),s&&de(re,{color:"red",children:s})]});let Y=E[l]??null;return ue(Ae,{flexDirection:"column",children:[ue(Ae,{children:[ue(re,{bold:!0,children:["Tasks (",t.length,")"]}),n!=="all"&&ue(re,{dimColor:!0,children:[" [filter: ",n,"]"]}),ue(re,{dimColor:!0,children:[" \u2022 Page ",y+1,"/",C]})]}),s&&de(re,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?ue(re,{dimColor:!0,children:["No tasks found",n!=="all"?` with status "${n}"`:"","."]}):ue(Ae,{marginTop:1,flexDirection:"row",gap:2,children:[de(Ae,{flexDirection:"column",flexGrow:3,children:E.map((N,O)=>{let V=O===l,B=_n[N.status]??"white";return ue(Ae,{flexDirection:"column",marginBottom:1,children:[ue(Ae,{children:[de(re,{color:V?"cyan":"gray",bold:V,children:V?"\u276F ":" "}),de(re,{color:B,bold:!0,children:N.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${N.id.slice(0,8)}`})]}),de(Ae,{paddingLeft:2,children:de(re,{color:V?"white":void 0,children:eo(N.prompt,V?72:56)})}),de(Ae,{paddingLeft:2,children:ue(re,{dimColor:!0,children:[qn(N.createdAt)," \u2022 ",Fn(N)," \u2022 ",On(N.costUsd)]})})]},N.id)})}),de(Ae,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?ue(Oi,{children:[de(re,{bold:!0,children:"Preview"}),ue(Ae,{marginTop:1,children:[de(re,{color:_n[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),de(re,{children:eo(Y.prompt,220)}),ue(Ae,{marginTop:1,flexDirection:"column",children:[ue(re,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),ue(re,{dimColor:!0,children:["Created: ",qn(Y.createdAt)]}),ue(re,{dimColor:!0,children:["Duration: ",Fn(Y)]}),ue(re,{dimColor:!0,children:["Cost: ",On(Y.costUsd)]}),ue(re,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"red",bold:!0,children:"Error"}),de(re,{color:"red",children:eo(Y.error,180)})]}):Y.result?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"green",bold:!0,children:"Latest Result"}),de(re,{children:eo(Y.result,180)})]}):null,de(Ae,{marginTop:1,children:de(re,{dimColor:!0,children:"Enter opens full detail"})})]}):de(re,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Fi(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function eo(e,t){return Fi(e.replace(/\s+/g," ").trim(),t)}function Fn(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 On(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function qn(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`}To();import{Box as Gt,Text as Ge,useInput as qi}from"ink";import{useEffect as Vi,useState as Vn}from"react";import{readFileSync as Ui,existsSync as Wi}from"fs";import{parse as Gi}from"yaml";import{Fragment as Ki,jsx as Fe,jsxs as Xe}from"react/jsx-runtime";function Un({onBack:e}){let[t,r]=Vn(null),[a,o]=Vn(null);return qi((u,d)=>{(d.escape||u==="q")&&e()}),Vi(()=>{try{let u=Ho;if(!Wi(u)){o(`Config file not found: ${u}`);return}let d=Ui(u,"utf-8");r(Gi(d))}catch(u){o(u.message)}},[]),a?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{color:"red",children:a}),Fe(Ge,{dimColor:!0,children:"Press Esc to go back"})]}):t?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{bold:!0,children:"Configuration (Esc to go back)"}),Fe(Gt,{marginTop:1,flexDirection:"column",children:Fe(Io,{obj:t,indent:0})})]}):Fe(Ge,{dimColor:!0,children:"Loading config..."})}function Io({obj:e,indent:t}){let r=" ".repeat(t);return Fe(Ki,{children:Object.entries(e).map(([a,o])=>Fe(ji,{label:a,value:o,indent:t,parentKey:a},a))})}function ji({label:e,value:t,indent:r,parentKey:a}){let o=" ".repeat(r);return Array.isArray(t)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),t.length===0?Xe(Ge,{dimColor:!0,children:[o," []"]}):t.map((u,d)=>Fe(Wn,{value:u,indent:r+1,parentKey:a,index:d},`${e}-${d}`))]}):t&&typeof t=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),Fe(Io,{obj:t,indent:r+1})]}):Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),": ",Gn(a,jn(t))]})}function Wn({value:e,indent:t,parentKey:r,index:a}){let o=" ".repeat(t);return Array.isArray(e)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"- [",a,"]"]}),e.map((u,d)=>Fe(Wn,{value:u,indent:t+1,parentKey:r,index:d},`${a}-${d}`))]}):e&&typeof e=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"-"]}),Fe(Io,{obj:e,indent:t+1})]}):Xe(Ge,{children:[o,"- ",Gn(r,jn(e))]})}function Gn(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 jn(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as ro,Text as lt,useInput as Hi}from"ink";import{useEffect as zi,useState as Eo}from"react";import{jsx as Ir,jsxs as ht}from"react/jsx-runtime";function Kn({onBack:e}){let[t,r]=Eo([]),[a,o]=Eo(!0),[u,d]=Eo(null);return Hi((l,i)=>{(i.escape||l==="q")&&e()}),zi(()=>{v("/evolution-audit?limit=20").then(l=>{r(l),o(!1)}).catch(l=>{d(l.message),o(!1)})},[]),a?Ir(lt,{dimColor:!0,children:"Loading evolution log..."}):u?ht(ro,{flexDirection:"column",children:[Ir(lt,{color:"red",children:u}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?ht(ro,{flexDirection:"column",children:[Ir(lt,{dimColor:!0,children:"No evolution records yet"}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):ht(ro,{flexDirection:"column",children:[ht(lt,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(l=>ht(ro,{flexDirection:"column",marginTop:1,children:[ht(lt,{bold:!0,children:["[",new Date(l.timestamp).toLocaleString(),"]"]}),l.triggerTaskId&&ht(lt,{dimColor:!0,children:[" Task: ",l.triggerTaskId.slice(0,8)]}),l.diff.split(`
9
+ `).map((i,n)=>i.startsWith("+")?ht(lt,{color:"green",children:[" ",i]},n):i.startsWith("-")?ht(lt,{color:"red",children:[" ",i]},n):ht(lt,{dimColor:!0,children:[" ",i]},n))]},l.id))]})}import{Box as At,Text as Te,useInput as Xi}from"ink";import Yi from"ink-text-input";import{useEffect as Qi,useState as sr}from"react";import{jsx as je,jsxs as Pe}from"react/jsx-runtime";var Ji={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Zi(e,t=20){let r=Math.round(e*t),a=t-r;return"\u2588".repeat(r)+"\u2591".repeat(a)}function ea(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function oo({onBack:e}){let[t,r]=sr([]),[a,o]=sr(null),[u,d]=sr("list"),[l,i]=sr(""),[n,p]=sr(!1),[g,b]=sr(null);Xi((s,c)=>{if(u==="create"){c.escape&&(d("list"),i(""),b(null));return}(c.escape||s==="q")&&e(),s==="c"&&(d("create"),b(null)),s==="r"&&y()});let y=()=>{v("/goals?limit=20").then(({goals:s})=>r(s)).catch(s=>o(s.message))};Qi(()=>{y()},[]);let w=async s=>{if(s.trim()){p(!0),b(null);try{let c=await v("/goals",{method:"POST",body:{input:s.trim()}});b(`Goal created: ${c.goal.name}`),i(""),d("list"),y()}catch(c){b(`Failed: ${c instanceof Error?c.message:String(c)}`)}finally{p(!1)}}};return a?Pe(At,{flexDirection:"column",children:[Pe(Te,{color:"red",children:["Failed to load goals: ",a]}),je(Te,{dimColor:!0,children:"Press Esc or q to return"})]}):u==="create"?Pe(At,{flexDirection:"column",children:[je(Te,{bold:!0,children:"Create Goal"}),je(Te,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Pe(At,{marginTop:1,children:[je(Te,{color:"cyan",children:"> "}),je(Yi,{value:l,onChange:i,onSubmit:w})]}),n&&je(Te,{color:"yellow",children:"Creating goal..."}),g&&je(Te,{color:g.startsWith("Failed")?"red":"green",children:g}),je(Te,{dimColor:!0,children:"Press Esc to cancel"})]}):Pe(At,{flexDirection:"column",children:[Pe(Te,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?je(Te,{dimColor:!0,children:"No goals found. Press c to create one."}):je(At,{marginTop:1,flexDirection:"column",children:t.map(s=>{let c=s.targetValue>0?s.currentValue/s.targetValue:0,I=Ji[s.status]??"white";return Pe(At,{marginBottom:1,flexDirection:"column",children:[Pe(At,{children:[je(Te,{bold:!0,color:I,children:s.name}),Pe(Te,{dimColor:!0,children:[" (",s.role,")"]}),je(Te,{dimColor:!0,children:" \u2014 "}),je(Te,{color:I,children:s.status})]}),Pe(At,{children:[Pe(Te,{dimColor:!0,children:[" ",Zi(c)," "]}),Pe(Te,{color:c>=1?"green":"white",children:[Math.round(c*100),"%"]}),Pe(Te,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),Pe(At,{children:[Pe(Te,{dimColor:!0,children:[" \u23F0 ",ea(s.deadline)," left"]}),Pe(Te,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),Pe(Te,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),je(Te,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as ir,Text as rt,useInput as ta}from"ink";import{useEffect as ra,useState as Hn}from"react";import{jsx as Rt,jsxs as Pt}from"react/jsx-runtime";function oa(e,t,r=15){let a=e/(e+t),o=Math.round(a*r);return"\u2593".repeat(o)+"\u2591".repeat(r-o)}function zn({onBack:e}){let[t,r]=Hn([]),[a,o]=Hn(null);if(ta((d,l)=>{(l.escape||d==="q")&&e()}),ra(()=>{v("/strategies?limit=50").then(d=>r(d.strategies??[])).catch(d=>o(d.message))},[]),a)return Pt(ir,{flexDirection:"column",children:[Pt(rt,{color:"red",children:["Failed to load strategies: ",a]}),Rt(rt,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Pt(ir,{flexDirection:"column",children:[Rt(rt,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Rt(rt,{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 Pt(ir,{flexDirection:"column",children:[Rt(rt,{bold:!0,children:"Strategy Lab"}),Rt(rt,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Rt(ir,{marginTop:1,flexDirection:"column",children:Array.from(u.entries()).map(([d,l])=>Pt(ir,{marginBottom:1,flexDirection:"column",children:[Rt(rt,{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 Pt(ir,{children:[Rt(rt,{dimColor:!0,children:" "}),Pt(rt,{children:[oa(i.alpha,i.beta)," "]}),Pt(rt,{color:n>.6?"green":n>.4?"yellow":"red",children:[(n*100).toFixed(0),"%"]}),Pt(rt,{dimColor:!0,children:[" ",i.name," (\u03B1=",i.alpha.toFixed(1)," \u03B2=",i.beta.toFixed(1)," trials=",i.totalTrials,")"]})]},i.id)})]},d))}),Rt(rt,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as ye,Text as W,useInput as la}from"ink";import Ao from"ink-text-input";import{useEffect as ca,useState as Oe,useCallback as yt}from"react";import{CronExpressionParser as da}from"cron-parser";import{useState as na,useEffect as sa,useCallback as Xn,useRef as ia}from"react";var aa=3e3;function ot(){let[e,t]=na(null),r=ia(null),a=Xn(()=>{r.current&&(clearTimeout(r.current),r.current=null),t(null)},[]),o=Xn((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},aa))},[]);return sa(()=>()=>{r.current&&clearTimeout(r.current)},[]),{message:e,setMessage:o,clearMessage:a}}import{Fragment as ma,jsx as Z,jsxs as Q}from"react/jsx-runtime";var Po=["manual","cron","once","template_complete"],Yn=["cron","once","template_complete"],no={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function ua(e){try{return da.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function so({onBack:e}){let[t,r]=Oe([]),[a,o]=Oe(!0),[u,d]=Oe(0),[l,i]=Oe("list"),[n,p]=Oe({...no}),[g,b]=Oe("name"),[y,w]=Oe(null),{message:s,setMessage:c,clearMessage:I}=ot(),[C,E]=Oe(!1),[G,Y]=Oe(!1),[N,O]=Oe({}),[V,B]=Oe(null),[z,se]=Oe(!1),[ne,$e]=Oe(!1),[ge,D]=Oe([]),[ie,_]=Oe({}),ae=yt(async S=>{try{let A=await v(`/template-executions?templateId=${S}&limit=5`);D(A.executions??[])}catch{D([])}},[]),Ce=yt(async(S,A)=>{try{await v(`/executions/${S}/feedback`,{method:"POST",body:{rating:A}}),_($=>({...$,[S]:A}))}catch($){c(`Feedback failed: ${$ instanceof Error?$.message:String($)}`,"error")}},[c]),L=yt(()=>{o(!0),v("/task-templates").then(({templates:S})=>{r(S),new Set(S.flatMap($=>$.steps?.map(le=>le.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:$})=>{if(!Array.isArray($)){O({});return}O(Object.fromEntries($.map(le=>[le.id,le.name])))}).catch(()=>O({})):O({}),o(!1)}).catch(()=>o(!1))},[]);ca(()=>{L()},[L]);let K=l==="create"||l==="edit",ee=yt(async()=>{let S=t[u];if(!(!S||C)){E(!0),c(`Triggering ${S.name}...`,"loading");try{let A=await v(`/task-templates/${S.id}/run`,{method:"POST"});c(`Triggered: ${S.name} (${A.executionId})`,"success")}catch(A){c(`Trigger failed: ${A instanceof Error?A.message:String(A)}`,"error")}finally{E(!1)}}},[t,u,C,c]),pe=yt(async()=>{let S=t[u];if(!S||G)return;if(!Yn.includes(S.trigger?.type??"manual")){c("Toggle not applicable for manual triggers","error");return}let A=!S.enabled;Y(!0),c(`${S.name} \u2192 ${A?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${S.id}`,{method:"PATCH",body:{enabled:A}}),r($=>$.map(le=>le.id===S.id?{...le,enabled:A}:le)),c(`${S.name} ${A?"enabled":"disabled"}`,"success")}catch($){c(`Toggle failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{Y(!1)}},[t,u,G,c]),St=yt(async()=>{if(z)return;let S=t[u];if(S){se(!0);try{let A=await v(`/task-templates/${S.id}/dependents`,{method:"GET"});B({templateId:S.id,templateName:S.name,executionCount:A.dependents.executionCount,taskCount:A.dependents.taskCount}),A.dependents.taskCount===0&&A.dependents.executionCount===0?c(`Delete "${S.name}"? Press d to confirm, Esc to cancel.`,"loading"):c(`"${S.name}" has ${A.dependents.executionCount} template execution${A.dependents.executionCount===1?"":"s"}, ${A.dependents.taskCount} task${A.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(A){c(`Failed to inspect dependents: ${A instanceof Error?A.message:String(A)}`,"error")}finally{se(!1)}}},[t,u,c,z]),gt=yt(async S=>{let A=V;if(A){B(null);try{let $=await v(`/task-templates/${A.templateId}?mode=${S}`,{method:"DELETE"}),le=[];$.deletedCounts.templateExecutions>0&&le.push(`${$.deletedCounts.templateExecutions} template exec`),$.deletedCounts.tasks>0&&le.push(`${$.deletedCounts.tasks} task${$.deletedCounts.tasks===1?"":"s"}`);let Ue=le.length?` (+${le.join(", ")})`:"";c(`Deleted: ${A.templateName}${Ue}`,"success"),L(),d(Ne=>Math.max(0,Math.min(Ne,t.length-2)))}catch($){c(`Delete failed: ${$ instanceof Error?$.message:String($)}`,"error")}}},[V,L,c,t.length]),et=yt(()=>{B(null),I()},[I]),Ut=yt(()=>{let S=t[u];S&&(w(S.id),p({name:S.name,triggerType:S.trigger?.type??"manual",cron:S.trigger?.cron??"",targetTemplateId:S.trigger?.type==="template_complete"?S.trigger.event?.split(":")[1]??"":"",stepPrompt:S.steps?.[0]?.prompt??""}),b("name"),i("edit"))},[t,u]),Jt=yt(async()=>{let S={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 v("/task-templates",{method:"POST",body:S}),c(`Created: ${n.name}`,"success")):l==="edit"&&y&&(await v(`/task-templates/${y}`,{method:"PATCH",body:S}),c(`Updated: ${n.name}`,"success"))}catch(A){c(`Save failed: ${A instanceof Error?A.message:String(A)}`,"error")}i("list"),p({...no}),w(null),L()},[n,l,y,L]);return la((S,A)=>{if(K){if(A.escape){i("list"),p({...no}),w(null);return}if(A.return){let $=["name","triggerType","cron","stepPrompt"],Ue=n.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:$.filter(M=>M!=="targetTemplateId"),Ne=Ue.indexOf(g);if(Ne<Ue.length-1){let M=Ne+1;if(Ue[M]==="cron"&&n.triggerType!=="cron"&&M++,M<Ue.length){b(Ue[M]);return}}Jt();return}if(A.tab&&g==="triggerType"){p($=>{let le=Po.indexOf($.triggerType);return{...$,triggerType:Po[(le+1)%Po.length]}});return}if(A.tab&&g==="targetTemplateId"){p($=>{let le=t.filter(M=>M.id!==y),Ue=le.findIndex(M=>M.id===$.targetTemplateId),Ne=le[(Ue+1)%le.length];return{...$,targetTemplateId:Ne?.id??""}});return}return}if(V){if(A.escape){et();return}if(S==="D"&&A.shift){gt("with_tasks");return}if(S==="d"&&!A.shift){gt("template_only");return}return}if(A.escape||S==="q"){e();return}if(A.upArrow){d($=>Math.max(0,$-1));return}if(A.downArrow){d($=>Math.min(t.length-1,$+1));return}if(S==="t"){ee();return}if(S==="d"&&!A.shift){St();return}if(S==="e"){Ut();return}if(S==="c"){p({...no}),b("name"),i("create");return}if(S==="s"||S===" "){pe();return}if(S==="r"&&(L(),I()),S==="x"){let $=t[u];if(!$)return;ne?($e(!1),D([])):($e(!0),ae($.id));return}if(S==="g"&&ne&&ge.length>0){Ce(ge[0].id,"good");return}if(S==="b"&&ne&&ge.length>0){Ce(ge[0].id,"bad");return}}),a?Z(W,{dimColor:!0,children:"Loading templates..."}):K?Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:[l==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),Q(ye,{marginTop:1,flexDirection:"column",children:[Q(ye,{children:[Q(W,{bold:g==="name",color:g==="name"?"cyan":void 0,children:["Name:"," "]}),g==="name"?Z(Ao,{value:n.name,onChange:S=>p(A=>({...A,name:S})),placeholder:"template name"}):Z(W,{children:n.name||"(empty)"})]}),Q(ye,{children:[Q(W,{bold:g==="triggerType",color:g==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),Z(W,{children:n.triggerType}),g==="triggerType"&&Z(W,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),n.triggerType==="cron"&&Q(ye,{children:[Q(W,{bold:g==="cron",color:g==="cron"?"cyan":void 0,children:["Cron:"," "]}),g==="cron"?Z(Ao,{value:n.cron,onChange:S=>p(A=>({...A,cron:S})),placeholder:"*/5 * * * *"}):Z(W,{children:n.cron||"(empty)"})]}),n.triggerType==="template_complete"&&Q(ye,{children:[Q(W,{bold:g==="targetTemplateId",color:g==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),Z(W,{children:(()=>{let S=t.find(A=>A.id===n.targetTemplateId);return S?S.name:n.targetTemplateId?`(id: ${n.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),g==="targetTemplateId"&&Z(W,{dimColor:!0,children:" (Tab to cycle)"})]}),Q(ye,{children:[Q(W,{bold:g==="stepPrompt",color:g==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),g==="stepPrompt"?Z(Ao,{value:n.stepPrompt,onChange:S=>p(A=>({...A,stepPrompt:S})),placeholder:"What should this template do?"}):Z(W,{children:n.stepPrompt||"(empty)"})]})]}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&Z(ye,{marginTop:1,children:Q(W,{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?Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"No templates found. Press c to create one."})}):Z(ye,{marginTop:1,flexDirection:"column",children:t.map((S,A)=>{let $=A===u,le=S.trigger?.type==="cron"&&S.trigger?.cron?ua(S.trigger.cron):"",Ue=new Set(S.steps?.filter(M=>M.roleId).map(M=>M.roleId)),Ne=S.steps?.length>1?`${S.steps.length} steps${Ue.size>0?` / ${Ue.size} roles`:""}`:`${S.steps?.length??0} step`;return Q(ye,{flexDirection:"column",children:[Q(ye,{children:[Z(W,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),Z(W,{color:$?"cyan":void 0,bold:$,children:Er(S.name,24)}),Z(W,{dimColor:!0,children:Er(S.trigger?.type,10)}),Yn.includes(S.trigger?.type??"manual")?Z(W,{color:S.enabled?"green":"gray",children:Er(S.enabled?"on":"off",6)}):Z(W,{dimColor:!0,children:Er("\u2014",6)}),Z(W,{dimColor:!0,children:Er(Ne,18)}),le&&Q(W,{dimColor:!0,children:["next: ",le]})]}),$&&Q(ma,{children:[S.config?.delivery&&Z(ye,{marginLeft:4,marginTop:0,children:Q(W,{dimColor:!0,children:[" Delivery: ",S.config.delivery.mode,S.config.delivery.mode==="primary-artifact"&&S.config.delivery.primaryArtifact&&` (${S.config.delivery.primaryArtifact.stepId}/${S.config.delivery.primaryArtifact.key})`]})}),S.steps&&S.steps.length>1&&Z(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:S.steps.map((M,Zt)=>Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt+1,". "]}),Z(W,{dimColor:!0,children:M.id}),M.roleId&&Q(W,{color:"yellow",children:[" @",N[M.roleId]??M.roleId]}),M.dependsOn&&M.dependsOn.length>0&&Q(W,{dimColor:!0,children:[" (after: ",M.dependsOn.join(", "),")"]}),M.consumesFrom&&M.consumesFrom.length>0&&Q(W,{dimColor:!0,children:[" [consumes: ",M.consumesFrom.join(", "),"]"]}),M.consumesFromOptional&&M.consumesFromOptional.length>0&&Q(W,{dimColor:!0,children:[" [consumes?: ",M.consumesFromOptional.join(", "),"]"]}),M.persona&&Q(W,{dimColor:!0,children:[" [speak as: ",M.persona.speakAs,M.persona.voiceConstraints?` / ${M.persona.voiceConstraints}`:"","]"]}),M.outputContract&&Q(W,{dimColor:!0,children:[" [",(M.outputContract.contractRules??[]).map(wt=>wt.kind).join(" "),M.outputContract.mustReferenceArtifacts?" ref-artifacts":"","]"]}),M.config&&Q(W,{dimColor:!0,children:[" ","[",[M.config.timeout!==void 0?`timeout:${M.config.timeout}s`:"",M.config.maxTurns!==void 0?`turns:${M.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},M.id))}),$&&ne&&Q(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:[ge.length===0?Z(W,{dimColor:!0,children:" No recent executions"}):ge.map((M,Zt)=>{let wt=ie[M.id];return Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt===0?">":" "," "]}),Z(W,{color:M.status==="completed"?"green":M.status==="failed"?"red":"gray",children:M.status.padEnd(10)}),Z(W,{dimColor:!0,children:new Date(M.startedAt).toLocaleString().slice(0,16)}),Q(W,{dimColor:!0,children:[" ",M.id.slice(0,8)]}),wt&&Z(W,{color:wt==="good"?"green":"red",children:wt==="good"?" \u{1F44D}":" \u{1F44E}"})]},M.id)}),ge.length>0&&Z(W,{dimColor:!0,children:" g:good b:bad (rates most recent)"})]})]})]},S.id)})}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh x:executions"})})]})}function Er(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ot,Text as Ye,useInput as fa}from"ink";import ga from"ink-text-input";import{useEffect as pa,useState as ar,useCallback as Qn}from"react";import{jsx as qe,jsxs as jt}from"react/jsx-runtime";function Jn({onBack:e}){let[t,r]=ar([]),[a,o]=ar(""),[u,d]=ar(!0),[l,i]=ar(!1),[n,p]=ar(""),[g,b]=ar(null),y=Qn(()=>{d(!0),v("/webhooks").then(({webhooks:s,auth:c})=>{r(s),o(c),d(!1)}).catch(()=>d(!1))},[]);pa(()=>{y()},[y]);let w=Qn(async s=>{if(s.trim())try{let c=await v(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});b(`Triggered: ${c.executionId}`)}catch(c){b(`Trigger failed: ${c instanceof Error?c.message:String(c)}`)}},[]);return fa((s,c)=>{if(l){if(c.escape){i(!1),p("");return}if(c.return){w(n),i(!1),p("");return}return}if(c.escape||s==="q"){e();return}if(s==="t"){i(!0),p(""),b(null);return}s==="r"&&(y(),b(null))}),u?qe(Ye,{dimColor:!0,children:"Loading webhooks..."}):jt(Ot,{flexDirection:"column",children:[jt(Ye,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),jt(Ye,{dimColor:!0,children:["Auth: ",a]}),g&&qe(Ot,{marginTop:1,children:qe(Ye,{color:"yellow",children:g})}),l&&jt(Ot,{marginTop:1,children:[qe(Ye,{bold:!0,color:"cyan",children:"Trigger webhook: "}),qe(ga,{value:n,onChange:p,placeholder:"webhook name or ID"}),qe(Ye,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):jt(Ot,{marginTop:1,flexDirection:"column",children:[qe(Ot,{children:jt(Ye,{bold:!0,children:[lr("NAME",24),lr("DESCRIPTION",36),lr("TRIGGER",28),"TAGS"]})}),t.map(s=>jt(Ot,{children:[qe(Ye,{children:lr(s.displayName,24)}),qe(Ye,{dimColor:!0,children:lr(xa(s.description??"",34),36)}),qe(Ye,{dimColor:!0,children:lr(s.trigger,28)}),qe(Ye,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function lr(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 bt,Text as Se,useInput as Ta}from"ink";import ha from"ink-text-input";import{useEffect as Zn,useState as Dt,useCallback as Ro}from"react";import{jsx as we,jsxs as ct}from"react/jsx-runtime";function ya(e){return e>=4?"red":e===3?"yellow":"gray"}function ba(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function va(e){return new Date(e).toLocaleDateString()}function ts({onBack:e}){let[t,r]=Dt([]),[a,o]=Dt(0),[u,d]=Dt([]),[l,i]=Dt(!0),[n,p]=Dt(!1),[g,b]=Dt(""),[y,w]=Dt("all"),[s,c]=Dt(null),[I,C]=Dt(!1),E=Ro(()=>{v("/agents").then(({agents:B})=>{r(B),i(!1)}).catch(()=>i(!1))},[]);Zn(()=>{E()},[E]);let G=t[a],Y=Ro(()=>{G&&(C(!1),v(`/memories/${G.id}`).then(({memories:B})=>{d(B),c(null)}).catch(B=>c(`Failed: ${B instanceof Error?B.message:String(B)}`)))},[G]);Zn(()=>{G&&Y()},[G,Y]);let N=Ro(async B=>{if(!(!G||!B.trim()))try{let z=await v("/memories/query",{method:"POST",body:{agentId:G.id,prompt:B.trim()}});d(z.memories),C(!0),c(`Search: ${z.count} results`)}catch(z){c(`Search failed: ${z instanceof Error?z.message:String(z)}`)}},[G]),O=n,V=u.filter(B=>y==="all"?!0:y==="high"?B.importance>3:y==="medium"?B.importance===3:B.importance<3);return Ta((B,z)=>{if(O){if(z.escape){p(!1),b("");return}if(z.return){N(g),p(!1),b("");return}return}if(z.escape||B==="q"){e();return}if(B==="a"){o(se=>(se+1)%Math.max(1,t.length));return}if(z.leftArrow){o(se=>(se-1+t.length)%Math.max(1,t.length));return}if(z.rightArrow){o(se=>(se+1)%Math.max(1,t.length));return}if(B==="s"){p(!0),b(""),c(null);return}if(B==="h"){w(se=>se==="high"?"all":"high");return}if(B==="m"){w(se=>se==="medium"?"all":"medium");return}if(B==="l"){w(se=>se==="low"?"all":"low");return}B==="r"&&Y()}),l?we(Se,{dimColor:!0,children:"Loading agents..."}):t.length===0?ct(bt,{flexDirection:"column",children:[we(Se,{dimColor:!0,children:"No agents found"}),we(Se,{dimColor:!0,children:"Press Esc to go back"})]}):ct(bt,{flexDirection:"column",children:[we(Se,{bold:!0,children:"Memories (Esc to go back)"}),ct(bt,{marginTop:1,children:[we(Se,{children:"Agent: "}),we(Se,{bold:!0,color:"cyan",children:G?.name??"?"}),ct(Se,{dimColor:!0,children:[" (",a+1,"/",t.length,") [a/arrows to switch]"]})]}),we(bt,{children:ct(Se,{dimColor:!0,children:["Filter: ",y==="all"?"all":y," | ",I?"search results":"all memories"," (",V.length,")"]})}),s&&we(bt,{children:we(Se,{color:"yellow",children:s})}),n&&ct(bt,{marginTop:1,children:[we(Se,{bold:!0,color:"cyan",children:"Search: "}),we(ha,{value:g,onChange:b,placeholder:"search query..."}),we(Se,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),V.length===0?we(bt,{marginTop:1,children:ct(Se,{dimColor:!0,children:["No memories",y!=="all"?` matching filter '${y}'`:""]})}):we(bt,{marginTop:1,flexDirection:"column",children:V.map(B=>ct(bt,{marginBottom:0,children:[ct(Se,{color:ya(B.importance),bold:!0,children:[ba(B.importance)," "]}),we(Se,{dimColor:!0,children:es(B.type??"?",12)}),we(Se,{dimColor:!0,children:es(`\xD7${B.retrievedCount??0}`,5)}),ct(Se,{children:[Ca(B.content,55)," "]}),we(Se,{dimColor:!0,children:va(B.createdAt)}),B.score!==void 0&&ct(Se,{dimColor:!0,children:[" (",B.score.toFixed(2),")"]})]},B.id))}),we(bt,{marginTop:1,children:we(Se,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function es(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Ca(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as dt,Text as be,useInput as Sa}from"ink";import io from"ink-text-input";import{useState as Ke,useEffect as rs,useCallback as Do}from"react";import{jsx as Re,jsxs as Ie}from"react/jsx-runtime";var os={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"]},wa={"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 ns({onBack:e}){let{state:t}=tt(),[r,a]=Ke({}),[o,u]=Ke([]),[d,l]=Ke(null),[i,n]=Ke("view"),[p,g]=Ke(0),[b,y]=Ke(""),[w,s]=Ke(null),[c,I]=Ke(!1),[C,E]=Ke([]),[G,Y]=Ke({}),[N,O]=Ke(0),[V,B]=Ke(""),[z,se]=Ke(""),[ne,$e]=Ke(""),ge=Object.values(os).flat(),D=Do(()=>{v("/config").then(L=>{a(L.config),u(L.mutable)}).catch(L=>l(L.message)),v("/config/env-diff").then(L=>{E(L.diffs)}).catch(()=>{}),v("/config/env").then(L=>Y(L.env??{})).catch(()=>{})},[]);rs(()=>{D()},[D]),rs(()=>{t.configVersion>0&&D()},[t.configVersion,D]);let ie=Do(async()=>{let L=ge[p];if(L){I(!0),s(null);try{let K=b,ee=r[L];if(ee&&typeof ee.value=="number"&&(K=Number(b),isNaN(K))){s("Invalid number"),I(!1);return}let pe=await v("/config",{method:"PATCH",body:{[L]:K}});pe.updated.length>0&&(s(`Updated: ${L}`),D()),pe.errors.length>0&&s(pe.errors[0]),n("view")}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}finally{I(!1)}}},[ge,p,b,r,D]),_=Object.keys(G),ae=Do(async L=>{try{await v("/config/env",{method:"PUT",body:L}),s("Env vars saved"),D()}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}},[D]);if(Sa((L,K)=>{if(i==="edit"){if(K.escape){n("view");return}return}if(i==="env-list"){if(K.escape){n("view");return}if(K.upArrow&&N>0&&O(ee=>ee-1),K.downArrow&&N<_.length-1&&O(ee=>ee+1),L==="a"){B(""),n("env-add-key");return}if(L==="d"&&_.length>0){let ee=_[N],pe={...G};delete pe[ee],ae(pe),N>=_.length-1&&N>0&&O(St=>St-1);return}if(K.return&&_.length>0){$e(G[_[N]]??""),n("env-edit-value");return}return}if(i==="env-add-key"){if(K.escape){n("env-list");return}return}if(i==="env-add-value"){if(K.escape){n("env-list");return}return}if(i==="env-edit-value"){if(K.escape){n("env-list");return}return}if(K.escape||L==="q"){e();return}if(K.upArrow&&p>0&&g(ee=>ee-1),K.downArrow&&p<ge.length-1&&g(ee=>ee+1),K.return||L==="e"){let ee=ge[p],pe=r[ee];pe&&pe.mutable?(y(String(pe.value??"")),n("edit"),s(null)):pe&&!pe.mutable&&s("This setting requires a restart to change")}L==="v"&&(O(0),n("env-list"),s(null)),L==="r"&&(D(),s("Refreshed")),L==="s"&&C.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),E([]),D()}),L==="l"&&C.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),D()})}),d)return Ie(dt,{flexDirection:"column",children:[Ie(be,{color:"red",children:["Failed to load config: ",d]}),Re(be,{dimColor:!0,children:"Press Esc or q to return"})]});let Ce=0;return Ie(dt,{flexDirection:"column",children:[Re(be,{bold:!0,children:"Settings"}),w&&Re(be,{color:w.startsWith("Failed")||w.startsWith("This setting")?"yellow":"green",children:w}),C&&C.length>0&&Ie(dt,{flexDirection:"column",marginBottom:1,children:[Ie(be,{color:"yellow",children:[".env differs from DB (",C.length," key(s)): ",C.map(L=>L.envKey).join(", ")]}),Re(be,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Re(dt,{marginTop:1,flexDirection:"column",children:Object.entries(os).map(([L,K])=>Ie(dt,{marginBottom:1,flexDirection:"column",children:[Re(be,{bold:!0,color:"cyan",children:L}),K.map(ee=>{let pe=r[ee],gt=Ce++===p,et=o.includes(ee),Ut=wa[ee]??ee,Jt=pe?String(pe.value??""):"...";return i==="edit"&&gt?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",Ut,": "]}),Re(io,{value:b,onChange:y,onSubmit:()=>{ie()}}),c&&Re(be,{color:"yellow",children:" saving..."})]},ee):Ie(dt,{children:[Ie(be,{color:gt?"cyan":"white",children:[gt?"> ":" ",et?" ":"\u{1F512} ",Ut,": "," "]}),Re(be,{color:et?"white":"gray",children:Jt}),!et&&Re(be,{dimColor:!0,children:" (restart required)"})]},ee)})]},L))}),Re(be,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),i.startsWith("env")&&Ie(dt,{flexDirection:"column",marginTop:1,children:[Ie(be,{bold:!0,color:"cyan",children:["Environment Variables (",_.length,")"]}),_.length===0&&i==="env-list"&&Re(be,{dimColor:!0,children:" No env vars. Press a to add."}),_.map((L,K)=>{let ee=K===N;return i==="env-edit-value"&&ee?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",L," = "]}),Re(io,{value:ne,onChange:$e,onSubmit:()=>{ae({...G,[L]:ne}),n("env-list")}})]},L):Ie(be,{color:ee&&i==="env-list"?"cyan":"white",children:[ee&&i==="env-list"?"> ":" ",L," = ",G[L]]},L)}),i==="env-add-key"&&Ie(dt,{children:[Re(be,{color:"green",children:" New key: "}),Re(io,{value:V,onChange:B,onSubmit:()=>{V.trim()&&(se(""),n("env-add-value"))}})]}),i==="env-add-value"&&Ie(dt,{children:[Ie(be,{color:"green",children:[" ",V," = "]}),Re(io,{value:z,onChange:se,onSubmit:()=>{ae({...G,[V.trim()]:z}),n("env-list")}})]}),Re(be,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as Kt,Text as Ve,useInput as ka}from"ink";import{useEffect as Ba,useState as Mo,useCallback as Ia}from"react";import{jsx as Me,jsxs as dr}from"react/jsx-runtime";function ss({onBack:e}){let[t,r]=Mo([]),[a,o]=Mo(!0),[u,d]=Mo(0),{message:l,setMessage:i,clearMessage:n}=ot(),p=Ia(()=>{o(!0),v("/plugins").then(({plugins:g})=>{r(g),o(!1)}).catch(()=>o(!1))},[]);return Ba(()=>{p()},[p]),ka((g,b)=>{if(b.escape||g==="q"){e();return}if(b.upArrow){d(y=>Math.max(0,y-1));return}if(b.downArrow){d(y=>Math.min(t.length-1,y+1));return}g==="r"&&(p(),n())}),a?Me(Ve,{dimColor:!0,children:"Loading plugins..."}):dr(Kt,{flexDirection:"column",children:[dr(Ve,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),l&&Me(Kt,{marginTop:1,children:dr(Ve,{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?Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"No plugins installed."})}):dr(Kt,{marginTop:1,flexDirection:"column",children:[dr(Kt,{children:[Me(Ve,{dimColor:!0,children:" "}),Me(Ve,{dimColor:!0,children:cr("Name",24)}),Me(Ve,{dimColor:!0,children:cr("Scope",8)}),Me(Ve,{dimColor:!0,children:cr("User",6)}),Me(Ve,{dimColor:!0,children:"Path"})]}),t.map((g,b)=>{let y=b===u,w=g.id.split("@")[0];return dr(Kt,{children:[Me(Ve,{color:y?"cyan":void 0,bold:y,children:y?"> ":" "}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(w,24)}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(g.scope,8)}),Me(Ve,{color:g.globalEnabled?"green":"gray",children:cr(g.globalEnabled?"on":"off",6)}),Me(Ve,{dimColor:!0,children:g.installPath})]},g.id)})]}),Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"r:refresh"})})]})}function cr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as $o,Text as No,useInput as Ea}from"ink";import{useState as Aa}from"react";import{jsx as Ht,jsxs as is}from"react/jsx-runtime";var Pa=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function as({onBack:e}){let[t,r]=Aa("tasks");return Ea((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}}),is($o,{flexDirection:"column",children:[Ht(No,{bold:!0,children:"Work Surface"}),Ht(No,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Ht($o,{gap:3,marginBottom:1,marginTop:1,children:Pa.map(a=>{let o=t===a.id;return Ht($o,{children:is(No,{color:o?"cyan":"gray",bold:o,children:[o?"\u25CF":"\u25CB"," ",a.key,". ",a.label]})},a.id)})}),t==="tasks"&&Ht(to,{onBack:e}),t==="automations"&&Ht(so,{onBack:e}),t==="goals"&&Ht(oo,{onBack:e})]})}import{Box as me,Text as oe,useInput as Ra}from"ink";import{useEffect as Da,useState as Ar}from"react";import{jsx as j,jsxs as De}from"react/jsx-runtime";var ls={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function cs({onBack:e}){let[t,r]=Ar([]),[a,o]=Ar(!0),[u,d]=Ar(0),[l,i]=Ar(null),[n,p]=Ar("");Da(()=>{g()},[]);async function g(){try{let w=await v("/channels");r(w.channels)}catch{}o(!1)}async function b(w){if(t.find(c=>c.id===w)?.platform==="wechat")try{p("Starting WeChat QR login...");let c=await v(`/channels/${w}/wechat/qr-start`,{method:"POST"});if(c.qrcodeUrl){p(`Scan QR: ${c.qrcodeUrl}
10
+ Waiting for scan...`);let I=await v(`/channels/${w}/wechat/qr-wait`,{method:"POST",body:{sessionKey:c.sessionKey,timeoutMs:12e4}});p(I.message)}else p(c.message);g()}catch{p("WeChat connect failed")}else try{await v(`/channels/${w}/connect`,{method:"POST"}),p("Connecting..."),g()}catch{p("Connect failed")}}async function y(w){try{await v(`/channels/${w}/disconnect`,{method:"POST"}),p("Disconnected"),g()}catch{p("Disconnect failed")}}return Ra((w,s)=>{if(l){if(s.escape||w==="q"){i(null);return}if(w==="c"){b(l.id);return}if(w==="d"){y(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?j(me,{flexDirection:"column",children:j(oe,{dimColor:!0,children:"Loading channels..."})}):l?De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[De(oe,{bold:!0,children:["Channel: ",l.name]}),j(oe,{dimColor:!0,children:" (Esc to go back)"})]}),De(me,{flexDirection:"column",gap:0,children:[De(oe,{children:["ID: ",l.id]}),De(oe,{children:["Platform: ",l.platform]}),De(oe,{children:["Status: ",j(oe,{color:ls[l.status]??"white",children:l.status})]}),De(oe,{children:["Enabled: ",l.enabled?"yes":"no"]}),De(oe,{children:["Messages: ",l.messageCount]}),De(oe,{children:["Config: ",JSON.stringify(l.config)]})]}),j(me,{marginTop:1,children:j(oe,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),n&&j(oe,{color:"yellow",children:n})]}):De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[j(oe,{bold:!0,children:"Channels"}),De(oe,{dimColor:!0,children:[" (",t.length," total) "]}),j(oe,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?j(oe,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):De(me,{flexDirection:"column",children:[De(me,{children:[j(me,{width:3,children:j(oe,{dimColor:!0,children:" "})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"ID"})}),j(me,{width:16,children:j(oe,{bold:!0,dimColor:!0,children:"Name"})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"Platform"})}),j(me,{width:14,children:j(oe,{bold:!0,dimColor:!0,children:"Status"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Enabled"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((w,s)=>De(me,{children:[j(me,{width:3,children:j(oe,{children:s===u?">":" "})}),j(me,{width:12,children:j(oe,{inverse:s===u,children:w.id.slice(0,8)})}),j(me,{width:16,children:j(oe,{children:w.name})}),j(me,{width:12,children:j(oe,{children:w.platform})}),j(me,{width:14,children:De(oe,{color:ls[w.status]??"white",children:[w.status==="connected"?"\u25CF":w.status==="error"?"\u2717":"\u25CB"," ",w.status]})}),j(me,{width:10,children:j(oe,{color:w.enabled?"green":"gray",children:w.enabled?"yes":"no"})}),j(me,{width:10,children:j(oe,{children:w.messageCount})})]},w.id))]})]})}import{Box as ur,Text as mt,useInput as Na}from"ink";import{useEffect as La,useState as Pr,useCallback as _a}from"react";import{Box as R,Text as x,useInput as Ma}from"ink";import ut from"ink-text-input";import{useEffect as ds,useState as X,useCallback as vt}from"react";To();import{Fragment as ao,jsx as h,jsxs as k}from"react/jsx-runtime";var $a=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function us({roleId:e,onBack:t}){let[r,a]=X(null),[o,u]=X([]),[d,l]=X(!0),[i,n]=X("view"),[p,g]=X(""),[b,y]=X(0),[w,s]=X(""),[c,I]=X([]),[C,E]=X(0),[G,Y]=X(new Set),[N,O]=X("inline"),[V,B]=X(""),[z,se]=X(""),[ne,$e]=X(""),[ge,D]=X([]),[ie,_]=X(new Set),[ae,Ce]=X(0),[L,K]=X("default"),[ee,pe]=X(""),[St,gt]=X(""),[et,Ut]=X("mode"),[Jt,S]=X([]),[A,$]=X(null),[le,Ue]=X([]),[Ne,M]=X([]),[Zt,wt]=X(""),[_t,$r]=X(0),[Nr,qo]=X(""),[Vo,Uo]=X(""),[Wo,Go]=X(""),[Lr,po]=X(0),[Tr,jo]=X([]),[_r,xo]=X(0),[Fr,Or]=X(!1),[er,Bs]=X(""),{message:F,setMessage:q}=ot(),ce=vt(()=>{l(!0),v(`/roles/${e}`).then(({role:m,projectPlugins:T,workspacePath:f})=>{a(m),u(T??[]),Bs(f??""),g(m.cagPrompt??""),Y(new Set(m.allowedTools??[])),O(m.executionMode??"inline"),B(m.model??""),se(m.effortTier??""),$e(m.maxBudgetUsd!=null?String(m.maxBudgetUsd):""),l(!1)}).catch(()=>l(!1))},[e]);ds(()=>{ce(),v("/config").then(m=>{let T=m.config["defaults.deniedReadPaths"]?.value;Array.isArray(T)&&S(T),$(m.sandbox),Ue(m.osCapabilities?.registry??[])}).catch(()=>{})},[ce]),ds(()=>{O(r?.executionMode??"inline"),B(r?.model??""),se(r?.effortTier??""),$e(r?.maxBudgetUsd!=null?String(r?.maxBudgetUsd):""),K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),M(r?.osCapabilities??[]);let m=r?.osCapabilities?.find(T=>T.id==="automation")?.targets??[];wt(m.join(", "))},[r?.id,r?.executionMode,r?.model,r?.effortTier,r?.maxBudgetUsd,r?.permissionMode,r?.allowedBashPatterns,r?.deniedBashPatterns,r?.osCapabilities]);let Is=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{cagPrompt:p}}),q("CAG prompt saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,p,ce,q]),Es=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{additionalDirectories:it}}),q("Directories saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,ce,q]),As=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{allowedTools:Array.from(G)}}),q("Tool permissions saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,G,ce,q]),Ps=vt(async()=>{if(!r)return;let m={executionMode:N};V!==void 0&&(m.model=V),m.effortTier=z===""?null:z;let T=parseFloat(ne);isNaN(T)||(m.maxBudgetUsd=T);try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Execution config saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,N,V,z,ne,ce,q]),Rs=vt(async()=>{if(!r)return;let m={permissionMode:L},T=ee.split(",").map(P=>P.trim()).filter(Boolean),f=St.split(",").map(P=>P.trim()).filter(Boolean);m.allowedBashPatterns=T.length>0?T:[],m.deniedBashPatterns=f.length>0?f:[];try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Permission config saved","success"),n("view"),ce()}catch(P){q(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[r,L,ee,St,ce,q]),Ko=vt(m=>{let T=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)))),T.set(f.id,P)}return Array.from(T.values()).sort((f,P)=>f.id.localeCompare(P.id))},[]),Ds=vt(async()=>{if(!r)return;let m=Ko(Ne),T=m.find(f=>f.id==="automation")?.targets??[];if(m.some(f=>f.id==="automation")&&(T.length===0||T.some(f=>!$a.test(f)))){q("Automation requires valid bundle id targets","error");return}try{await v(`/roles/${r.id}`,{method:"PATCH",body:{osCapabilities:m}}),q("OS capabilities saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,Ne,Ko,ce,q]),Ms=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/install/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Bound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Bind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),$s=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/uninstall/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Unbound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Unbind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),it=r?.additionalDirectories??[];if(Ma((m,T)=>{if(T.escape){n("view");return}if(m==="r"){ce();return}switch(i){case"view":{if(m==="c"){n("edit-cag");return}if(m==="d"){n("edit-dirs"),y(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"){v("/channels?enabled=true").then(({channels:f})=>{D(f.map(P=>({name:P.name,id:P.id}))),_(new Set(r?.allowedChannels??[])),Ce(0),n("edit-channels")}).catch(()=>q("Failed to load channels","error"));return}if(m==="p"){K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),Ut("mode"),n("edit-permissions");return}if(m==="v"){$r(0),n("edit-env");return}if(m==="b"){po(0),n("edit-plugins");return}if(m==="i"){if(!r)return;let f=!r.inheritUserSettings;v(`/roles/${r.id}`,{method:"PATCH",body:{inheritUserSettings:f}}).then(()=>{q(`Inherit user settings: ${f?"ON":"OFF"}`,"success"),ce()}).catch(()=>q("Failed to toggle","error"));return}if(m==="R"&&r?.presetId){v(`/presets/role/${r.presetId}/restore`,{method:"POST"}).then(()=>{q("Preset restored","success"),ce()}).catch(f=>q(`Restore failed: ${f instanceof Error?f.message:String(f)}`,"error"));return}break}case"edit-cag":{if(T.ctrl&&m==="s"){Is();return}break}case"edit-dirs":{if(m==="s"){Es();return}if(m==="a"){n("edit-dirs-add");return}if(m==="m"&&it.length>0){let f=it[b];if(f){a(U=>U&&{...U,additionalDirectories:U.additionalDirectories?.map((he,kt)=>kt===b?{...typeof he=="string"?{path:he}:he,mode:he.mode==="ro"?"rw":"ro"}:he)});let P=f.mode==="ro"?"rw":"ro";q(`Mode set to ${P.toUpperCase()}`,"success")}return}if(m==="x"&&it.length>0){a(f=>f&&{...f,additionalDirectories:it.filter((P,U)=>U!==b)}),y(f=>Math.max(0,Math.min(f,it.length-2)));return}if(T.upArrow){y(f=>Math.max(0,f-1));return}if(T.downArrow){y(f=>Math.min(it.length-1,f+1));return}break}case"edit-dirs-add":{if(T.escape){n("edit-dirs"),s(""),I([]);return}if(T.return&&c.length>0){let f=c[C];f&&(s(f.endsWith("/")?f:f+"/"),I([]));return}if(T.return){let f=w.trim();f&&f.startsWith("/")?(a(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:f,mode:"rw"}]}),s(""),I([]),n("edit-dirs")):q("Path must be absolute (must start with /)","error");return}if(T.tab){let f=w.trim();if(!f||!f.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(f)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),I([])):P.length>1&&(I(P),E(0))}).catch(()=>{I([])});return}if(T.upArrow&&c.length>0){E(f=>Math.max(0,f-1));return}if(T.downArrow&&c.length>0){E(f=>Math.min(c.length-1,f+1));return}break}case"edit-tools":{if(m==="s"){As();return}let f=parseInt(m,10)-1;if(!isNaN(f)&&f>=0&&f<qr.length){let P=qr[f];Y(U=>{let he=new Set(U);return he.has(P)?he.delete(P):he.add(P),he});return}break}case"edit-oscaps":{if(m==="s"){Ds();return}if(m==="a"&&Ne.some(U=>U.id==="automation")){let U=Ne.find(he=>he.id==="automation")?.targets??[];wt(U.join(", ")),n("edit-oscaps-targets");return}let f=le.filter(U=>U.editable),P=parseInt(m,10)-1;if(!isNaN(P)&&P>=0&&P<f.length){let U=f[P];M(he=>he.some(hr=>hr.id===U.id)?he.filter(hr=>hr.id!==U.id):[...he,{id:U.id,targets:U.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(T.return){let f=Zt.split(",").map(P=>P.trim()).filter(Boolean);M(P=>P.map(U=>U.id==="automation"?{...U,targets:f}:U)),n("edit-oscaps");return}break}case"edit-exec":{if(m==="s"){Ps();return}if(T.tab){O(f=>f==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(m==="s"){Rs();return}if(T.tab){Ut(f=>f==="mode"?"allowed":f==="allowed"?"denied":"mode");return}if(et==="mode"&&(T.upArrow||T.downArrow)){let f=["default","acceptEdits","dontAsk","bypassPermissions"],P=f.indexOf(L);T.upArrow&&K(f[Math.max(0,P-1)]),T.downArrow&&K(f[Math.min(f.length-1,P+1)]);return}break}case"edit-channels":{if(m==="s"){if(!r)return;let f=ie.size>0?Array.from(ie):[];v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:f}}).then(()=>{q("Channels saved","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m==="u"){if(!r)return;v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{q("Channels: unrestricted","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m===" "){let f=ge[ae];f&&_(P=>{let U=new Set(P);return U.has(f.name)?U.delete(f.name):U.add(f.name),U});return}if(T.upArrow){Ce(f=>Math.max(0,f-1));return}if(T.downArrow){Ce(f=>Math.min(ge.length-1,f+1));return}break}case"edit-env":{let f=Object.keys(r?.envVars??{});if(m==="a"){qo(""),n("edit-env-add-key");return}if(m==="d"&&f.length>0){let P=f[_t],U={...r?.envVars??{}};delete U[P],v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Deleted","success"),ce()}).catch(()=>q("Delete failed","error")),_t>=f.length-1&&_t>0&&$r(he=>he-1);return}if(T.return&&f.length>0){Go((r?.envVars??{})[f[_t]]??""),n("edit-env-edit-value");return}T.upArrow&&_t>0&&$r(P=>P-1),T.downArrow&&_t<f.length-1&&$r(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break;case"edit-plugins":{if(Fr)return;if(m==="a"){v("/plugins").then(({plugins:f})=>{let P=new Set(o.map(U=>U.id));jo(f.filter(U=>!P.has(U.id))),xo(0),n("edit-plugins-add")}).catch(()=>q("Failed to load plugins","error"));return}if(m==="x"&&o.length>0){let f=o[Lr];f&&$s(f.id);return}if(T.upArrow){po(f=>Math.max(0,f-1));return}if(T.downArrow){po(f=>Math.min(o.length-1,f+1));return}break}case"edit-plugins-add":{if(Fr)return;if(T.escape){n("edit-plugins"),jo([]);return}if(T.return&&Tr.length>0){let f=Tr[_r];f&&Ms(f.id);return}if(T.upArrow){xo(f=>Math.max(0,f-1));return}if(T.downArrow){xo(f=>Math.min(Tr.length-1,f+1));return}break}}}),d)return h(x,{dimColor:!0,children:"Loading role..."});if(!r)return h(x,{dimColor:!0,children:"Role not found."});if(i==="edit-plugins")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Plugins (\u2191\u2193 navigate, x:unbind a:add Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),o.length===0?h(x,{dimColor:!0,children:"No plugins bound. Press a to add."}):o.map((m,T)=>k(R,{children:[k(x,{color:T===Lr?"cyan":void 0,bold:T===Lr,children:[T===Lr?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-plugins-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Plugin (\u2191\u2193 navigate, Enter:bind Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),Tr.length===0?h(x,{dimColor:!0,children:"No available plugins."}):Tr.map((m,T)=>k(R,{children:[k(x,{color:T===_r?"cyan":void 0,bold:T===_r,children:[T===_r?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-cag")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(ut,{value:p,onChange:g,placeholder:"Character And Guidance prompt..."}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(ut,{value:w,onChange:m=>{s(m),I([])},placeholder:"/absolute/path/to/directory"}),c.length>0&&k(R,{flexDirection:"column",marginTop:1,children:[c.map((m,T)=>k(x,{color:T===C?"cyan":void 0,dimColor:T!==C,children:[T===C?"> ":" ",m,"/"]},m)),h(x,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),it.length===0?h(x,{dimColor:!0,children:"No directories. Press a to add one."}):it.map((m,T)=>{let f=typeof m=="string"?{path:m,mode:"rw"}:m,P=f.mode!=="ro";return k(R,{children:[h(x,{color:T===b?"cyan":void 0,bold:T===b,children:T===b?"> ":" "}),k(x,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),h(x,{color:T===b?"cyan":void 0,children:f.path})]},f.path)})]});if(i==="edit-tools")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),qr.map((m,T)=>{let f=G.has(m);return k(R,{children:[k(x,{dimColor:!0,children:[T+1,". "]}),h(x,{color:f?"green":"red",children:f?"[ON] ":"[OFF] "}),h(x,{children:m})]},m)})]});if(i==="edit-oscaps"){let m=le.filter(T=>T.editable);return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),A&&k(x,{dimColor:!0,children:["Platform: ",A.platform," ",A.available?"(sandbox active)":"(sandbox unavailable)"]}),le.map(T=>{let f=m.findIndex(kt=>kt.id===T.id),P=Ne.some(kt=>kt.id===T.id),U=f>=0?`${f+1}.`:" -",he=T.id==="automation"?(()=>{let kt=Ne.find(hr=>hr.id===T.id)?.targets??[];return kt.length>0?` targets: ${kt.join(", ")}`:" targets: (none)"})():"";return k(R,{flexDirection:"column",marginBottom:1,children:[k(x,{color:P?"green":T.editable?"red":"gray",children:[U," ",P?"[ON]":"[OFF]"," ",T.label," [",T.availability,"]"]}),k(x,{dimColor:!0,children:[" ",T.description,he]}),T.effectiveDisabledReason&&!T.editable&&k(x,{dimColor:!0,children:[" ",T.effectiveDisabledReason]})]},T.id)}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]})}if(i==="edit-oscaps-targets")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),h(ut,{value:Zt,onChange:wt,placeholder:"com.apple.mail, com.apple.systemevents"}),h(x,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-exec")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,children:" Mode: "}),h(x,{color:"cyan",children:N}),h(x,{dimColor:!0,children:" (Tab to toggle)"})]}),k(R,{children:[h(x,{bold:!0,children:" Model: "}),h(ut,{value:V,onChange:B,placeholder:"sonnet, opus, haiku, or blank"})]}),k(R,{children:[h(x,{bold:!0,children:" Effort Tier: "}),h(ut,{value:z,onChange:se,placeholder:"low, medium, high, or blank to inherit"})]}),k(R,{children:[h(x,{bold:!0,children:" Max Budget (USD): "}),h(ut,{value:ne,onChange:$e,placeholder:"0 = unlimited"})]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-permissions")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,color:et==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(T=>k(x,{color:T===L?"green":"gray",children:[T===L?`[${T}]`:` ${T} `," "]},T))]}),k(R,{children:[h(x,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?h(ut,{value:ee,onChange:pe,placeholder:"git add *, pnpm test*"}):h(x,{children:ee||"(none)"})]}),k(R,{children:[h(x,{bold:!0,color:et==="denied"?"cyan":void 0,children:" Denied Bash: "}),et==="denied"?h(ut,{value:St,onChange:gt,placeholder:"rm -rf *, ssh *"}):h(x,{children:St||"(none)"})]}),h(x,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-channels")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),ge.length===0?h(x,{dimColor:!0,children:"No channels available"}):ge.map((m,T)=>k(R,{children:[k(x,{children:[T===ae?">":" "," "]}),k(x,{color:ie.has(m.name)?"green":"gray",children:["[",ie.has(m.name)?"x":" ","] ",m.name]})]},m.id)),k(x,{dimColor:!0,children:["Selected: ",ie.size>0?Array.from(ie).join(", "):"none (= block all)"]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i.startsWith("edit-env")){let m=Object.keys(r.envVars??{});return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Environment Variables (",m.length,")"]}),m.length===0&&i==="edit-env"&&h(x,{dimColor:!0,children:" No env vars. Press a to add."}),m.map((T,f)=>{let P=f===_t;return i==="edit-env-edit-value"&&P?k(R,{children:[k(x,{color:"cyan",children:["> ",T," = "]}),h(ut,{value:Wo,onChange:Go,onSubmit:()=>{let U={...r.envVars??{},[T]:Wo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Saved","success"),ce(),n("edit-env")}).catch(()=>q("Save failed","error"))}})]},T):k(x,{color:P&&i==="edit-env"?"cyan":"white",children:[P&&i==="edit-env"?"> ":" ",T," = ",(r.envVars??{})[T]]},T)}),i==="edit-env-add-key"&&k(R,{children:[h(x,{color:"green",children:" New key: "}),h(ut,{value:Nr,onChange:qo,onSubmit:()=>{Nr.trim()&&(Uo(""),n("edit-env-add-value"))}})]}),i==="edit-env-add-value"&&k(R,{children:[k(x,{color:"green",children:[" ",Nr," = "]}),h(ut,{value:Vo,onChange:Uo,onSubmit:()=>{let T={...r.envVars??{},[Nr.trim()]:Vo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:T}}).then(()=>{q("Added","success"),ce(),n("edit-env")}).catch(()=>q("Add failed","error"))}})]}),h(x,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),F&&h(x,{color:F.type==="error"?"red":"green",children:F.text})]})}return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Role: ",r.name]}),k(R,{children:[h(x,{dimColor:!0,children:"ID: "}),h(x,{children:r.id})]}),k(R,{children:[h(x,{dimColor:!0,children:"Status: "}),h(x,{color:r.status==="active"?"green":r.status==="probation"?"yellow":"red",children:r.status})]}),r.performanceScore!=null&&k(R,{children:[h(x,{dimColor:!0,children:"Score: "}),k(x,{children:[(r.performanceScore*100).toFixed(0),"%"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Created: "}),h(x,{children:new Date(r.createdAt).toLocaleString()})]}),k(R,{children:[h(x,{dimColor:!0,children:"Execution: "}),k(x,{children:[r.executionMode??"inline"," / tier:",r.effortTier??"\u2014"," / model:",r.model??"inherit"," / ",r.maxBudgetUsd!=null?`$${r.maxBudgetUsd}`:"no limit"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"OS Capabilities: "}),h(x,{children:(r.osCapabilities?.length??0)>0?r.osCapabilities.map(m=>m.id==="automation"&&m.targets?.length?`automation(${m.targets.join(",")})`:m.id).join(", "):"None"})]}),A&&k(R,{children:[h(x,{dimColor:!0,children:"Sandbox Platform: "}),k(x,{children:[A.platform," ",A.available?"(active)":"(unavailable)"]})]}),it.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Additional Directories:"}),it.map(m=>k(x,{dimColor:!0,children:[" ",m.path]},m.path))]}),k(R,{children:[h(x,{dimColor:!0,children:"Permission: "}),h(x,{children:r.permissionMode??"default"})]}),(r.allowedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Allow: "}),h(x,{children:r.allowedBashPatterns.join(", ")})]}),(r.deniedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Deny: "}),h(x,{children:r.deniedBashPatterns.join(", ")})]}),Jt.length>0&&k(R,{flexDirection:"column",children:[h(x,{dimColor:!0,children:"Denied Read Paths (global):"}),Jt.map(m=>k(x,{dimColor:!0,children:[" ",m]},m)),k(x,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Channels: "}),h(x,{children:r.allowedChannels===void 0?"Unrestricted":r.allowedChannels.length===0?"Blocked":r.allowedChannels.join(", ")})]}),k(R,{children:[h(x,{dimColor:!0,children:"Inherit User Settings: "}),h(x,{color:r.inheritUserSettings?"green":"gray",children:r.inheritUserSettings?"Yes":"No"})]}),r.learnedRules.stylePreferences.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Style Preferences:"}),r.learnedRules.stylePreferences.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.avoidedActions.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Avoided Actions:"}),r.learnedRules.avoidedActions.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.pinnedParameters.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Pinned Parameters:"}),r.learnedRules.pinnedParameters.map(m=>{let T=Object.entries(m.params).map(([P,U])=>`${P}=${JSON.stringify(U)}`).join(", "),f=m.condition?` [when: ${m.condition}]`:"";return k(x,{dimColor:!0,children:[" - ",m.tool," \u2192 ",T,f]},`${m.tool}-${m.pinnedAt}`)})]}),k(R,{children:[h(x,{dimColor:!0,children:"Plugins: "}),o.length===0?h(x,{dimColor:!0,children:"None"}):o.map(m=>k(x,{children:[m.name," "]},m.id))]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),h(R,{marginTop:1,children:k(x,{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 Qe,jsxs as Rr}from"react/jsx-runtime";function ms({onBack:e}){let[t,r]=Pr([]),[a,o]=Pr(!0),[u,d]=Pr(0),[l,i]=Pr("list"),[n,p]=Pr(null),{message:g,setMessage:b,clearMessage:y}=ot(),w=_a(()=>{o(!0),v("/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 La(()=>{w()},[w]),Na((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(I=>Math.max(0,I-1));return}if(c.downArrow){d(I=>Math.min(t.length-1,I+1));return}if(s==="r"&&(w(),y()),s===`
11
+ `||s==="o"||s==="e"){t.length>0&&(p(t[u].id),i("detail"));return}}),a?Qe(mt,{dimColor:!0,children:"Loading roles..."}):l==="detail"&&n?Qe(us,{roleId:n,onBack:()=>i("list")}):Rr(ur,{flexDirection:"column",children:[Rr(mt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),g&&Qe(ur,{marginTop:1,children:Rr(mt,{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?Qe(ur,{marginTop:1,children:Qe(mt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Qe(ur,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014",E=s.contractComplianceEma!=null?`[\u5951\u7EA6 ${s.contractComplianceEma.toFixed(2)}]`:"[\u5951\u7EA6 \u2014]";return Rr(ur,{children:[Qe(mt,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Qe(mt,{color:I?"cyan":void 0,bold:I,children:Lo(s.name,24)}),s.presetId&&Rr(mt,{dimColor:!0,children:["[",s.presetId,"]"]}),Qe(mt,{color:Fa(s.status),children:Lo(s.status,12)}),Qe(mt,{dimColor:!0,children:Lo(C,8)}),Qe(mt,{dimColor:!0,children:E})]},s.id)})}),Qe(ur,{marginTop:1,children:Qe(mt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function Fa(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Lo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Oa,Text as _o}from"ink";import qa from"react";import{jsx as lo,jsxs as Ua}from"react/jsx-runtime";var He={key:"Esc",label:"back"},Va={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},He],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},He],config:[He],evolution:[He],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},He],strategies:[He],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"},He],webhooks:[He],memories:[He],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},He],roles:[He],settings:[He],channels:[He]};function fs(){let{state:e}=tt(),t=Va[e.view]??[He];return lo(Oa,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((r,a)=>Ua(qa.Fragment,{children:[a>0&&lo(_o,{dimColor:!0,children:" "}),lo(_o,{color:"cyan",children:r.key}),lo(_o,{dimColor:!0,children:` ${r.label}`})]},`${r.key}-${r.label}`))})}import{Box as mr,Text as nt,useInput as Wa}from"ink";import{useEffect as Ga,useState as co,useCallback as ja}from"react";import{jsx as $t,jsxs as Mt}from"react/jsx-runtime";function gs({onBack:e}){let[t,r]=co([]),[a,o]=co(!0),[u,d]=co(0),[l,i]=co("all"),{message:n,setMessage:p}=ot(),g=ja(()=>{o(!0);let c=l!=="all"?`?status=${l}`:"";v(`/feature-requests${c}`).then(({featureRequests:I})=>{r(I),d(0),o(!1)}).catch(()=>o(!1))},[l]);Ga(()=>{g()},[g]);let b=async(c,I)=>{try{await v(`/feature-requests/${c}/status`,{method:"PATCH",body:{status:I}}),p(`Marked as ${I}`,"success"),await g()}catch(C){p(`Failed: ${C instanceof Error?C.message:String(C)}`,"error")}},y=t;Wa((c,I)=>{if(I.escape||c==="q"){e();return}if(I.upArrow){d(E=>Math.max(0,E-1));return}if(I.downArrow){d(E=>Math.min(y.length-1,E+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"&&y.length>0){let E=y[u];if(E&&E.status==="new"){b(E.id,"reviewed");return}}if(c==="d"&&y.length>0){let E=y[u];if(E){b(E.id,"dismissed");return}}if(c==="c"&&y.length>0){let E=y[u];if(E){b(E.id,"converted");return}}});let w=c=>c==="new"?"cyan":c==="reviewed"?"green":c==="dismissed"?"gray":c==="converted"?"yellow":"white",s=c=>{let I=Date.now()-c;if(Math.floor(I/6e4)<1)return"now";let E=Math.floor(I/36e5);return E<24?`${E}h ago`:`${Math.floor(E/24)}d ago`};return Mt(mr,{flexDirection:"column",children:[Mt(nt,{bold:!0,children:["Feature Requests (",y.length,") (Esc:back q:quit r:refresh)"]}),n&&$t(mr,{marginTop:1,children:Mt(nt,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),$t(nt,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),$t(nt,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),a?$t(nt,{dimColor:!0,children:"Loading..."}):y.length===0?$t(nt,{dimColor:!0,children:"No feature requests found."}):$t(mr,{marginTop:1,flexDirection:"column",children:y.map((c,I)=>{let C=I===u,E=c.content.length>80?c.content.slice(0,80)+"...":c.content;return Mt(mr,{flexDirection:"column",children:[Mt(mr,{children:[$t(nt,{color:C?"cyan":void 0,bold:C,children:C?"> ":" "}),Mt(nt,{color:w(c.status),children:["[",c.status,"]"]}),Mt(nt,{dimColor:!0,children:[" ",s(c.extractedAt)]}),c.tags&&c.tags.length>0&&Mt(nt,{dimColor:!0,children:[" ",c.tags.slice(0,3).join(", ")]})]}),Mt(mr,{paddingLeft:4,flexDirection:"column",children:[c.summary&&$t(nt,{color:C?"cyan":"white",children:c.summary}),$t(nt,{dimColor:!0,children:E})]})]},c.id)})})]})}import{Box as fr,Text as Je,useInput as Ka}from"ink";import{useEffect as Ha,useState as uo,useCallback as za}from"react";import{jsx as Nt,jsxs as Ct}from"react/jsx-runtime";function ps({onBack:e}){let[t,r]=uo([]),[a,o]=uo(!0),[u,d]=uo(0),[l,i]=uo("all"),{message:n,setMessage:p}=ot(),g=za(()=>{o(!0);let s=l!=="all"?`?status=${l}`:"";v(`/mistake-patterns${s}`).then(({mistakePatterns:c})=>{r(c),d(0),o(!1)}).catch(()=>o(!1))},[l]);Ha(()=>{g()},[g]);let b=async(s,c)=>{try{await v(`/mistake-patterns/${s}`,{method:"PATCH",body:{status:c}}),p(`Marked as ${c}`,"success"),await g()}catch(I){p(`Failed: ${I instanceof Error?I.message:String(I)}`,"error")}};Ka((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 I={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(I[s]){i(I[s]);return}if(s==="a"&&t.length>0){let C=t[u];if(C&&C.status!=="acknowledged"){b(C.id,"acknowledged");return}}if(s==="d"&&t.length>0){let C=t[u];if(C&&C.status!=="dismissed"){b(C.id,"dismissed");return}}if(s==="n"&&t.length>0){let C=t[u];if(C&&C.status!=="new"){b(C.id,"new");return}}});let y=s=>s==="new"?"cyan":s==="acknowledged"?"green":s==="dismissed"?"gray":"white",w=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 Ct(fr,{flexDirection:"column",children:[Ct(Je,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),n&&Nt(fr,{marginTop:1,children:Ct(Je,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),Nt(Je,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),Nt(Je,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),a?Nt(Je,{dimColor:!0,children:"Loading..."}):t.length===0?Nt(Je,{dimColor:!0,children:"No mistake patterns found."}):Nt(fr,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.dimensionValue.length>80?s.dimensionValue.slice(0,80)+"...":s.dimensionValue;return Ct(fr,{flexDirection:"column",children:[Ct(fr,{children:[Nt(Je,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Ct(Je,{color:y(s.status),children:["[",s.status,"]"]}),Ct(Je,{dimColor:!0,children:[" ",w(s.lastSeen)]}),Ct(Je,{dimColor:!0,children:[" [",s.dimensionType,"]"]}),Ct(Je,{dimColor:!0,children:[" ",s.roleIds.length," role(s)"]}),Ct(Je,{dimColor:!0,children:[" x",s.count]})]}),Nt(fr,{paddingLeft:4,flexDirection:"column",children:Nt(Je,{color:I?"cyan":"white",children:C})})]},s.id)})})]})}import{Box as Lt,Text as ke,useInput as Cs}from"ink";import{useEffect as al,useState as ft,useCallback as Ss,useRef as ws}from"react";import{readFileSync as Xa,existsSync as Ya}from"fs";import{join as Qa}from"path";import{homedir as Ja}from"os";function Za(){if(process.env.ADAM_API_KEY)return process.env.ADAM_API_KEY;let e=Qa(Ja(),".adam","adam.key");if(Ya(e))return Xa(e,"utf8").trim();throw new Error("ADAM_API_KEY env or ~/.adam/adam.key required")}function el(){return Number(process.env.ADAM_PORT??7100)}async function mo(e,t={}){let r={"x-api-key":Za(),...t.headers??{}};t.body&&(r["Content-Type"]??="application/json");let a=await fetch(`http://localhost:${el()}${e}`,{...t,headers:r});if(!a.ok)throw new Error(`${a.status}: ${await a.text()}`);if(a.status!==204)return a.json()}function xs(e={}){let t=new URLSearchParams(Object.entries(e).map(([r,a])=>[r,String(a)])).toString();return mo(`/artifacts${t?"?"+t:""}`)}function Ts(e){return mo(`/artifacts/${encodeURIComponent(e)}`)}function Fo(e,t=!1){return mo(`/artifacts/${encodeURIComponent(e)}${t?"?confirm=true":""}`,{method:"DELETE"})}function hs(e,t){return mo(`/artifacts/${encodeURIComponent(e)}/redeliver`,{method:"POST",body:JSON.stringify(t)})}import{spawn as tl}from"child_process";async function ys(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=tl(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 gr,Text as qt,useInput as rl}from"ink";import{jsx as ve,jsxs as zt}from"react/jsx-runtime";function ol(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}function nl(e){return new Date(e).toLocaleString()}function Ze({label:e,value:t}){return zt(gr,{children:[ve(qt,{dimColor:!0,children:e.padEnd(20)}),ve(qt,{color:"cyan",children:t})]})}function bs({artifact:e,deliveryLog:t,onBack:r}){return rl((a,o)=>{o.escape&&r()}),zt(gr,{flexDirection:"column",children:[ve(qt,{bold:!0,children:"Artifact Detail (Esc to go back)"}),zt(gr,{flexDirection:"column",marginTop:1,children:[ve(Ze,{label:"ID",value:e.id}),ve(Ze,{label:"Source",value:e.sourceKind}),ve(Ze,{label:"Role",value:e.producedByRole??e.roleId??"\u2014"}),ve(Ze,{label:"Mime",value:e.mime??"\u2014"}),ve(Ze,{label:"Kind",value:e.kind}),ve(Ze,{label:"Size",value:ol(e.sizeBytes)}),ve(Ze,{label:"Created",value:nl(e.createdAt)}),ve(Ze,{label:"Key",value:e.key??"\u2014"}),ve(Ze,{label:"Blob path",value:e.blobPath??"\u2014"}),e.executionId&&ve(Ze,{label:"Execution ID",value:e.executionId}),e.taskId&&ve(Ze,{label:"Task ID",value:e.taskId}),e.chatSessionId&&ve(Ze,{label:"Chat Session",value:e.chatSessionId}),e.originalFilename&&ve(Ze,{label:"Filename",value:e.originalFilename})]}),t.length>0&&zt(gr,{flexDirection:"column",marginTop:1,children:[zt(qt,{bold:!0,dimColor:!0,children:["Delivery Log (",t.length,")"]}),t.map((a,o)=>zt(gr,{children:[ve(qt,{dimColor:!0,children:" "}),ve(qt,{color:a.status==="delivered"?"green":a.status==="failed"?"red":"yellow",children:a.status}),zt(qt,{dimColor:!0,children:[" \u2192 ",a.target?.channelId??"\u2014",a.createdAt?` (${new Date(a.createdAt).toLocaleTimeString()})`:""]})]},o))]}),t.length===0&&ve(gr,{marginTop:1,children:ve(qt,{dimColor:!0,children:"No delivery log entries."})})]})}import{Box as fo,Text as Vt,useInput as sl}from"ink";import{useEffect as il,useState as Oo}from"react";import{jsx as Xt,jsxs as Dr}from"react/jsx-runtime";function vs({onSelect:e,onCancel:t,fetchChannels:r}){let[a,o]=Oo([]),[u,d]=Oo(!0),[l,i]=Oo(null);return il(()=>{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]),sl((n,p)=>{if(p.escape){t();return}let g=parseInt(n,10);if(!isNaN(g)&&g>=1&&g<=a.length){let b=a[g-1];b&&e(b.id)}}),u?Xt(fo,{children:Xt(Vt,{dimColor:!0,children:"Loading channels..."})}):l?Dr(fo,{children:[Xt(Vt,{color:"red",children:l}),Xt(Vt,{dimColor:!0,children:" (Esc to cancel)"})]}):Dr(fo,{flexDirection:"column",children:[Xt(Vt,{bold:!0,children:"Select channel to redeliver (Esc to cancel):"}),a.length===0?Xt(Vt,{dimColor:!0,children:"No channels configured."}):a.map((n,p)=>Dr(fo,{children:[Dr(Vt,{children:["[",p+1,"] "]}),Xt(Vt,{color:"cyan",children:n.name}),Dr(Vt,{dimColor:!0,children:[" (",n.platform,")"]})]},n.id))]})}import{jsx as fe,jsxs as Yt}from"react/jsx-runtime";function ll(e){return e?e.replace(/[\x00-\x1F\x7F]/g,""):""}function st(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}function cl(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(0)}K`:`${(e/(1024*1024)).toFixed(1)}M`}function dl(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 ul(e){return e==="template_step"?"tmpl":e==="task_published"?"task":e==="chat_sent"?"chat":e.slice(0,6)}function ks({onBack:e,onSelect:t,onAction:r}){let{dispatch:a}=tt(),[o,u]=ft([]),[d,l]=ft(0),[i,n]=ft(!0),[p,g]=ft(null),[b,y]=ft(0),[w,s]=ft("list"),[c,I]=ft(null),[C,E]=ft([]),[G,Y]=ft(null),[N,O]=ft(null),[V,B]=ft(null),z=ws(null),se=ws(null);function ne(D){B(D),se.current&&clearTimeout(se.current),se.current=setTimeout(()=>B(null),2e3)}let $e=Ss(()=>{z.current&&z.current.abort(),z.current=new AbortController,n(!0),g(null),xs({limit:100}).then(D=>{u(D.artifacts),l(D.total),y(0),n(!1)}).catch(D=>{D.name!=="AbortError"&&(g(`Failed to load: ${D instanceof Error?D.message:String(D)}`),n(!1))})},[]);al(()=>($e(),()=>{z.current&&z.current.abort(),se.current&&clearTimeout(se.current)}),[$e]),Cs((D,ie)=>{if(G)if(D==="y"){let _=G;Y(null),Fo(_.id,!0).then(()=>{ne("Deleted"),$e()}).catch(ae=>ne(`Delete failed: ${ae instanceof Error?ae.message:String(ae)}`))}else(D==="n"||ie.escape)&&Y(null)}),Cs((D,ie)=>{if(G||N)return;if(ie.escape||D==="q"){e();return}if(ie.upArrow||D==="k"){y(ae=>Math.max(0,ae-1));return}if(ie.downArrow||D==="j"){y(ae=>Math.min(Math.max(0,o.length-1),ae+1));return}if(D==="\r"||D===`
12
+ `||D==="o"){if(o.length>0&&o[b]){let ae=o[b];t(ae),Ts(ae.id).then(Ce=>{I(Ce.artifact),E(Ce.deliveryLog),s("detail")}).catch(()=>{I(ae),E([]),s("detail")})}return}let _=o.length>0?o[b]:void 0;if(_){if(D==="d"){r("d",_),ho(_.mime)?Y(_):Fo(_.id,!1).then(()=>{ne("Deleted"),$e()}).catch(Ce=>ne(`Delete failed: ${Ce instanceof Error?Ce.message:String(Ce)}`));return}if(D==="r"){r("r",_),O(_);return}if(D==="c"){r("c",_);let ae=_.blobPath??"";ys(ae).then(Ce=>{ne(Ce?`Copied: ${ae.slice(-40)}`:"Clipboard unavailable")}).catch(()=>ne("Clipboard unavailable"));return}if(D==="t"){r("t",_);let ae=_.taskId??_.executionId;a({type:"SET_VIEW",view:"tasks",selectedTaskId:ae});return}}});let ge=Ss(()=>{let{getApiKey:D,getPort:ie}={getApiKey:()=>process.env.ADAM_API_KEY??"",getPort:()=>Number(process.env.ADAM_PORT??7100)};return fetch(`http://localhost:${ie()}/channels`,{headers:{"x-api-key":D()}}).then(_=>_.json())},[]);if(w==="detail"&&c)return fe(bs,{artifact:c,deliveryLog:C,onBack:()=>s("list")});if(N){let D=N;return fe(vs,{fetchChannels:ge,onSelect:ie=>{O(null),hs(D.id,{channelId:ie}).then(_=>ne(`Redeliver queued: ${_.status}`)).catch(_=>ne(`Redeliver failed: ${_ instanceof Error?_.message:String(_)}`))},onCancel:()=>O(null)})}return i?Yt(Lt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{dimColor:!0,children:"Loading..."})]}):p?Yt(Lt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{color:"red",children:p}),fe(ke,{dimColor:!0,children:"Press Esc to go back or r to retry"})]}):Yt(Lt,{flexDirection:"column",children:[Yt(ke,{bold:!0,children:["Artifacts (",d,") (Esc to go back)"]}),fe(Lt,{children:Yt(ke,{dimColor:!0,bold:!0,children:[" ",st("#",3),st("Source",12),st("Role",12),st("Mime",16),st("Size",8),st("Created",16),"Delivered"]})}),o.length===0?fe(Lt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"No artifacts found."})}):o.map((D,ie)=>{let _=ie===b,ae=D.mime??"unknown",Ce=D.producedByRole??D.roleId??"\u2014";return Yt(Lt,{children:[fe(ke,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),fe(ke,{color:_?"cyan":void 0,bold:_,children:st(String(ie+1),3)}),fe(ke,{color:_?"cyan":void 0,children:st(ul(D.sourceKind),12)}),fe(ke,{color:_?"cyan":void 0,children:st(ll(Ce).slice(0,11),12)}),fe(ke,{color:_?"cyan":void 0,children:st(ae.slice(0,15),16)}),fe(ke,{color:_?"cyan":void 0,children:st(cl(D.sizeBytes),8)}),fe(ke,{color:_?"cyan":void 0,children:st(dl(D.createdAt),16)}),fe(ke,{color:_?"cyan":void 0,children:"\u2014"})]},D.id)}),G&&fe(Lt,{marginTop:1,children:Yt(ke,{color:"red",children:["Delete this ",ho(G.mime)," file? (y/n)"]})}),V&&!G&&fe(Lt,{marginTop:1,children:fe(ke,{color:"green",children:V})}),fe(Lt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"j/k=navigate enter=detail d=delete r=redeliver c=copy t=task"})})]})}import{Fragment as hl,jsx as te,jsxs as xr}from"react/jsx-runtime";function pl(){let{state:e,dispatch:t}=tt(),{session:r,sendMessage:a,createNewSession:o,archiveCurrentSession:u}=on(),[d,l]=fl([]);go(()=>{t({type:"SET_SESSION",session:r})},[r,t]),en();let{latestMessage:i}=sn(r?.id??null),n=Qt(null),p=Qt(new Set),g=Qt(new Set),b=Qt(new Set),y=Qt(new Set),[,w]=gl(B=>B+1,0);go(()=>{if(!i||i.id===n.current)return;n.current=i.id;let B=!i.kind||i.kind==="result_delivery"||i.kind==="assistant_text";if(B&&i.taskId&&g.current.has(i.taskId)){p.current.add(i.taskId);return}B&&i.taskId&&p.current.add(i.taskId),l(z=>[...z,{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:I}=rn(e.activeTaskId),C=s[s.length-1],E=C?.type==="complete"&&!c,G=Qt(null),Y=Qt("");go(()=>{Y.current=s.filter(B=>B.type==="reasoning").map(B=>B.content).join("")},[s]),go(()=>{if(E&&e.activeTaskId!==G.current){if(G.current=e.activeTaskId,e.activeTaskId&&p.current.has(e.activeTaskId))return;let B=C?.content||Y.current;B&&(e.activeTaskId&&g.current.add(e.activeTaskId),l(z=>[...z,{role:"assistant",content:B,taskId:e.activeTaskId??void 0,kind:"assistant_text"}]))}},[E,C,e.activeTaskId]);let N=async B=>{let z=B.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(z)&&process.exit(0),B.startsWith("/")){let ne=B.slice(1),ge={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"}[ne];if(ge){t({type:"SET_VIEW",view:ge});return}if(ne==="new"){if(await u()){let ie=await o();l([]),I(),p.current.clear(),g.current.clear(),b.current.clear(),y.current.clear(),ie&&l([{role:"assistant",content:`Session archived. New session started: ${ie.id.slice(0,8)}`}])}return}if(ne==="session"){let D=r?`Session: ${r.id}
13
13
  Turns: ${r.messageCount}
14
- Last active: ${new Date(r.lastActiveAt).toLocaleString()}`:"No active session";l(ie=>[...ie,{role:"assistant",content:D}]);return}}if(l(ne=>[...ne,{role:"user",content:B}]),I(),!await a(B)){l(ne=>[...ne,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},O=d.some(B=>B.kind==="approval_prompt"&&B.promptId&&!b.current.has(B.promptId)&&!y.current.has(B.promptId)),V=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval&&!O;return xr(Mr,{flexDirection:"column",paddingX:1,children:[te(an,{}),xr(Mr,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&xr(ml,{children:[te(wn,{messages:d,onApprovalSubmitted:B=>{b.current.add(B),w()},onApprovalFailed:B=>{y.current.add(B),w()}}),te(dn,{events:s,isStreaming:c}),!e.connected&&!e.serverUnreachable&&te(Mr,{children:te(pr,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&xr(Mr,{flexDirection:"column",children:[te(pr,{color:"red",bold:!0,children:"Server unreachable after 15s."}),te(pr,{dimColor:!0,children:"Check: adam server logs"}),te(pr,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&te(os,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&te(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&te(Fn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&te(Un,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&te(oo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&te(Gn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&te(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&te(zn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&te(Qn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&te(ts,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&te(ls,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&te(ds,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&te(us,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&te(es,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&te(ss,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="artifacts"&&te(vs,{onBack:()=>t({type:"SET_VIEW",view:"chat"}),onSelect:()=>{},onAction:()=>{}})]}),e.pendingPlanApproval?te(Bn,{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?te(kn,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):V?te(cn,{onSubmit:N}):te(cs,{}),e.planTimeoutNotice&&te(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()}),xr(Mr,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[xr(pr,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),te(pr,{dimColor:!0,children:" [d] Dismiss"})]})}function ul(){return te(Yo,{children:te(cl,{})})}export{ul as default};
14
+ Last active: ${new Date(r.lastActiveAt).toLocaleString()}`:"No active session";l(ie=>[...ie,{role:"assistant",content:D}]);return}}if(l(ne=>[...ne,{role:"user",content:B}]),I(),!await a(B)){l(ne=>[...ne,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},O=d.some(B=>B.kind==="approval_prompt"&&B.promptId&&!b.current.has(B.promptId)&&!y.current.has(B.promptId)),V=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval&&!O;return xr(Mr,{flexDirection:"column",paddingX:1,children:[te(ln,{}),xr(Mr,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&xr(hl,{children:[te(En,{messages:d,onApprovalSubmitted:B=>{b.current.add(B),w()},onApprovalFailed:B=>{y.current.add(B),w()}}),te(un,{events:s,isStreaming:c}),!e.connected&&!e.serverUnreachable&&te(Mr,{children:te(pr,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&xr(Mr,{flexDirection:"column",children:[te(pr,{color:"red",bold:!0,children:"Server unreachable after 15s."}),te(pr,{dimColor:!0,children:"Check: adam server logs"}),te(pr,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&te(as,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&te(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&te(Un,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&te(Kn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&te(oo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&te(zn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&te(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&te(Jn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&te(ts,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&te(ss,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&te(ms,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&te(gs,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&te(ps,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&te(ns,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&te(cs,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="artifacts"&&te(ks,{onBack:()=>t({type:"SET_VIEW",view:"chat"}),onSelect:()=>{},onAction:()=>{}})]}),e.pendingPlanApproval?te(Pn,{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?te(An,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):V?te(dn,{onSubmit:N}):te(fs,{}),e.planTimeoutNotice&&te(xl,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function xl({planId:e,onDismiss:t}){return ml(r=>{r==="d"&&t()}),xr(Mr,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[xr(pr,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),te(pr,{dimColor:!0,children:" [d] Dismiss"})]})}function Tl(){return te(Qo,{children:te(pl,{})})}export{Tl as default};