adam-agent-server 1.13.0 → 1.15.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 (210) hide show
  1. package/README.md +4 -5
  2. package/dist/App-6TRGTNZ7.js +13 -0
  3. package/dist/approval-handler-YLO3V75T.js +1 -0
  4. package/dist/audit-diagnostics-MASYIEGZ.js +1 -0
  5. package/dist/audit-manager-LYBXP7U4.js +1 -0
  6. package/dist/bree-engine-AA7EVKTG.js +1 -0
  7. package/dist/{channels-WFC26TED.js → channels-2IL6USWL.js} +1 -1
  8. package/dist/channels-6BEGHNOK.js +1 -0
  9. package/dist/chat-tool-calls-KARPW7PE.js +1 -0
  10. package/dist/chunk-245WE5AF.js +1 -0
  11. package/dist/chunk-2N4EOZZ4.js +9 -0
  12. package/dist/chunk-3BRHWRZ5.js +2 -0
  13. package/dist/chunk-3KNR2F6H.js +3 -0
  14. package/dist/chunk-42V6ZPCS.js +5 -0
  15. package/dist/chunk-6NWIZ3BH.js +220 -0
  16. package/dist/chunk-APAOIZN4.js +114 -0
  17. package/dist/chunk-ASPPM7TQ.js +1 -0
  18. package/dist/chunk-BKNXRSJU.js +4 -0
  19. package/dist/{chunk-MRTJFYPR.js → chunk-BLCNUT53.js} +1 -1
  20. package/dist/chunk-BPXS4QEO.js +1006 -0
  21. package/dist/chunk-CLNYHWZ6.js +5 -0
  22. package/dist/chunk-D3SPXZZY.js +6 -0
  23. package/dist/{chunk-SWP2JC54.js → chunk-DRO3DG7X.js} +1 -1
  24. package/dist/chunk-EVUZ5LH2.js +1 -0
  25. package/dist/chunk-F6U5TMM3.js +5 -0
  26. package/dist/chunk-FD4IKMXV.js +1 -0
  27. package/dist/chunk-GXWB47NF.js +9 -0
  28. package/dist/{chunk-PXGK5H5C.js → chunk-I7LJ4432.js} +1 -1
  29. package/dist/chunk-ICAM2GUU.js +1 -0
  30. package/dist/{chunk-B44X7JAJ.js → chunk-IRUR4DVD.js} +1 -1
  31. package/dist/chunk-ISKCTUI7.js +9 -0
  32. package/dist/{chunk-7T4B2MZ7.js → chunk-J3VYLSJI.js} +1 -1
  33. package/dist/chunk-KJNAORKM.js +15 -0
  34. package/dist/chunk-L47LZYVG.js +21 -0
  35. package/dist/chunk-LU3D53ZV.js +34 -0
  36. package/dist/{chunk-YKYRNTPV.js → chunk-N2OLEUAQ.js} +1 -1
  37. package/dist/{chunk-PHT24MOV.js → chunk-NLTYJUQG.js} +1 -1
  38. package/dist/chunk-NNMQGISW.js +1 -0
  39. package/dist/chunk-NPGZRSGL.js +5 -0
  40. package/dist/chunk-NTVLV7NI.js +1 -0
  41. package/dist/chunk-NUJSTEV4.js +1 -0
  42. package/dist/{chunk-FUWPDXXG.js → chunk-NWGRLNUM.js} +1 -1
  43. package/dist/chunk-OQ3JOTPK.js +1 -0
  44. package/dist/chunk-RBJPQYV3.js +6 -0
  45. package/dist/chunk-SVUP3F4V.js +14 -0
  46. package/dist/chunk-TLMG5W3L.js +4 -0
  47. package/dist/chunk-TLP4ZMJB.js +19 -0
  48. package/dist/{chunk-WQFNB2MQ.js → chunk-TZCMK3UG.js} +6 -6
  49. package/dist/chunk-UFWMUBFH.js +25 -0
  50. package/dist/chunk-VKKDSXMR.js +1 -0
  51. package/dist/chunk-VNXTBIPI.js +31 -0
  52. package/dist/chunk-XF7YHFVR.js +15 -0
  53. package/dist/{chunk-X5V4VMET.js → chunk-XIVFVKMB.js} +2 -2
  54. package/dist/chunk-XYZVMTNN.js +1 -0
  55. package/dist/{chunk-Q2JQFDAK.js → chunk-XZEBYOFR.js} +3 -3
  56. package/dist/chunk-Z6LHGA27.js +1 -0
  57. package/dist/cli.js +10 -10
  58. package/dist/config-VHWLMFIN.js +1 -0
  59. package/dist/{config-GKVOAMY2.js → config-XO7TGH27.js} +1 -1
  60. package/dist/db-WCTOLFAZ.js +1 -0
  61. package/dist/delivery-log-ML4RJOBM.js +1 -0
  62. package/dist/dist-HCSYRPJU.js +1 -0
  63. package/dist/engine-XLH4VL6Y.js +1 -0
  64. package/dist/evolution-audit-HLU7LQL6.js +1 -0
  65. package/dist/execution-tools-SYP3GR6T.js +1 -0
  66. package/dist/{external-api-DOVGA3ML.js → external-api-YMEFVZGG.js} +1 -1
  67. package/dist/index.js +240 -36
  68. package/dist/learner-NJXX2RUL.js +1 -0
  69. package/dist/{logger-WEXZORHP.js → logger-PAMNFWI3.js} +1 -1
  70. package/dist/memories-JDTQM3UN.js +1 -0
  71. package/dist/memory-extractor-5PTMCSOX.js +1 -0
  72. package/dist/memory-gc-BCHTOSXK.js +1 -0
  73. package/dist/memory-service-66EMRJXO.js +1 -0
  74. package/dist/onnxruntime_binding-2BPLI7ZQ.node +0 -0
  75. package/dist/onnxruntime_binding-5J67DTMJ.node +0 -0
  76. package/dist/onnxruntime_binding-7ZZLEQ2F.node +0 -0
  77. package/dist/onnxruntime_binding-KDCXAPN5.node +0 -0
  78. package/dist/onnxruntime_binding-R73P2IQW.node +0 -0
  79. package/dist/outbound-gateway-3INYZDOR.js +1 -0
  80. package/dist/presets-DT3J2ON4.js +1 -0
  81. package/dist/reflection-job-ST4ANCGB.js +23 -0
  82. package/dist/role-presets-3IQKCSVQ.js +1 -0
  83. package/dist/role-workspace-SIHNI6HO.js +1 -0
  84. package/dist/roles-F6AEM6B5.js +1 -0
  85. package/dist/{runtime-QA2DCZYQ.js → runtime-TWLGJSL6.js} +1 -1
  86. package/dist/session-manager-JTQRJI7R.js +1 -0
  87. package/dist/skill-registry-4JT62GEF.js +1 -0
  88. package/dist/target-resolution-PSSBM4LX.js +1 -0
  89. package/dist/task-templates-6G46OVYT.js +1 -0
  90. package/dist/template-dispatch-2K7KV7YS.js +1 -0
  91. package/dist/template-execution-artifacts-NEPSVD2B.js +1 -0
  92. package/dist/trace-context-UR7DI5ME.js +1 -0
  93. package/package.json +34 -14
  94. package/web/dist/assets/{Button-VPwTNGpF.js → Button-fLMsJd5o.js} +1 -1
  95. package/web/dist/assets/{Card-C2N6k4gh.js → Card-cy-gHU0O.js} +1 -1
  96. package/web/dist/assets/{ChannelDetail-DktmpO0A.js → ChannelDetail-CsKBPHkT.js} +1 -1
  97. package/web/dist/assets/Channels-DMutLV9r.js +14 -0
  98. package/web/dist/assets/Chat-DWTs-iOw.js +2 -0
  99. package/web/dist/assets/Dashboard-CoatfhW8.js +1 -0
  100. package/web/dist/assets/{EmptyState-CWS9PJND.js → EmptyState-C5kVDHc7.js} +1 -1
  101. package/web/dist/assets/{EnvVarEditor-D0kGIBcl.js → EnvVarEditor-BvRsHayG.js} +1 -1
  102. package/web/dist/assets/{EventDefDetail-BiXTA6LF.js → EventDefDetail-zuJydp12.js} +1 -1
  103. package/web/dist/assets/Events-nCImjXyr.js +1 -0
  104. package/web/dist/assets/{Evolution-C884p_CE.js → Evolution-Br41g99g.js} +1 -1
  105. package/web/dist/assets/ExtensionDetail-BXlphIkn.js +1 -0
  106. package/web/dist/assets/Extensions-3lhbw0A2.js +1 -0
  107. package/web/dist/assets/{FeatureRequests-Ck0WQnXX.js → FeatureRequests-oaXQNu43.js} +1 -1
  108. package/web/dist/assets/{GoalDetail-DJOyf7By.js → GoalDetail-DRDg1JDv.js} +1 -1
  109. package/web/dist/assets/Goals-DGmKvtGA.js +1 -0
  110. package/web/dist/assets/{Logs-6r7fnBn7.js → Logs-BZKxhdnb.js} +1 -1
  111. package/web/dist/assets/{Memories-CvPaqv5r.js → Memories-DhJJk-KB.js} +1 -1
  112. package/web/dist/assets/{Mistakes-aUhkqHDC.js → Mistakes-DxThj9as.js} +1 -1
  113. package/web/dist/assets/{NotFound-R6tIzhL0.js → NotFound-buXr2gl7.js} +1 -1
  114. package/web/dist/assets/{PageHeader-D9lLjo0N.js → PageHeader-BgNbz3JV.js} +1 -1
  115. package/web/dist/assets/Plugins-BXrsGsXs.js +1 -0
  116. package/web/dist/assets/RoleDetail-rClUsHwS.js +35 -0
  117. package/web/dist/assets/Roles-DH9cRv8h.js +1 -0
  118. package/web/dist/assets/{SectionHeader-BB3H3F_P.js → SectionHeader-CwX6m1f6.js} +1 -1
  119. package/web/dist/assets/Settings-My2lOEWv.js +1 -0
  120. package/web/dist/assets/{Strategies-DUps-2I9.js → Strategies-YLMryJlG.js} +1 -1
  121. package/web/dist/assets/{Switch-B_R_EX9s.js → Switch-PNpjNoGn.js} +1 -1
  122. package/web/dist/assets/{Table-D4lT5uHx.js → Table-BrERwl-F.js} +1 -1
  123. package/web/dist/assets/{Tabs-CwzWpI-7.js → Tabs-CGHmpUAD.js} +1 -1
  124. package/web/dist/assets/TaskDetail-Bkaq0NwW.js +2 -0
  125. package/web/dist/assets/Work-4OcGMu_a.js +1 -0
  126. package/web/dist/assets/api-BkdixMz9.js +1 -0
  127. package/web/dist/assets/{es2015-DCW7LI8d.js → es2015-JqLIWAgH.js} +1 -1
  128. package/web/dist/assets/index-C-e-qpXc.js +12 -0
  129. package/web/dist/assets/index-DGTVc0qD.css +2 -0
  130. package/web/dist/assets/{useIsMobileLayout-D6Tz5o5h.js → useIsMobileLayout-Blj4Mk4K.js} +1 -1
  131. package/web/dist/assets/{usePluginsWithUsage-CSQr03vZ.js → usePluginsWithUsage-Ch9WCFTb.js} +1 -1
  132. package/web/dist/assets/vendor-icons-U4igmrUq.js +1 -0
  133. package/web/dist/assets/{vendor-react-CIkiuNDu.js → vendor-react-Bp_V-Hsf.js} +1 -1
  134. package/web/dist/assets/{vendor-state-CEOsUh-T.js → vendor-state-Zjl_6-V3.js} +1 -1
  135. package/web/dist/index.html +8 -8
  136. package/dist/App-5QZKMPRM.js +0 -13
  137. package/dist/adam-tools-SQD2V4RJ.js +0 -1
  138. package/dist/approval-handler-J6RUTICJ.js +0 -1
  139. package/dist/audit-manager-CWVHQAUI.js +0 -1
  140. package/dist/bree-engine-VGEYMVNP.js +0 -1
  141. package/dist/channels-OOIM62BX.js +0 -1
  142. package/dist/chunk-2BXTT4P2.js +0 -6
  143. package/dist/chunk-47COBMRF.js +0 -1
  144. package/dist/chunk-6JBSBSCL.js +0 -1
  145. package/dist/chunk-6WRZJVQ2.js +0 -1
  146. package/dist/chunk-7IFLU3CY.js +0 -4
  147. package/dist/chunk-AQO6IIHV.js +0 -684
  148. package/dist/chunk-AVM3O74V.js +0 -5
  149. package/dist/chunk-B544JOZM.js +0 -3
  150. package/dist/chunk-DZIEY4CH.js +0 -47
  151. package/dist/chunk-E4WIUUL4.js +0 -27
  152. package/dist/chunk-HDHMNT6D.js +0 -1
  153. package/dist/chunk-JYHOGBCP.js +0 -12
  154. package/dist/chunk-M3RZWIW3.js +0 -50
  155. package/dist/chunk-N4ES7TCL.js +0 -1
  156. package/dist/chunk-NPIXYK5G.js +0 -5
  157. package/dist/chunk-O7XQSONJ.js +0 -5
  158. package/dist/chunk-OZL6VNOR.js +0 -146
  159. package/dist/chunk-Q2ISNOBQ.js +0 -1
  160. package/dist/chunk-QYRI4HYA.js +0 -1
  161. package/dist/chunk-R2WB5BKF.js +0 -7
  162. package/dist/chunk-RMGBR3XZ.js +0 -21
  163. package/dist/chunk-S6OV7Z6K.js +0 -1
  164. package/dist/chunk-SC2DDRYB.js +0 -5
  165. package/dist/chunk-SGIKNIC5.js +0 -49
  166. package/dist/chunk-TI3AKKWZ.js +0 -80
  167. package/dist/chunk-U2LBBBWO.js +0 -8
  168. package/dist/chunk-UXDTFTG5.js +0 -10
  169. package/dist/chunk-Y5FFL6UO.js +0 -5
  170. package/dist/chunk-ZFDULJGB.js +0 -3
  171. package/dist/chunk-ZQ4PNKMQ.js +0 -10
  172. package/dist/config-DRFRLIVN.js +0 -1
  173. package/dist/db-FACSMWEY.js +0 -1
  174. package/dist/delivery-log-JIQMHBJ5.js +0 -1
  175. package/dist/dist-CDWBOTZS.js +0 -1
  176. package/dist/engine-OHYWUUMJ.js +0 -1
  177. package/dist/evolution-audit-M7FSYRQR.js +0 -1
  178. package/dist/learner-OUNQSWN7.js +0 -1
  179. package/dist/memories-ABE7PMQL.js +0 -1
  180. package/dist/memory-extractor-ZX2NJIBV.js +0 -6
  181. package/dist/memory-service-UWER3T2S.js +0 -1
  182. package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
  183. package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
  184. package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
  185. package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
  186. package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
  187. package/dist/outbound-gateway-XDCGAXXW.js +0 -1
  188. package/dist/presets-RMW3WO5P.js +0 -1
  189. package/dist/role-presets-FAXQRBII.js +0 -1
  190. package/dist/role-workspace-ISGPO25D.js +0 -1
  191. package/dist/roles-WNKRM6FD.js +0 -1
  192. package/dist/session-manager-SOJXQHHY.js +0 -1
  193. package/dist/task-templates-IS3DJCZB.js +0 -1
  194. package/dist/token-estimator-HMPVGDCN.js +0 -1
  195. package/dist/workflow-executor-LOMKVFPV.js +0 -1
  196. package/web/dist/assets/Channels-ozCXdZMq.js +0 -12
  197. package/web/dist/assets/Chat-CggvtidD.js +0 -2
  198. package/web/dist/assets/Dashboard-z37ZVhzH.js +0 -1
  199. package/web/dist/assets/Events-C4P3jjZd.js +0 -1
  200. package/web/dist/assets/Goals-CDZWDuXR.js +0 -1
  201. package/web/dist/assets/Plugins-CtwoMUoj.js +0 -1
  202. package/web/dist/assets/RoleDetail-B32225ae.js +0 -33
  203. package/web/dist/assets/Roles-CGYsxuq8.js +0 -1
  204. package/web/dist/assets/Settings-D2jrO8-G.js +0 -1
  205. package/web/dist/assets/TaskDetail-DKminIM_.js +0 -2
  206. package/web/dist/assets/Work-uD_6IieV.js +0 -1
  207. package/web/dist/assets/api-D-UzHSDq.js +0 -1
  208. package/web/dist/assets/index-6f2jcj0h.css +0 -2
  209. package/web/dist/assets/index-Bl-2p6d8.js +0 -12
  210. package/web/dist/assets/vendor-icons-jzPiR6xl.js +0 -1
package/README.md CHANGED
@@ -42,7 +42,7 @@ Manages task lifecycle, concurrent execution pool, real-time streaming, remote h
42
42
  | | |
43
43
  | +-----v------+ |
44
44
  | | Scheduler | | Cron + event triggers
45
- | | (Bree) | | Multi-step workflows
45
+ | | (Bree) | | Multi-step template executions
46
46
  | +-----+------+ |
47
47
  | | |
48
48
  | +-------v--------+ |
@@ -67,7 +67,7 @@ Manages task lifecycle, concurrent execution pool, real-time streaming, remote h
67
67
  |----------|-------------|
68
68
  | **Task Management** | Submit, queue, run, cancel; full status tracking; cost and token accounting |
69
69
  | **Execution Pool** | Configurable concurrent slot pool; event-driven task pickup; poll-based fallback; crash resilience |
70
- | **Scheduling** | Cron expressions (5-field); event-driven triggers (`template_complete:<id>`); multi-step workflows with dependency DAGs |
70
+ | **Scheduling** | Cron expressions (5-field); event-driven triggers (`template_complete:<id>`); multi-step templates with dependency DAGs |
71
71
  | **Goal System** | Natural language SMART goals; metric trees; Thompson Sampling strategy selection |
72
72
  | **Role Model** | Role (identity/personality) with allowedTools/disallowedTools; role-level macOS OS Capabilities; learned rules; memory with hybrid search |
73
73
  | **Real-time Streaming** | WebSocket per-task stream + global event bus; structured pino logging |
@@ -160,7 +160,6 @@ adam tasks cancel <id>
160
160
  # Info
161
161
  adam config [--json]
162
162
  adam evolution [-l limit]
163
- adam register-ai-digest
164
163
  ```
165
164
 
166
165
  ### TUI Slash Commands
@@ -272,7 +271,7 @@ adam/
272
271
  │ │ ├── index.ts # CLI entry (commander)
273
272
  │ │ ├── daemon.ts # Daemon process management
274
273
  │ │ ├── client.ts # HTTP client for daemon
275
- │ │ ├── commands/ # config, evolution, logs, run, tasks, register-ai-digest
274
+ │ │ ├── commands/ # config, evolution, logs, run, tasks
276
275
  │ │ └── tui/ # Ink terminal UI (21 components, 11 slash commands)
277
276
  │ ├── server/
278
277
  │ │ ├── app.ts # Fastify + Swagger + static files
@@ -303,7 +302,7 @@ adam/
303
302
  │ │ └── evaluator/ # L0-L3 collectors, llm-judge, calibration
304
303
  │ ├── scheduler/
305
304
  │ │ ├── bree-engine.ts # Cron + event trigger scheduling
306
- │ │ └── workflow-executor.ts # Multi-step DAG execution
305
+ │ │ └── template-executor.ts # Multi-step TemplateExecution DAG execution
307
306
  │ ├── delivery/
308
307
  │ │ ├── engine.ts # Event subscription, rule matching
309
308
  │ │ └── outbound-gateway.ts # Dedup, format, anti-loop, retry, rate limit
@@ -0,0 +1,13 @@
1
+ import{b as v,d as vo,e as Br}from"./chunk-NLTYJUQG.js";import{a as bo,f as wr,h as kr}from"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";import{Box as go,Text as Xt,useInput as fa}from"ink";import{useState as pa,useEffect as Ho,useRef as Rt,useReducer as xa}from"react";import{createContext as os,useContext as rs,useReducer as ns}from"react";import{jsx as as}from"react/jsx-runtime";var ss={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null,version:null};function is(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};case"SET_VERSION":return{...e,version:t.version};default:return e}}var Ir=os(null);function Er({children:e}){let[t,o]=ns(is,ss);return as(Ir.Provider,{value:{state:t,dispatch:o},children:e})}function tt(){let e=rs(Ir);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Ar,useRef as Pr}from"react";var ls=15e3;function Rr(){let{state:e,dispatch:t}=tt(),o=Pr(null),g=Pr(null);Ar(()=>{g.current=e.session?.id??null},[e.session?.id]),Ar(()=>{let n=!0,m=null,d=()=>{o.current&&(clearTimeout(o.current),o.current=null)},a=()=>{d(),o.current=setTimeout(()=>{n&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},ls)};return(()=>{try{m=new vo("/events"),m.on("task_status_change",()=>{}),m.on("approval_request",s=>{if(!n)return;let p=s;t({type:"SET_PENDING_APPROVAL",approval:{taskId:p.taskId,approvalId:p.approvalId,toolName:p.toolName,toolInput:p.toolInput,matchedPattern:p.matchedPattern}})}),m.on("plan_approval_request",s=>{if(!n)return;let p=s;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:p.taskId,planId:p.planId,roleId:p.roleId,plan:p.plan}})}),m.on("plan_approval_decision",()=>{n&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),m.on("config_changed",()=>{n&&t({type:"CONFIG_CHANGED"})}),m.on("execution_task_start",s=>{if(!n)return;let p=s,f=g.current;f&&(async()=>{try{let S=await v(`/tasks/${p.taskId}`);n&&S.sourceSessionId===f&&t({type:"SET_ACTIVE_TASK",taskId:p.taskId})}catch{}})()}),m.on("stats_update",s=>{if(!n)return;let p=s;t({type:"UPDATE_STATS",activeTasks:p.activeTasks,queuedTasks:p.queuedTasks,costToday:p.totalCostToday})}),m.connect().then(async()=>{if(n){d(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let s=await v("/version");t({type:"SET_VERSION",version:s.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{n&&(t({type:"SET_CONNECTED",connected:!1}),a())})}catch{n&&(t({type:"SET_CONNECTED",connected:!1}),a())}})(),()=>{n=!1,d(),m?.close()}},[t])}import{useEffect as cs,useRef as ds,useState as Dr,useCallback as us}from"react";function Mr(e){let[t,o]=Dr([]),[g,n]=Dr(!1),m=ds(null),d=us(()=>{o([]),n(!1)},[]);return cs(()=>{if(!e)return;let a=!0;o([]),n(!0);try{let i=new Br(e);return m.current=i,i.on("reasoning",s=>{if(!a)return;let f=s.content??"";o(S=>{let b=S[S.length-1];if(b?.type==="reasoning"){let k=[...S];return k[k.length-1]={...b,content:b.content+f},k}return[...S,{type:"reasoning",content:f,timestamp:Date.now()}]})}),i.on("tool_call",s=>{if(!a)return;let p=s;o(f=>[...f,{type:"tool_call",content:p.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:p.toolName}}])}),i.on("tool_result",s=>{if(!a)return;let p=s;o(f=>[...f,{type:"tool_result",content:p.content??"",timestamp:Date.now()}])}),i.on("error",s=>{if(!a)return;let p=s;o(f=>[...f,{type:"error",content:p.error??"unknown error",timestamp:Date.now()}])}),i.on("complete",s=>{if(!a)return;let p=s;o(f=>[...f,{type:"complete",content:p.result??"",timestamp:Date.now(),metadata:{cost:p.costUsd,turns:p.numTurns,duration:p.totalDurationMs}}]),n(!1)}),i.connect().catch(()=>{a&&(o(s=>[...s,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),n(!1))}),()=>{a=!1,i.close()}}catch{n(!1)}},[e]),{events:t,isStreaming:g,clearEvents:d}}import{useState as Yo,useEffect as ms,useCallback as Zt}from"react";function Jo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function $r(){let[e,t]=Yo(null),[o,g]=Yo(!0),[n,m]=Yo(null),d=Zt(async()=>{try{let S=(await v("/chat/sessions?status=active")).sessions.find(b=>b.source.type==="tui");return S?Jo(S):null}catch{return null}},[]),a=Zt(async()=>{try{let f=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),S=Jo(f.session);return t(S),S}catch{return m("Failed to create session"),null}},[]),i=Zt(async f=>{try{let S=await v("/chat/messages",{method:"POST",body:{content:f,source:{type:"tui"}}});return t(b=>b&&{...b,messageCount:b.messageCount+1,lastActiveAt:Date.now()}),S}catch{return null}},[]),s=Zt(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),p=Zt(async()=>{if(e)try{let f=await v(`/chat/sessions/${e.id}`);t(Jo(f.session))}catch{t(null)}},[e]);return ms(()=>{let f=!1;async function S(){g(!0);let b=await d();f||(b?t(b):await a(),f||g(!1))}return S(),()=>{f=!0}},[]),{session:e,loading:o,error:n,sendMessage:i,createNewSession:a,archiveCurrentSession:s,refreshSession:p,setSession:t}}import{useEffect as Nr,useRef as gs,useState as fs}from"react";function _r(e){let[t,o]=fs(null),g=gs(new Set);return Nr(()=>{if(!e)return;let n=!0,m=null;try{m=new vo("/chat/stream"),m.on("chat_message",d=>{if(!n)return;let i=d.message;i&&i.sessionId===e&&i.role==="assistant"&&(g.current.has(i.id)||(g.current.add(i.id),o(i)))}),m.connect().catch(()=>{})}catch{}return()=>{n=!1,m?.close()}},[e]),Nr(()=>{g.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as Zo,Text as Me}from"ink";import{Fragment as Co,jsx as ye,jsxs as _t}from"react/jsx-runtime";var ps=90;function Lr({children:e}){return ye(Zo,{children:e})}function Or(){let{state:e}=tt(),t=e.session,g=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,n=e.connected?"up":"down",m=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)<ps,s=_t(Co,{children:[ye(Me,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ye(Me,{dimColor:!0,children:" | "}),ye(Me,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),ye(Me,{children:` ${n}`}),ye(Me,{dimColor:!0,children:" | "}),ye(Me,{children:m.toLowerCase()})]}),p=_t(Co,{children:[ye(Me,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),ye(Me,{dimColor:!0,children:" | "}),ye(Me,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&_t(Co,{children:[ye(Me,{dimColor:!0,children:" | "}),ye(Me,{children:d}),g&&_t(Co,{children:[ye(Me,{dimColor:!0,children:" | "}),ye(Me,{color:"yellow",children:"timeout"})]})]})]});return i?_t(Zo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[ye(Lr,{children:s}),ye(Lr,{children:p})]}):_t(Zo,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[s,ye(Me,{dimColor:!0,children:" | "}),p]})}import{Box as So,Text as wo,useInput as Ts}from"ink";import{useState as tr,useMemo as hs}from"react";import ys 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:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function er(e){let t=e.toLowerCase();return xs.filter(o=>o.name.startsWith(t))}function Fr(e){let t=er(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as ko,jsxs as eo}from"react/jsx-runtime";function qr({onSubmit:e}){let[t,o]=tr(""),[g,n]=tr(0),[m,d]=tr(!1),a=t.startsWith("/")&&t.length>=1,i=t.slice(1),s=hs(()=>a?er(i):[],[a,i]),p=b=>{o(b),b.startsWith("/")?(d(!0),n(0)):d(!1)},f=()=>{let b=t.trim();if(b){if(b.startsWith("/")){let k=b.slice(1),r=Fr(k);e(r?`/${r.name}`:b)}else e(b);o(""),d(!1)}},S=b=>{e(`/${b.name}`),o(""),d(!1)};return Ts((b,k)=>{if(!(!m||!a||s.length===0)){if(k.upArrow){n(r=>r<=0?s.length-1:r-1);return}if(k.downArrow){n(r=>r>=s.length-1?0:r+1);return}if(k.tab){let r=s[g];r&&S(r);return}if(k.escape){d(!1),o("");return}}},{isActive:m&&a&&s.length>0}),eo(So,{flexDirection:"column",children:[m&&a&&s.length>0&&ko(So,{flexDirection:"column",marginBottom:0,paddingX:1,children:s.map((b,k)=>{let r=k===g;return eo(So,{children:[ko(wo,{color:r?"cyan":"gray",bold:r,children:r?"\u25B8 ":" "}),eo(wo,{color:r?"cyan":"white",bold:r,children:["/",b.name]}),eo(wo,{dimColor:!0,children:[" \u2014 ",b.description]})]},b.name)})}),eo(So,{borderStyle:"round",borderDimColor:!0,children:[ko(wo,{bold:!0,children:"\u25B8 "}),ko(ys,{value:t,onChange:p,onSubmit:f,placeholder:"Type a message or / for commands..."})]})]})}import{Box as Lt,Text as Ie,useInput as bs}from"ink";import{useState as vs}from"react";import{jsx as Oe,jsxs as ot}from"react/jsx-runtime";function Cs({content:e,expanded:t}){let o=e.split(`
2
+ `);return o.length<=5?Oe(Ie,{color:"green",children:e}):t?Oe(Ie,{color:"green",children:e}):ot(Ie,{color:"green",children:[o.slice(0,3).join(`
3
+ `),`
4
+ `,ot(Ie,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function Ss({event:e,expanded:t}){switch(e.type){case"reasoning":return Oe(Lt,{children:Oe(Ie,{color:"gray",children:e.content})});case"tool_call":return Oe(Lt,{children:ot(Ie,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return ot(Lt,{flexDirection:"column",children:[Oe(Ie,{color:"blue",dimColor:!0,children:"[result]"}),Oe(Cs,{content:e.content,expanded:t})]});case"error":return Oe(Lt,{children:ot(Ie,{color:"red",children:["[error] ",e.content]})});case"complete":return ot(Lt,{flexDirection:"column",marginTop:1,children:[e.content&&Oe(Ie,{children:e.content}),Oe(Ie,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&ot(Ie,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&ot(Ie,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&ot(Ie,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function Vr({events:e,isStreaming:t}){let[o,g]=vs(!1),n=e.some(m=>m.type==="tool_result"&&m.content.split(`
5
+ `).length>5);return bs((m,d)=>{d.ctrl&&m==="o"&&g(a=>!a)},{isActive:n}),e.length===0&&!t?null:ot(Lt,{flexDirection:"column",children:[t&&e.length===0&&Oe(Ie,{dimColor:!0,children:"Waiting for response..."}),e.map((m,d)=>Oe(Ss,{event:m,expanded:o},d)),n&&Oe(Ie,{dimColor:!0,children:o?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as en,Text as Do}from"ink";import{Box as ws,Text as Bo}from"ink";import ks from"ink-spinner";import{jsx as Io,jsxs as Ur}from"react/jsx-runtime";var Bs={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 Wr({content:e,phase:t,taskShortId:o}){let g=Bs[t];return Ur(ws,{children:[Io(Bo,{color:g.color,children:t==="running"?Io(ks,{type:"dots"}):g.glyph}),Io(Bo,{children:" "}),o&&Ur(Bo,{dimColor:!0,children:["[",o,"] "]}),Io(Bo,{dimColor:!0,children:e})]})}import{Box as to,Text as Po}from"ink";var Gr=["cyan","magenta","green","yellow","blue","red"];function Is(e){let t=5381;for(let o=0;o<e.length;o++)t=(t<<5)+t^e.charCodeAt(o);return Math.abs(t)}function Eo(e){return e?Gr[Is(e)%Gr.length]:"cyan"}function Ao(e){return e?`T-${e.replace(/-/g,"").slice(0,8).toUpperCase()}`:""}import{jsx as oo,jsxs as Ro}from"react/jsx-runtime";function Es(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function As(e){if(!e)return"";let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function Ps(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 Hr(e){let t=Eo(e.roleId),o=e.roleName??"?",g=e.taskShortIdLabel?` \xB7 ${e.taskShortIdLabel}`:"";return Ro(to,{flexDirection:"column",borderStyle:"round",borderColor:t,paddingX:1,children:[oo(to,{children:Ro(Po,{bold:!0,color:t,children:["[",o,g,"]"]})}),oo(to,{marginTop:1,children:oo(Po,{children:e.content})}),e.attachments&&e.attachments.length>0&&oo(to,{flexDirection:"column",marginTop:1,children:e.attachments.map(n=>{let m=n.purpose?`purpose=${n.purpose}, `:"";return Ro(Po,{dimColor:!0,children:["[file] ",n.filename," (",m,Es(n.size),") \u2192 ",n.locator]},n.artifactId)})}),e.mirroredToTargets&&e.mirroredToTargets.length>0&&oo(to,{marginTop:1,children:Ro(Po,{dimColor:!0,italic:!0,children:["(also delivered to: ",Ps(e.mirroredToTargets)," @ ",As(e.createdAt),")"]})})]})}import{Box as Bt,Text as Ot}from"ink";import Rs from"ink-select-input";import{useState as jr}from"react";import{jsx as dt,jsxs as ro}from"react/jsx-runtime";var Ds=[{label:"\u6279\u51C6 / Yes",value:"\u6279\u51C6"},{label:"\u62D2\u7EDD / No",value:"\u62D2\u7EDD"}];function Kr({promptId:e,content:t,shape:o,choices:g,onSubmitted:n,onSubmitFailure:m}){let[d,a]=jr(null),[i,s]=jr(null),p=o==="yes_no"?Ds:o==="choose_one"&&g&&g.length>0?g.map(S=>({label:S,value:S})):[],f=async S=>{try{await v("/chat/messages",{method:"POST",body:{content:S.value,source:{type:"tui"},buttonPayload:{promptId:e,value:S.value}}}),a(S.value),n?.(S.value)}catch{s(`Failed to submit. Try again or type "#${e} ${S.value}" in the input bar.`),m?.()}};return ro(Bt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[ro(Ot,{bold:!0,color:"yellow",children:["\u26A0 #",e]}),dt(Bt,{marginTop:1,children:dt(Ot,{children:t})}),d?dt(Bt,{marginTop:1,children:ro(Ot,{color:"green",children:["[\u5DF2\u63D0\u4EA4: ",d," \u2713]"]})}):o==="free_input"?dt(Bt,{marginTop:1,children:ro(Ot,{dimColor:!0,children:["Free-input shape: \u8BF7\u56DE\u590D #",e," \u4F60\u7684\u7B54\u590D"]})}):p.length>0?dt(Bt,{marginTop:1,children:dt(Rs,{items:p,onSelect:f})}):dt(Bt,{marginTop:1,children:ro(Ot,{color:"red",dimColor:!0,children:["(no choices configured for shape=",o,")"]})}),i&&dt(Bt,{marginTop:1,children:dt(Ot,{color:"red",children:i})})]})}import{Box as Ms,Text as $s}from"ink";import{jsx as _s,jsxs as Ns}from"react/jsx-runtime";function zr({content:e}){return _s(Ms,{children:Ns($s,{dimColor:!0,children:["\xB7 ",e]})})}import{Box as or,Text as Ls}from"ink";import{jsx as Qr,jsxs as Xr}from"react/jsx-runtime";function Yr({threadRoot:e,roleId:t,roleName:o,taskShortIdLabel:g,brief:n,children:m}){let d=Eo(t),a=[g,o,n].filter(Boolean),i=a.length>0?a.join(" / "):e.slice(0,8);return Xr(or,{flexDirection:"column",borderStyle:"round",borderColor:d,paddingX:1,marginBottom:1,children:[Qr(or,{children:Xr(Ls,{bold:!0,color:d,children:["[Thread ",i,"]"]})}),Qr(or,{flexDirection:"column",marginTop:1,children:m})]})}import{useEffect as Os,useState as Jr}from"react";function Zr(){let[e,t]=Jr(new Map),[o,g]=Jr(!1);return Os(()=>{let n=!1;async function m(){try{let d=await v("/roles");if(n)return;let a=new Map;for(let i of d.roles)a.set(i.id,i.name);t(a)}catch{}finally{n||g(!0)}}return m(),()=>{n=!0}},[]),{getName:n=>n&&e.get(n)||"?",loaded:o}}import{jsx as bt,jsxs as rr}from"react/jsx-runtime";function Fs(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 qs(e,t,o){return function(n,m){if(!n.kind||n.kind==="user_message"||n.kind==="assistant_text")return rr(en,{flexDirection:"column",marginBottom:1,children:[bt(Do,{dimColor:!0,bold:!0,children:n.role==="user"?"You:":"Adam:"}),bt(Do,{children:n.content})]},m);if(n.kind==="status_report")return bt(Wr,{content:n.content,phase:Fs(n.content),taskShortId:Ao(n.taskId)},m);if(n.kind==="result_delivery")return bt(Hr,{content:n.content,roleId:n.roleId,roleName:e(n.roleId),taskShortIdLabel:Ao(n.taskId),attachments:n.attachments,mirroredToTargets:n.mirroredToTargets,createdAt:n.createdAt},m);if(n.kind==="approval_prompt"&&n.promptId&&n.approvalShape){let d=n.promptId;return bt(Kr,{promptId:d,content:n.content,shape:n.approvalShape,onSubmitted:()=>t?.(d),onSubmitFailure:()=>o?.(d)},m)}return n.kind==="system_note"?bt(zr,{content:n.content},m):bt(Do,{dimColor:!0,children:n.content},m)}}function Vs(e){let t=[],o=0;for(;o<e.length;){let g=e[o];if(g.kind==="status_report"){let n=o;for(;n<e.length&&e[n].kind==="status_report";)n++;let m=n-o;if(m>=3){t.push({__synthetic:!0,count:m,lastContent:e[n-1].content}),o=n;continue}}t.push(g),o++}return t}function tn({messages:e,onApprovalSubmitted:t,onApprovalFailed:o}){let{getName:g}=Zr(),n=qs(g,t,o);if(e.length===0)return null;let m=[],d=new Map;for(let a of e)if(!a.threadRoot)m.push(a);else{let i=d.get(a.threadRoot)??[];i.push(a),d.set(a.threadRoot,i)}return rr(en,{flexDirection:"column",children:[m.map((a,i)=>n(a,`free-${a.id??i}`)),Array.from(d.entries()).map(([a,i])=>{let s=i[0],p=Vs(i);return bt(Yr,{threadRoot:a,roleId:s.roleId,roleName:g(s.roleId),taskShortIdLabel:Ao(s.taskId),brief:s.content.slice(0,30),children:p.map((f,S)=>"__synthetic"in f?rr(Do,{dimColor:!0,children:["\u2026 ",f.count," \u6761\u8FDB\u5C55\uFF08\u6700\u8FD1: ",f.lastContent.slice(0,40),"\uFF09"]},`compressed-${S}`):n(f,`${a}-${f.id??S}`))},`thread-${a}`)})]})}import{Box as no,Text as rt,useInput as Us}from"ink";import{jsx as nt,jsxs as so}from"react/jsx-runtime";function on({approval:e,onResolved:t}){return Us(o=>{o==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),so(no,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[nt(rt,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),so(no,{marginTop:1,children:[nt(rt,{children:"Tool: "}),nt(rt,{bold:!0,children:e.toolName})]}),so(no,{children:[nt(rt,{children:"Input: "}),nt(rt,{children:JSON.stringify(e.toolInput)})]}),so(no,{children:[nt(rt,{children:"Pattern: "}),nt(rt,{dimColor:!0,children:e.matchedPattern})]}),so(no,{marginTop:1,children:[nt(rt,{color:"green",children:"[a] Approve"}),nt(rt,{children:" "}),nt(rt,{color:"red",children:"[r] Reject"})]})]})}import{Box as io,Text as Ee,useInput as Ws}from"ink";import{useState as Gs,useEffect as Hs}from"react";import{jsx as ut,jsxs as ze}from"react/jsx-runtime";var js=300;function rn({approval:e,onResolved:t,onTimeout:o}){let[g,n]=Gs(js);Hs(()=>{let d=setInterval(()=>{n(a=>a<=1?(clearInterval(d),o(),0):a-1)},1e3);return()=>clearInterval(d)},[o]),Ws(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 m=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return ze(io,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ut(Ee,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),ze(Ee,{dimColor:!0,children:["Plan ID: ",e.planId]}),ze(Ee,{dimColor:!0,children:["Time remaining: ",g,"s"]}),ze(io,{marginTop:1,children:[ut(Ee,{children:"Overall Risk: "}),ut(Ee,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),ze(Ee,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(d=>{let a=d.riskLevel==="high"?"red":d.riskLevel==="medium"?"yellow":"green";return ze(io,{paddingLeft:2,children:[ze(Ee,{children:["[",d.index,"] "]}),ut(Ee,{children:d.description}),ze(Ee,{dimColor:!0,children:[" (",d.toolsNeeded.join(", "),")"]}),ze(Ee,{color:a,children:[" [",d.riskLevel,"]"]})]},d.index)}),ze(io,{marginTop:1,children:[ut(Ee,{dimColor:!0,children:"Permissions: "}),ut(Ee,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),ze(io,{marginTop:1,children:[ut(Ee,{color:"green",children:"[a] Allow once "}),ut(Ee,{color:"green",children:"[p] Allow permanent "}),ut(Ee,{color:"red",children:"[r] Deny"})]})]})}import{Box as be,Text as K,useInput as ti}from"ink";import{useEffect as oi,useState as vt,useCallback as dn}from"react";import{Box as xe,Text as U,useInput as Ks}from"ink";import{useEffect as zs,useState as Ft}from"react";import{jsx as ae,jsxs as H}from"react/jsx-runtime";var nn={plan:!0,result:!1,routing:!0,error:!0},Xs={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function cn({taskId:e,onBack:t}){let[o,g]=Ft(null),[n,m]=Ft([]),[d,a]=Ft([]),[i,s]=Ft(null),[p,f]=Ft(nn),[S,b]=Ft(!1);zs(()=>{let C=!1;return g(null),m([]),a([]),s(null),f(nn),b(!1),v(`/tasks/${e}`).then(({task:A})=>{C||g(A)}).catch(A=>{C||s(A instanceof Error?A.message:String(A))}),v(`/tasks/${e}/plan`).then(({plans:A})=>{C||m(A)}).catch(()=>{C||m([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:A})=>{C||a(A)}).catch(()=>{C||a([])}),()=>{C=!0}},[e]);let k=C=>{f(A=>({...A,[C]:!A[C]}))};if(Ks((C,A)=>{if(C==="b"||A.escape){t();return}C==="1"&&k("plan"),C==="2"&&k("result"),C==="3"&&k("routing"),C==="4"&&k("error"),C==="5"&&b(X=>!X)}),i)return H(xe,{flexDirection:"column",children:[H(U,{color:"red",children:["Task detail failed: ",i]}),ae(U,{dimColor:!0,children:"[b] Back"})]});if(!o)return H(U,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let r=n[0],l=Zs(o.deliverTo,o.reportTo),E=d.length>0?`${d.length} delivery event${d.length===1?"":"s"}`:"No delivery events";return H(xe,{flexDirection:"column",children:[H(xe,{children:[H(U,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ae(U,{dimColor:!0,children:" \u2022 "}),ae(U,{color:Xs[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),H(U,{dimColor:!0,children:[o.roleId?`role ${o.roleId}`:"no role"," \u2022 ",ln(o.createdAt)," \u2022 ",Js(o.totalDurationMs)]}),H(xe,{marginTop:1,flexDirection:"column",children:[ae(U,{bold:!0,children:"Summary"}),ae(U,{children:S?o.prompt:Qs(o.prompt,240)}),o.prompt.length>240&&H(U,{dimColor:!0,children:["[5] ",S?"collapse prompt":"expand prompt"]}),H(xe,{marginTop:1,flexDirection:"column",children:[H(U,{dimColor:!0,children:["Cost: ",Ys(o.costUsd)]}),H(U,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),H(U,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),H(U,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),H(xe,{marginTop:1,flexDirection:"column",children:[H(U,{bold:!0,children:["[1] Plan ",p.plan?"hide":"show"]}),ae(U,{dimColor:!0,children:r?`${r.plan.steps.length} planned step${r.plan.steps.length===1?"":"s"} \u2022 ${r.plan.overallRisk} risk \u2022 ${r.status}`:"No execution plan"}),p.plan&&r&&H(xe,{marginTop:1,flexDirection:"column",children:[r.plan.steps.map(C=>H(xe,{flexDirection:"column",marginBottom:1,children:[H(U,{children:[C.index,". ",C.description]}),H(U,{dimColor:!0,children:[C.riskLevel," risk \u2022 ",C.toolsNeeded.join(", ")||"no tools listed"]}),C.expectedOutput?H(U,{dimColor:!0,children:["Expected: ",C.expectedOutput]}):null]},C.index)),r.learnedRules&&r.learnedRules.length>0&&H(xe,{flexDirection:"column",children:[ae(U,{color:"blue",bold:!0,children:"Learned Rules"}),r.learnedRules.map((C,A)=>H(U,{dimColor:!0,children:["\u2022 ",C]},A))]})]})]}),H(xe,{marginTop:1,flexDirection:"column",children:[H(U,{bold:!0,children:["[2] Result ",p.result?"hide":"show"]}),ae(U,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),p.result&&ae(xe,{marginTop:1,children:ae(U,{children:o.result?an(o.result,18):"No result yet."})})]}),H(xe,{marginTop:1,flexDirection:"column",children:[H(U,{bold:!0,children:["[3] Routing ",p.routing?"hide":"show"]}),H(U,{dimColor:!0,children:[l," \u2022 ",E]}),p.routing&&H(xe,{marginTop:1,flexDirection:"column",children:[ae(U,{color:"cyan",children:"Deliver To"}),sn(o.deliverTo),ae(U,{color:"cyan",children:"Report To"}),sn(o.reportTo),d.length>0&&H(xe,{marginTop:1,flexDirection:"column",children:[ae(U,{color:"cyan",children:"Recent Delivery"}),d.map(C=>H(U,{dimColor:!0,children:[C.status," \u2022 ",ei(C)," \u2022 ",ln(C.createdAt)]},C.id))]})]})]}),H(xe,{marginTop:1,flexDirection:"column",children:[H(U,{bold:!0,children:["[4] Error ",p.error?"hide":"show"]}),ae(U,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),p.error&&o.error&&ae(xe,{marginTop:1,children:ae(U,{color:"red",children:an(o.error,16)})})]}),ae(xe,{marginTop:1,children:ae(U,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function sn(e){return!e||e.length===0?ae(U,{dimColor:!0,children:" none"}):ae(xe,{flexDirection:"column",children:e.map((t,o)=>ae(U,{dimColor:!0,children:t.type==="channel"?` channel ${t.channelId.slice(0,8)}${t.chatId?` / ${t.chatId.slice(0,8)}`:""}`:` session ${t.sessionId.slice(0,8)}`},`${t.type}-${o}`))})}function an(e,t){let o=e.split(`
6
+ `);return o.length<=t?e:`${o.slice(0,t).join(`
7
+ `)}
8
+ \u2026`}function Qs(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function Ys(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Js(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let o=Math.floor(t/60),g=t%60;return g===0?`${o}m`:`${o}m ${g}s`}function ln(e){return new Date(e).toLocaleString()}function Zs(e,t){let o=e?.length??0,g=t?.length??0;return o===0&&g===0?"No delivery targets":`${o} output target${o===1?"":"s"} \u2022 ${g} report target${g===1?"":"s"}`}function ei(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 ni,jsx as oe,jsxs as re}from"react/jsx-runtime";var un={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},Mo=["all","pending","queued","running","completed","failed","cancelled","blocked"],nr=15;function No({onBack:e}){let[t,o]=vt([]),[g,n]=vt(!0),[m,d]=vt("list"),[a,i]=vt(0),[s,p]=vt("all"),[f,S]=vt(0),[b,k]=vt(0),[r,l]=vt(null),E=dn(async()=>{n(!0);try{let N=new URLSearchParams({limit:"100"});s!=="all"&&N.set("status",s);let F=await v(`/tasks?${N}`);o(F.tasks)}catch{o([])}finally{n(!1)}},[s]);oi(()=>{E()},[E]);let C=Math.max(1,Math.ceil(t.length/nr)),A=t.slice(b*nr,(b+1)*nr),X=dn(async()=>{let N=A[a];if(N)try{await v(`/tasks/${N.id}/cancel`,{method:"POST"}),l(`Cancelled: ${N.id.slice(0,8)}`),d("list"),E()}catch(F){l(`Failed: ${F instanceof Error?F.message:String(F)}`),d("list")}},[A,a,E]);if(ti((N,F)=>{if(m==="detail"){(F.escape||F.return||N==="q")&&d("list");return}if(m==="cancelling"){N==="y"?X():d("list");return}if(m==="filter"){if(F.escape){d("list");return}F.upArrow&&f>0&&S(q=>q-1),F.downArrow&&f<Mo.length-1&&S(q=>q+1),F.return&&(p(Mo[f]),k(0),i(0),d("list"));return}if(F.escape||N==="q"){e();return}if(F.upArrow&&a>0&&i(q=>q-1),F.downArrow&&a<A.length-1&&i(q=>q+1),F.return&&A[a]&&d("detail"),N==="x"&&A[a]){let q=A[a];["running","pending","queued","paused"].includes(q.status)?(d("cancelling"),l(null)):l(`Cannot cancel task in status: ${q.status}`)}N==="f"&&(S(Mo.indexOf(s)),d("filter")),N==="r"&&E(),(F.pageDown||N==="n")&&b<C-1&&(k(q=>q+1),i(0)),(F.pageUp||N==="p")&&b>0&&(k(q=>q-1),i(0))}),g)return oe(K,{dimColor:!0,children:"Loading tasks..."});if(m==="filter")return re(be,{flexDirection:"column",children:[oe(K,{bold:!0,children:"Filter by status:"}),Mo.map((N,F)=>oe(be,{children:re(K,{color:F===f?"cyan":"white",children:[F===f?"> ":" ",N,N===s?" (current)":""]})},N)),oe(K,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(m==="detail"&&A[a])return oe(cn,{taskId:A[a].id,onBack:()=>d("list")});if(m==="cancelling"&&A[a])return re(be,{flexDirection:"column",children:[re(K,{color:"red",children:['Cancel task "',A[a].id.slice(0,8),'"? (y/n)']}),r&&oe(K,{color:"red",children:r})]});let Q=A[a]??null;return re(be,{flexDirection:"column",children:[re(be,{children:[re(K,{bold:!0,children:["Tasks (",t.length,")"]}),s!=="all"&&re(K,{dimColor:!0,children:[" [filter: ",s,"]"]}),re(K,{dimColor:!0,children:[" \u2022 Page ",b+1,"/",C]})]}),r&&oe(K,{color:r.startsWith("Failed")||r.startsWith("Cannot")?"red":"green",children:r}),t.length===0?re(K,{dimColor:!0,children:["No tasks found",s!=="all"?` with status "${s}"`:"","."]}):re(be,{marginTop:1,flexDirection:"row",gap:2,children:[oe(be,{flexDirection:"column",flexGrow:3,children:A.map((N,F)=>{let q=F===a,I=un[N.status]??"white";return re(be,{flexDirection:"column",marginBottom:1,children:[re(be,{children:[oe(K,{color:q?"cyan":"gray",bold:q,children:q?"\u276F ":" "}),oe(K,{color:I,bold:!0,children:N.status.toUpperCase()}),oe(K,{dimColor:!0,children:` ${N.id.slice(0,8)}`})]}),oe(be,{paddingLeft:2,children:oe(K,{color:q?"white":void 0,children:$o(N.prompt,q?72:56)})}),oe(be,{paddingLeft:2,children:re(K,{dimColor:!0,children:[fn(N.createdAt)," \u2022 ",mn(N)," \u2022 ",gn(N.costUsd)]})})]},N.id)})}),oe(be,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Q?re(ni,{children:[oe(K,{bold:!0,children:"Preview"}),re(be,{marginTop:1,children:[oe(K,{color:un[Q.status]??"white",bold:!0,children:Q.status.toUpperCase()}),oe(K,{dimColor:!0,children:` ${Q.id.slice(0,8)}`})]}),oe(K,{children:$o(Q.prompt,220)}),re(be,{marginTop:1,flexDirection:"column",children:[re(K,{dimColor:!0,children:["Role: ",Q.roleId??Q.agentId??"\u2014"]}),re(K,{dimColor:!0,children:["Created: ",fn(Q.createdAt)]}),re(K,{dimColor:!0,children:["Duration: ",mn(Q)]}),re(K,{dimColor:!0,children:["Cost: ",gn(Q.costUsd)]}),re(K,{dimColor:!0,children:["Turns: ",Q.numTurns??"\u2014"]})]}),Q.error?re(be,{marginTop:1,flexDirection:"column",children:[oe(K,{color:"red",bold:!0,children:"Error"}),oe(K,{color:"red",children:$o(Q.error,180)})]}):Q.result?re(be,{marginTop:1,flexDirection:"column",children:[oe(K,{color:"green",bold:!0,children:"Latest Result"}),oe(K,{children:$o(Q.result,180)})]}):null,oe(be,{marginTop:1,children:oe(K,{dimColor:!0,children:"Enter opens full detail"})})]}):oe(K,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function ri(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function $o(e,t){return ri(e.replace(/\s+/g," ").trim(),t)}function mn(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let o=Math.max(1,Math.round(t/1e3));if(o<60)return`${o}s`;let g=Math.floor(o/60),n=o%60;return n===0?`${g}m`:`${g}m ${n}s`}function gn(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function fn(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let o=Math.floor(t/60);if(o<60)return`${o}m ago`;let g=Math.floor(o/60);return g<24?`${g}h ago`:`${Math.floor(g/24)}d ago`}kr();import{Box as It,Text as $e,useInput as si}from"ink";import{useEffect as ii,useState as pn}from"react";import{readFileSync as ai,existsSync as li}from"fs";import{parse as ci}from"yaml";import{Fragment as ui,jsx as Ae,jsxs as Fe}from"react/jsx-runtime";function xn({onBack:e}){let[t,o]=pn(null),[g,n]=pn(null);return si((m,d)=>{(d.escape||m==="q")&&e()}),ii(()=>{try{let m=wr;if(!li(m)){n(`Config file not found: ${m}`);return}let d=ai(m,"utf-8");o(ci(d))}catch(m){n(m.message)}},[]),g?Fe(It,{flexDirection:"column",children:[Ae($e,{color:"red",children:g}),Ae($e,{dimColor:!0,children:"Press Esc to go back"})]}):t?Fe(It,{flexDirection:"column",children:[Ae($e,{bold:!0,children:"Configuration (Esc to go back)"}),Ae(It,{marginTop:1,flexDirection:"column",children:Ae(sr,{obj:t,indent:0})})]}):Ae($e,{dimColor:!0,children:"Loading config..."})}function sr({obj:e,indent:t}){let o=" ".repeat(t);return Ae(ui,{children:Object.entries(e).map(([g,n])=>Ae(di,{label:g,value:n,indent:t,parentKey:g},g))})}function di({label:e,value:t,indent:o,parentKey:g}){let n=" ".repeat(o);return Array.isArray(t)?Fe(It,{flexDirection:"column",children:[Fe($e,{children:[n,Ae($e,{color:"cyan",children:e}),":"]}),t.length===0?Fe($e,{dimColor:!0,children:[n," []"]}):t.map((m,d)=>Ae(Tn,{value:m,indent:o+1,parentKey:g,index:d},`${e}-${d}`))]}):t&&typeof t=="object"?Fe(It,{flexDirection:"column",children:[Fe($e,{children:[n,Ae($e,{color:"cyan",children:e}),":"]}),Ae(sr,{obj:t,indent:o+1})]}):Fe($e,{children:[n,Ae($e,{color:"cyan",children:e}),": ",hn(g,yn(t))]})}function Tn({value:e,indent:t,parentKey:o,index:g}){let n=" ".repeat(t);return Array.isArray(e)?Fe(It,{flexDirection:"column",children:[Fe($e,{children:[n,"- [",g,"]"]}),e.map((m,d)=>Ae(Tn,{value:m,indent:t+1,parentKey:o,index:d},`${g}-${d}`))]}):e&&typeof e=="object"?Fe(It,{flexDirection:"column",children:[Fe($e,{children:[n,"-"]}),Ae(sr,{obj:e,indent:t+1})]}):Fe($e,{children:[n,"- ",hn(o,yn(e))]})}function hn(e,t){let o=e.toLowerCase();return o.includes("key")||o.includes("token")||o.includes("secret")||o.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function yn(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as _o,Text as Xe,useInput as mi}from"ink";import{useEffect as gi,useState as ir}from"react";import{jsx as ao,jsxs as st}from"react/jsx-runtime";function bn({onBack:e}){let[t,o]=ir([]),[g,n]=ir(!0),[m,d]=ir(null);return mi((a,i)=>{(i.escape||a==="q")&&e()}),gi(()=>{v("/evolution-audit?limit=20").then(a=>{o(a),n(!1)}).catch(a=>{d(a.message),n(!1)})},[]),g?ao(Xe,{dimColor:!0,children:"Loading evolution log..."}):m?st(_o,{flexDirection:"column",children:[ao(Xe,{color:"red",children:m}),ao(Xe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?st(_o,{flexDirection:"column",children:[ao(Xe,{dimColor:!0,children:"No evolution records yet"}),ao(Xe,{dimColor:!0,children:"Press Esc to go back"})]}):st(_o,{flexDirection:"column",children:[st(Xe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(a=>st(_o,{flexDirection:"column",marginTop:1,children:[st(Xe,{bold:!0,children:["[",new Date(a.timestamp).toLocaleString(),"]"]}),a.triggerTaskId&&st(Xe,{dimColor:!0,children:[" Task: ",a.triggerTaskId.slice(0,8)]}),a.diff.split(`
9
+ `).map((i,s)=>i.startsWith("+")?st(Xe,{color:"green",children:[" ",i]},s):i.startsWith("-")?st(Xe,{color:"red",children:[" ",i]},s):st(Xe,{dimColor:!0,children:[" ",i]},s))]},a.id))]})}import{Box as mt,Text as le,useInput as fi}from"ink";import pi from"ink-text-input";import{useEffect as xi,useState as qt}from"react";import{jsx as Ne,jsxs as ve}from"react/jsx-runtime";var Ti={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function hi(e,t=20){let o=Math.round(e*t),g=t-o;return"\u2588".repeat(o)+"\u2591".repeat(g)}function yi(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Lo({onBack:e}){let[t,o]=qt([]),[g,n]=qt(null),[m,d]=qt("list"),[a,i]=qt(""),[s,p]=qt(!1),[f,S]=qt(null);fi((r,l)=>{if(m==="create"){l.escape&&(d("list"),i(""),S(null));return}(l.escape||r==="q")&&e(),r==="c"&&(d("create"),S(null)),r==="r"&&b()});let b=()=>{v("/goals?limit=20").then(({goals:r})=>o(r)).catch(r=>n(r.message))};xi(()=>{b()},[]);let k=async r=>{if(r.trim()){p(!0),S(null);try{let l=await v("/goals",{method:"POST",body:{input:r.trim()}});S(`Goal created: ${l.goal.name}`),i(""),d("list"),b()}catch(l){S(`Failed: ${l instanceof Error?l.message:String(l)}`)}finally{p(!1)}}};return g?ve(mt,{flexDirection:"column",children:[ve(le,{color:"red",children:["Failed to load goals: ",g]}),Ne(le,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?ve(mt,{flexDirection:"column",children:[Ne(le,{bold:!0,children:"Create Goal"}),Ne(le,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),ve(mt,{marginTop:1,children:[Ne(le,{color:"cyan",children:"> "}),Ne(pi,{value:a,onChange:i,onSubmit:k})]}),s&&Ne(le,{color:"yellow",children:"Creating goal..."}),f&&Ne(le,{color:f.startsWith("Failed")?"red":"green",children:f}),Ne(le,{dimColor:!0,children:"Press Esc to cancel"})]}):ve(mt,{flexDirection:"column",children:[ve(le,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Ne(le,{dimColor:!0,children:"No goals found. Press c to create one."}):Ne(mt,{marginTop:1,flexDirection:"column",children:t.map(r=>{let l=r.targetValue>0?r.currentValue/r.targetValue:0,E=Ti[r.status]??"white";return ve(mt,{marginBottom:1,flexDirection:"column",children:[ve(mt,{children:[Ne(le,{bold:!0,color:E,children:r.name}),ve(le,{dimColor:!0,children:[" (",r.role,")"]}),Ne(le,{dimColor:!0,children:" \u2014 "}),Ne(le,{color:E,children:r.status})]}),ve(mt,{children:[ve(le,{dimColor:!0,children:[" ",hi(l)," "]}),ve(le,{color:l>=1?"green":"white",children:[Math.round(l*100),"%"]}),ve(le,{dimColor:!0,children:[" (",r.currentValue,"/",r.targetValue," ",r.metricType,")"]})]}),ve(mt,{children:[ve(le,{dimColor:!0,children:[" \u23F0 ",yi(r.deadline)," left"]}),ve(le,{dimColor:!0,children:[" | \u{1F4B0} $",r.budgetUsd]}),ve(le,{dimColor:!0,children:[" | ID: ",r.id.slice(0,8)]})]})]},r.id)})}),Ne(le,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as Vt,Text as We,useInput as bi}from"ink";import{useEffect as vi,useState as vn}from"react";import{jsx as ft,jsxs as gt}from"react/jsx-runtime";function Ci(e,t,o=15){let g=e/(e+t),n=Math.round(g*o);return"\u2593".repeat(n)+"\u2591".repeat(o-n)}function Cn({onBack:e}){let[t,o]=vn([]),[g,n]=vn(null);if(bi((d,a)=>{(a.escape||d==="q")&&e()}),vi(()=>{v("/strategies?limit=50").then(d=>o(d.strategies??[])).catch(d=>n(d.message))},[]),g)return gt(Vt,{flexDirection:"column",children:[gt(We,{color:"red",children:["Failed to load strategies: ",g]}),ft(We,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return gt(Vt,{flexDirection:"column",children:[ft(We,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),ft(We,{dimColor:!0,children:"Press Esc or q to return"})]});let m=new Map;for(let d of t){let a=`${d.role}/${d.taskType}`,i=m.get(a)??[];i.push(d),m.set(a,i)}return gt(Vt,{flexDirection:"column",children:[ft(We,{bold:!0,children:"Strategy Lab"}),ft(We,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),ft(Vt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([d,a])=>gt(Vt,{marginBottom:1,flexDirection:"column",children:[ft(We,{bold:!0,color:"cyan",children:d}),a.sort((i,s)=>{let p=i.alpha/(i.alpha+i.beta);return s.alpha/(s.alpha+s.beta)-p}).map(i=>{let s=i.alpha/(i.alpha+i.beta);return gt(Vt,{children:[ft(We,{dimColor:!0,children:" "}),gt(We,{children:[Ci(i.alpha,i.beta)," "]}),gt(We,{color:s>.6?"green":s>.4?"yellow":"red",children:[(s*100).toFixed(0),"%"]}),gt(We,{dimColor:!0,children:[" ",i.name," (\u03B1=",i.alpha.toFixed(1)," \u03B2=",i.beta.toFixed(1)," trials=",i.totalTrials,")"]})]},i.id)})]},d))}),ft(We,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as Te,Text as W,useInput as Ii}from"ink";import ar from"ink-text-input";import{useEffect as Ei,useState as He,useCallback as Ct}from"react";import{CronExpressionParser as Ai}from"cron-parser";import{useState as Si,useEffect as wi,useCallback as Sn,useRef as ki}from"react";var Bi=3e3;function Ge(){let[e,t]=Si(null),o=ki(null),g=Sn(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),n=Sn((m,d)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:m,type:d}),d==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},Bi))},[]);return wi(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:n,clearMessage:g}}import{Fragment as Ri,jsx as ee,jsxs as Y}from"react/jsx-runtime";var lr=["manual","cron","once","template_complete"],wn=["cron","once","template_complete"],Oo={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function Pi(e){try{return Ai.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function Fo({onBack:e}){let[t,o]=He([]),[g,n]=He(!0),[m,d]=He(0),[a,i]=He("list"),[s,p]=He({...Oo}),[f,S]=He("name"),[b,k]=He(null),{message:r,setMessage:l,clearMessage:E}=Ge(),[C,A]=He(!1),[X,Q]=He(!1),[N,F]=He({}),[q,I]=He(null),[Z,se]=He(!1),ie=Ct(()=>{n(!0),v("/task-templates").then(({templates:x})=>{o(x),new Set(x.flatMap(R=>R.steps?.map(j=>j.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:R})=>{if(!Array.isArray(R)){F({});return}F(Object.fromEntries(R.map(j=>[j.id,j.name])))}).catch(()=>F({})):F({}),n(!1)}).catch(()=>n(!1))},[]);Ei(()=>{ie()},[ie]);let et=a==="create"||a==="edit",De=Ct(async()=>{let x=t[m];if(!(!x||C)){A(!0),l(`Triggering ${x.name}...`,"loading");try{let w=await v(`/task-templates/${x.id}/run`,{method:"POST"});l(`Triggered: ${x.name} (${w.executionId})`,"success")}catch(w){l(`Trigger failed: ${w instanceof Error?w.message:String(w)}`,"error")}finally{A(!1)}}},[t,m,C,l]),pe=Ct(async()=>{let x=t[m];if(!x||X)return;if(!wn.includes(x.trigger?.type??"manual")){l("Toggle not applicable for manual triggers","error");return}let w=!x.enabled;Q(!0),l(`${x.name} \u2192 ${w?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${x.id}`,{method:"PATCH",body:{enabled:w}}),o(R=>R.map(j=>j.id===x.id?{...j,enabled:w}:j)),l(`${x.name} ${w?"enabled":"disabled"}`,"success")}catch(R){l(`Toggle failed: ${R instanceof Error?R.message:String(R)}`,"error")}finally{Q(!1)}},[t,m,X,l]),ke=Ct(async()=>{if(Z)return;let x=t[m];if(x){se(!0);try{let w=await v(`/task-templates/${x.id}/dependents`,{method:"GET"});I({templateId:x.id,templateName:x.name,executionCount:w.dependents.executionCount,taskCount:w.dependents.taskCount}),w.dependents.taskCount===0&&w.dependents.executionCount===0?l(`Delete "${x.name}"? Press d to confirm, Esc to cancel.`,"loading"):l(`"${x.name}" has ${w.dependents.executionCount} template execution${w.dependents.executionCount===1?"":"s"}, ${w.dependents.taskCount} task${w.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(w){l(`Failed to inspect dependents: ${w instanceof Error?w.message:String(w)}`,"error")}finally{se(!1)}}},[t,m,l,Z]),Be=Ct(async x=>{let w=q;if(w){I(null);try{let R=await v(`/task-templates/${w.templateId}?mode=${x}`,{method:"DELETE"}),j=[];R.deletedCounts.templateExecutions>0&&j.push(`${R.deletedCounts.templateExecutions} template exec`),R.deletedCounts.tasks>0&&j.push(`${R.deletedCounts.tasks} task${R.deletedCounts.tasks===1?"":"s"}`);let ce=j.length?` (+${j.join(", ")})`:"";l(`Deleted: ${w.templateName}${ce}`,"success"),ie(),d(me=>Math.max(0,Math.min(me,t.length-2)))}catch(R){l(`Delete failed: ${R instanceof Error?R.message:String(R)}`,"error")}}},[q,ie,l,t.length]),yt=Ct(()=>{I(null),E()},[E]),wt=Ct(()=>{let x=t[m];x&&(k(x.id),p({name:x.name,triggerType:x.trigger?.type??"manual",cron:x.trigger?.cron??"",targetTemplateId:x.trigger?.type==="template_complete"?x.trigger.event?.split(":")[1]??"":"",stepPrompt:x.steps?.[0]?.prompt??""}),S("name"),i("edit"))},[t,m]),L=Ct(async()=>{let x={name:s.name,trigger:{type:s.triggerType,...s.triggerType==="cron"?{cron:s.cron}:{},...s.triggerType==="template_complete"&&s.targetTemplateId?{event:`template_complete:${s.targetTemplateId}`}:{}},steps:[{id:"step-1",prompt:s.stepPrompt}],enabled:!0};try{a==="create"?(await v("/task-templates",{method:"POST",body:x}),l(`Created: ${s.name}`,"success")):a==="edit"&&b&&(await v(`/task-templates/${b}`,{method:"PATCH",body:x}),l(`Updated: ${s.name}`,"success"))}catch(w){l(`Save failed: ${w instanceof Error?w.message:String(w)}`,"error")}i("list"),p({...Oo}),k(null),ie()},[s,a,b,ie]);return Ii((x,w)=>{if(et){if(w.escape){i("list"),p({...Oo}),k(null);return}if(w.return){let R=["name","triggerType","cron","stepPrompt"],ce=s.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:R.filter(M=>M!=="targetTemplateId"),me=ce.indexOf(f);if(me<ce.length-1){let M=me+1;if(ce[M]==="cron"&&s.triggerType!=="cron"&&M++,M<ce.length){S(ce[M]);return}}L();return}if(w.tab&&f==="triggerType"){p(R=>{let j=lr.indexOf(R.triggerType);return{...R,triggerType:lr[(j+1)%lr.length]}});return}if(w.tab&&f==="targetTemplateId"){p(R=>{let j=t.filter(M=>M.id!==b),ce=j.findIndex(M=>M.id===R.targetTemplateId),me=j[(ce+1)%j.length];return{...R,targetTemplateId:me?.id??""}});return}return}if(q){if(w.escape){yt();return}if(x==="D"&&w.shift){Be("with_tasks");return}if(x==="d"&&!w.shift){Be("template_only");return}return}if(w.escape||x==="q"){e();return}if(w.upArrow){d(R=>Math.max(0,R-1));return}if(w.downArrow){d(R=>Math.min(t.length-1,R+1));return}if(x==="t"){De();return}if(x==="d"&&!w.shift){ke();return}if(x==="e"){wt();return}if(x==="c"){p({...Oo}),S("name"),i("create");return}if(x==="s"||x===" "){pe();return}x==="r"&&(ie(),E())}),g?ee(W,{dimColor:!0,children:"Loading templates..."}):et?Y(Te,{flexDirection:"column",children:[Y(W,{bold:!0,children:[a==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),Y(Te,{marginTop:1,flexDirection:"column",children:[Y(Te,{children:[Y(W,{bold:f==="name",color:f==="name"?"cyan":void 0,children:["Name:"," "]}),f==="name"?ee(ar,{value:s.name,onChange:x=>p(w=>({...w,name:x})),placeholder:"template name"}):ee(W,{children:s.name||"(empty)"})]}),Y(Te,{children:[Y(W,{bold:f==="triggerType",color:f==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),ee(W,{children:s.triggerType}),f==="triggerType"&&ee(W,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),s.triggerType==="cron"&&Y(Te,{children:[Y(W,{bold:f==="cron",color:f==="cron"?"cyan":void 0,children:["Cron:"," "]}),f==="cron"?ee(ar,{value:s.cron,onChange:x=>p(w=>({...w,cron:x})),placeholder:"*/5 * * * *"}):ee(W,{children:s.cron||"(empty)"})]}),s.triggerType==="template_complete"&&Y(Te,{children:[Y(W,{bold:f==="targetTemplateId",color:f==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),ee(W,{children:(()=>{let x=t.find(w=>w.id===s.targetTemplateId);return x?x.name:s.targetTemplateId?`(id: ${s.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),f==="targetTemplateId"&&ee(W,{dimColor:!0,children:" (Tab to cycle)"})]}),Y(Te,{children:[Y(W,{bold:f==="stepPrompt",color:f==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),f==="stepPrompt"?ee(ar,{value:s.stepPrompt,onChange:x=>p(w=>({...w,stepPrompt:x})),placeholder:"What should this template do?"}):ee(W,{children:s.stepPrompt||"(empty)"})]})]}),ee(Te,{marginTop:1,children:ee(W,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):Y(Te,{flexDirection:"column",children:[Y(W,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),r&&ee(Te,{marginTop:1,children:Y(W,{color:r.type==="success"?"green":r.type==="error"?"red":"gray",children:[r.type==="success"?"\u2713 ":r.type==="error"?"\u2717 ":"\u2192 ",r.text]})}),t.length===0?ee(Te,{marginTop:1,children:ee(W,{dimColor:!0,children:"No templates found. Press c to create one."})}):ee(Te,{marginTop:1,flexDirection:"column",children:t.map((x,w)=>{let R=w===m,j=x.trigger?.type==="cron"&&x.trigger?.cron?Pi(x.trigger.cron):"",ce=new Set(x.steps?.filter(M=>M.roleId).map(M=>M.roleId)),me=x.steps?.length>1?`${x.steps.length} steps${ce.size>0?` / ${ce.size} roles`:""}`:`${x.steps?.length??0} step`;return Y(Te,{flexDirection:"column",children:[Y(Te,{children:[ee(W,{color:R?"cyan":void 0,bold:R,children:R?"> ":" "}),ee(W,{color:R?"cyan":void 0,bold:R,children:lo(x.name,24)}),ee(W,{dimColor:!0,children:lo(x.trigger?.type,10)}),wn.includes(x.trigger?.type??"manual")?ee(W,{color:x.enabled?"green":"gray",children:lo(x.enabled?"on":"off",6)}):ee(W,{dimColor:!0,children:lo("\u2014",6)}),ee(W,{dimColor:!0,children:lo(me,18)}),j&&Y(W,{dimColor:!0,children:["next: ",j]})]}),R&&Y(Ri,{children:[x.config?.delivery&&ee(Te,{marginLeft:4,marginTop:0,children:Y(W,{dimColor:!0,children:[" Delivery: ",x.config.delivery.mode,x.config.delivery.mode==="primary-artifact"&&x.config.delivery.primaryArtifact&&` (${x.config.delivery.primaryArtifact.stepId}/${x.config.delivery.primaryArtifact.key})`]})}),x.steps&&x.steps.length>1&&ee(Te,{flexDirection:"column",marginLeft:4,marginTop:0,children:x.steps.map((M,Dt)=>Y(Te,{children:[Y(W,{dimColor:!0,children:[" ",Dt+1,". "]}),ee(W,{dimColor:!0,children:M.id}),M.roleId&&Y(W,{color:"yellow",children:[" @",N[M.roleId]??M.roleId]}),M.dependsOn&&M.dependsOn.length>0&&Y(W,{dimColor:!0,children:[" (after: ",M.dependsOn.join(", "),")"]}),M.consumesFrom&&M.consumesFrom.length>0&&Y(W,{dimColor:!0,children:[" [consumes: ",M.consumesFrom.join(", "),"]"]}),M.consumesFromOptional&&M.consumesFromOptional.length>0&&Y(W,{dimColor:!0,children:[" [consumes?: ",M.consumesFromOptional.join(", "),"]"]}),M.persona&&Y(W,{dimColor:!0,children:[" [speak as: ",M.persona.speakAs,M.persona.voiceConstraints?` / ${M.persona.voiceConstraints}`:"","]"]}),M.outputContract&&Y(W,{dimColor:!0,children:[" [",M.outputContract.lengthTarget?`${M.outputContract.lengthTarget.min}-${M.outputContract.lengthTarget.max} ${M.outputContract.lengthTarget.unit}`:"",M.outputContract.format?` ${M.outputContract.format}`:"",M.outputContract.mustReferenceArtifacts?" ref-artifacts":"","]"]}),M.config&&Y(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))})]})]},x.id)})}),ee(Te,{marginTop:1,children:ee(W,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function lo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as St,Text as qe,useInput as Di}from"ink";import Mi from"ink-text-input";import{useEffect as $i,useState as Ut,useCallback as kn}from"react";import{jsx as Pe,jsxs as Et}from"react/jsx-runtime";function Bn({onBack:e}){let[t,o]=Ut([]),[g,n]=Ut(""),[m,d]=Ut(!0),[a,i]=Ut(!1),[s,p]=Ut(""),[f,S]=Ut(null),b=kn(()=>{d(!0),v("/webhooks").then(({webhooks:r,auth:l})=>{o(r),n(l),d(!1)}).catch(()=>d(!1))},[]);$i(()=>{b()},[b]);let k=kn(async r=>{if(r.trim())try{let l=await v(`/webhooks/${encodeURIComponent(r.trim())}`,{method:"POST"});S(`Triggered: ${l.executionId}`)}catch(l){S(`Trigger failed: ${l instanceof Error?l.message:String(l)}`)}},[]);return Di((r,l)=>{if(a){if(l.escape){i(!1),p("");return}if(l.return){k(s),i(!1),p("");return}return}if(l.escape||r==="q"){e();return}if(r==="t"){i(!0),p(""),S(null);return}r==="r"&&(b(),S(null))}),m?Pe(qe,{dimColor:!0,children:"Loading webhooks..."}):Et(St,{flexDirection:"column",children:[Et(qe,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),Et(qe,{dimColor:!0,children:["Auth: ",g]}),f&&Pe(St,{marginTop:1,children:Pe(qe,{color:"yellow",children:f})}),a&&Et(St,{marginTop:1,children:[Pe(qe,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Pe(Mi,{value:s,onChange:p,placeholder:"webhook name or ID"}),Pe(qe,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Pe(St,{marginTop:1,children:Pe(qe,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):Et(St,{marginTop:1,flexDirection:"column",children:[Pe(St,{children:Et(qe,{bold:!0,children:[Wt("NAME",24),Wt("DESCRIPTION",36),Wt("TRIGGER",28),"TAGS"]})}),t.map(r=>Et(St,{children:[Pe(qe,{children:Wt(r.displayName,24)}),Pe(qe,{dimColor:!0,children:Wt(Ni(r.description??"",34),36)}),Pe(qe,{dimColor:!0,children:Wt(r.trigger,28)}),Pe(qe,{dimColor:!0,children:r.tags?.join(", ")??""})]},r.name))]}),Pe(St,{marginTop:1,children:Pe(qe,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function Wt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Ni(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as it,Text as ge,useInput as _i}from"ink";import Li from"ink-text-input";import{useEffect as In,useState as pt,useCallback as cr}from"react";import{jsx as fe,jsxs as Qe}from"react/jsx-runtime";function Oi(e){return e>=4?"red":e===3?"yellow":"gray"}function Fi(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function qi(e){return new Date(e).toLocaleDateString()}function An({onBack:e}){let[t,o]=pt([]),[g,n]=pt(0),[m,d]=pt([]),[a,i]=pt(!0),[s,p]=pt(!1),[f,S]=pt(""),[b,k]=pt("all"),[r,l]=pt(null),[E,C]=pt(!1),A=cr(()=>{v("/agents").then(({agents:I})=>{o(I),i(!1)}).catch(()=>i(!1))},[]);In(()=>{A()},[A]);let X=t[g],Q=cr(()=>{X&&(C(!1),v(`/memories/${X.id}`).then(({memories:I})=>{d(I),l(null)}).catch(I=>l(`Failed: ${I instanceof Error?I.message:String(I)}`)))},[X]);In(()=>{X&&Q()},[X,Q]);let N=cr(async I=>{if(!(!X||!I.trim()))try{let Z=await v("/memories/query",{method:"POST",body:{agentId:X.id,prompt:I.trim()}});d(Z.memories),C(!0),l(`Search: ${Z.count} results`)}catch(Z){l(`Search failed: ${Z instanceof Error?Z.message:String(Z)}`)}},[X]),F=s,q=m.filter(I=>b==="all"?!0:b==="high"?I.importance>3:b==="medium"?I.importance===3:I.importance<3);return _i((I,Z)=>{if(F){if(Z.escape){p(!1),S("");return}if(Z.return){N(f),p(!1),S("");return}return}if(Z.escape||I==="q"){e();return}if(I==="a"){n(se=>(se+1)%Math.max(1,t.length));return}if(Z.leftArrow){n(se=>(se-1+t.length)%Math.max(1,t.length));return}if(Z.rightArrow){n(se=>(se+1)%Math.max(1,t.length));return}if(I==="s"){p(!0),S(""),l(null);return}if(I==="h"){k(se=>se==="high"?"all":"high");return}if(I==="m"){k(se=>se==="medium"?"all":"medium");return}if(I==="l"){k(se=>se==="low"?"all":"low");return}I==="r"&&Q()}),a?fe(ge,{dimColor:!0,children:"Loading agents..."}):t.length===0?Qe(it,{flexDirection:"column",children:[fe(ge,{dimColor:!0,children:"No agents found"}),fe(ge,{dimColor:!0,children:"Press Esc to go back"})]}):Qe(it,{flexDirection:"column",children:[fe(ge,{bold:!0,children:"Memories (Esc to go back)"}),Qe(it,{marginTop:1,children:[fe(ge,{children:"Agent: "}),fe(ge,{bold:!0,color:"cyan",children:X?.name??"?"}),Qe(ge,{dimColor:!0,children:[" (",g+1,"/",t.length,") [a/arrows to switch]"]})]}),fe(it,{children:Qe(ge,{dimColor:!0,children:["Filter: ",b==="all"?"all":b," | ",E?"search results":"all memories"," (",q.length,")"]})}),r&&fe(it,{children:fe(ge,{color:"yellow",children:r})}),s&&Qe(it,{marginTop:1,children:[fe(ge,{bold:!0,color:"cyan",children:"Search: "}),fe(Li,{value:f,onChange:S,placeholder:"search query..."}),fe(ge,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),q.length===0?fe(it,{marginTop:1,children:Qe(ge,{dimColor:!0,children:["No memories",b!=="all"?` matching filter '${b}'`:""]})}):fe(it,{marginTop:1,flexDirection:"column",children:q.map(I=>Qe(it,{marginBottom:0,children:[Qe(ge,{color:Oi(I.importance),bold:!0,children:[Fi(I.importance)," "]}),fe(ge,{dimColor:!0,children:En(I.type??"?",12)}),fe(ge,{dimColor:!0,children:En(`\xD7${I.retrievedCount??0}`,5)}),Qe(ge,{children:[Vi(I.content,55)," "]}),fe(ge,{dimColor:!0,children:qi(I.createdAt)}),I.score!==void 0&&Qe(ge,{dimColor:!0,children:[" (",I.score.toFixed(2),")"]})]},I.id))}),fe(it,{marginTop:1,children:fe(ge,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function En(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Vi(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ye,Text as ue,useInput as Ui}from"ink";import qo from"ink-text-input";import{useState as _e,useEffect as Pn,useCallback as dr}from"react";import{jsx as Ce,jsxs as he}from"react/jsx-runtime";var Rn={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"]},Wi={"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 Dn({onBack:e}){let{state:t}=tt(),[o,g]=_e({}),[n,m]=_e([]),[d,a]=_e(null),[i,s]=_e("view"),[p,f]=_e(0),[S,b]=_e(""),[k,r]=_e(null),[l,E]=_e(!1),[C,A]=_e([]),[X,Q]=_e({}),[N,F]=_e(0),[q,I]=_e(""),[Z,se]=_e(""),[ie,et]=_e(""),De=Object.values(Rn).flat(),pe=dr(()=>{v("/config").then(L=>{g(L.config),m(L.mutable)}).catch(L=>a(L.message)),v("/config/env-diff").then(L=>{A(L.diffs)}).catch(()=>{}),v("/config/env").then(L=>Q(L.env??{})).catch(()=>{})},[]);Pn(()=>{pe()},[pe]),Pn(()=>{t.configVersion>0&&pe()},[t.configVersion,pe]);let ke=dr(async()=>{let L=De[p];if(L){E(!0),r(null);try{let x=S,w=o[L];if(w&&typeof w.value=="number"&&(x=Number(S),isNaN(x))){r("Invalid number"),E(!1);return}let R=await v("/config",{method:"PATCH",body:{[L]:x}});R.updated.length>0&&(r(`Updated: ${L}`),pe()),R.errors.length>0&&r(R.errors[0]),s("view")}catch(x){r(`Failed: ${x instanceof Error?x.message:String(x)}`)}finally{E(!1)}}},[De,p,S,o,pe]),Be=Object.keys(X),yt=dr(async L=>{try{await v("/config/env",{method:"PUT",body:L}),r("Env vars saved"),pe()}catch(x){r(`Failed: ${x instanceof Error?x.message:String(x)}`)}},[pe]);if(Ui((L,x)=>{if(i==="edit"){if(x.escape){s("view");return}return}if(i==="env-list"){if(x.escape){s("view");return}if(x.upArrow&&N>0&&F(w=>w-1),x.downArrow&&N<Be.length-1&&F(w=>w+1),L==="a"){I(""),s("env-add-key");return}if(L==="d"&&Be.length>0){let w=Be[N],R={...X};delete R[w],yt(R),N>=Be.length-1&&N>0&&F(j=>j-1);return}if(x.return&&Be.length>0){et(X[Be[N]]??""),s("env-edit-value");return}return}if(i==="env-add-key"){if(x.escape){s("env-list");return}return}if(i==="env-add-value"){if(x.escape){s("env-list");return}return}if(i==="env-edit-value"){if(x.escape){s("env-list");return}return}if(x.escape||L==="q"){e();return}if(x.upArrow&&p>0&&f(w=>w-1),x.downArrow&&p<De.length-1&&f(w=>w+1),x.return||L==="e"){let w=De[p],R=o[w];R&&R.mutable?(b(String(R.value??"")),s("edit"),r(null)):R&&!R.mutable&&r("This setting requires a restart to change")}L==="v"&&(F(0),s("env-list"),r(null)),L==="r"&&(pe(),r("Refreshed")),L==="s"&&C.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{r("Synced to .env"),A([]),pe()}),L==="l"&&C.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{r("Loaded from .env"),pe()})}),d)return he(Ye,{flexDirection:"column",children:[he(ue,{color:"red",children:["Failed to load config: ",d]}),Ce(ue,{dimColor:!0,children:"Press Esc or q to return"})]});let wt=0;return he(Ye,{flexDirection:"column",children:[Ce(ue,{bold:!0,children:"Settings"}),k&&Ce(ue,{color:k.startsWith("Failed")||k.startsWith("This setting")?"yellow":"green",children:k}),C&&C.length>0&&he(Ye,{flexDirection:"column",marginBottom:1,children:[he(ue,{color:"yellow",children:[".env differs from DB (",C.length," key(s)): ",C.map(L=>L.envKey).join(", ")]}),Ce(ue,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Ce(Ye,{marginTop:1,flexDirection:"column",children:Object.entries(Rn).map(([L,x])=>he(Ye,{marginBottom:1,flexDirection:"column",children:[Ce(ue,{bold:!0,color:"cyan",children:L}),x.map(w=>{let R=o[w],ce=wt++===p,me=n.includes(w),M=Wi[w]??w,Dt=R?String(R.value??""):"...";return i==="edit"&&ce?he(Ye,{children:[he(ue,{color:"cyan",children:["> ",M,": "]}),Ce(qo,{value:S,onChange:b,onSubmit:()=>{ke()}}),l&&Ce(ue,{color:"yellow",children:" saving..."})]},w):he(Ye,{children:[he(ue,{color:ce?"cyan":"white",children:[ce?"> ":" ",me?" ":"\u{1F512} ",M,": "," "]}),Ce(ue,{color:me?"white":"gray",children:Dt}),!me&&Ce(ue,{dimColor:!0,children:" (restart required)"})]},w)})]},L))}),Ce(ue,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),i.startsWith("env")&&he(Ye,{flexDirection:"column",marginTop:1,children:[he(ue,{bold:!0,color:"cyan",children:["Environment Variables (",Be.length,")"]}),Be.length===0&&i==="env-list"&&Ce(ue,{dimColor:!0,children:" No env vars. Press a to add."}),Be.map((L,x)=>{let w=x===N;return i==="env-edit-value"&&w?he(Ye,{children:[he(ue,{color:"cyan",children:["> ",L," = "]}),Ce(qo,{value:ie,onChange:et,onSubmit:()=>{yt({...X,[L]:ie}),s("env-list")}})]},L):he(ue,{color:w&&i==="env-list"?"cyan":"white",children:[w&&i==="env-list"?"> ":" ",L," = ",X[L]]},L)}),i==="env-add-key"&&he(Ye,{children:[Ce(ue,{color:"green",children:" New key: "}),Ce(qo,{value:q,onChange:I,onSubmit:()=>{q.trim()&&(se(""),s("env-add-value"))}})]}),i==="env-add-value"&&he(Ye,{children:[he(ue,{color:"green",children:[" ",q," = "]}),Ce(qo,{value:Z,onChange:se,onSubmit:()=>{yt({...X,[q.trim()]:Z}),s("env-list")}})]}),Ce(ue,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as At,Text as Re,useInput as Gi}from"ink";import{useEffect as Hi,useState as ur,useCallback as ji}from"react";import{jsx as we,jsxs as Ht}from"react/jsx-runtime";function Mn({onBack:e}){let[t,o]=ur([]),[g,n]=ur(!0),[m,d]=ur(0),{message:a,setMessage:i,clearMessage:s}=Ge(),p=ji(()=>{n(!0),v("/plugins").then(({plugins:f})=>{o(f),n(!1)}).catch(()=>n(!1))},[]);return Hi(()=>{p()},[p]),Gi((f,S)=>{if(S.escape||f==="q"){e();return}if(S.upArrow){d(b=>Math.max(0,b-1));return}if(S.downArrow){d(b=>Math.min(t.length-1,b+1));return}f==="r"&&(p(),s())}),g?we(Re,{dimColor:!0,children:"Loading plugins..."}):Ht(At,{flexDirection:"column",children:[Ht(Re,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),a&&we(At,{marginTop:1,children:Ht(Re,{color:a.type==="success"?"green":a.type==="error"?"red":"gray",children:[a.type==="success"?"\u2713 ":a.type==="error"?"\u2717 ":"\u2192 ",a.text]})}),t.length===0?we(At,{marginTop:1,children:we(Re,{dimColor:!0,children:"No plugins installed."})}):Ht(At,{marginTop:1,flexDirection:"column",children:[Ht(At,{children:[we(Re,{dimColor:!0,children:" "}),we(Re,{dimColor:!0,children:Gt("Name",24)}),we(Re,{dimColor:!0,children:Gt("Scope",8)}),we(Re,{dimColor:!0,children:Gt("User",6)}),we(Re,{dimColor:!0,children:"Path"})]}),t.map((f,S)=>{let b=S===m,k=f.id.split("@")[0];return Ht(At,{children:[we(Re,{color:b?"cyan":void 0,bold:b,children:b?"> ":" "}),we(Re,{color:b?"cyan":void 0,bold:b,children:Gt(k,24)}),we(Re,{color:b?"cyan":void 0,bold:b,children:Gt(f.scope,8)}),we(Re,{color:f.globalEnabled?"green":"gray",children:Gt(f.globalEnabled?"on":"off",6)}),we(Re,{dimColor:!0,children:f.installPath})]},f.id)})]}),we(At,{marginTop:1,children:we(Re,{dimColor:!0,children:"r:refresh"})})]})}function Gt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as mr,Text as gr,useInput as Ki}from"ink";import{useState as zi}from"react";import{jsx as Pt,jsxs as $n}from"react/jsx-runtime";var Xi=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function Nn({onBack:e}){let[t,o]=zi("tasks");return Ki((g,n)=>{if(n.escape||g==="q"){e();return}if(g==="1"){o("tasks");return}if(g==="2"){o("automations");return}if(g==="3"){o("goals");return}}),$n(mr,{flexDirection:"column",children:[Pt(gr,{bold:!0,children:"Work Surface"}),Pt(gr,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Pt(mr,{gap:3,marginBottom:1,marginTop:1,children:Xi.map(g=>{let n=t===g.id;return Pt(mr,{children:$n(gr,{color:n?"cyan":"gray",bold:n,children:[n?"\u25CF":"\u25CB"," ",g.key,". ",g.label]})},g.id)})}),t==="tasks"&&Pt(No,{onBack:e}),t==="automations"&&Pt(Fo,{onBack:e}),t==="goals"&&Pt(Lo,{onBack:e})]})}import{Box as ne,Text as J,useInput as Qi}from"ink";import{useEffect as Yi,useState as co}from"react";import{jsx as V,jsxs as Se}from"react/jsx-runtime";var _n={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Ln({onBack:e}){let[t,o]=co([]),[g,n]=co(!0),[m,d]=co(0),[a,i]=co(null),[s,p]=co("");Yi(()=>{f()},[]);async function f(){try{let k=await v("/channels");o(k.channels)}catch{}n(!1)}async function S(k){if(t.find(l=>l.id===k)?.platform==="wechat")try{p("Starting WeChat QR login...");let l=await v(`/channels/${k}/wechat/qr-start`,{method:"POST"});if(l.qrcodeUrl){p(`Scan QR: ${l.qrcodeUrl}
10
+ Waiting for scan...`);let E=await v(`/channels/${k}/wechat/qr-wait`,{method:"POST",body:{sessionKey:l.sessionKey,timeoutMs:12e4}});p(E.message)}else p(l.message);f()}catch{p("WeChat connect failed")}else try{await v(`/channels/${k}/connect`,{method:"POST"}),p("Connecting..."),f()}catch{p("Connect failed")}}async function b(k){try{await v(`/channels/${k}/disconnect`,{method:"POST"}),p("Disconnected"),f()}catch{p("Disconnect failed")}}return Qi((k,r)=>{if(a){if(r.escape||k==="q"){i(null);return}if(k==="c"){S(a.id);return}if(k==="d"){b(a.id);return}return}if(r.escape){e();return}if(r.upArrow){d(l=>Math.max(0,l-1));return}if(r.downArrow){d(l=>Math.min(t.length-1,l+1));return}if(r.return&&t[m]){i(t[m]),p("");return}}),g?V(ne,{flexDirection:"column",children:V(J,{dimColor:!0,children:"Loading channels..."})}):a?Se(ne,{flexDirection:"column",children:[Se(ne,{marginBottom:1,children:[Se(J,{bold:!0,children:["Channel: ",a.name]}),V(J,{dimColor:!0,children:" (Esc to go back)"})]}),Se(ne,{flexDirection:"column",gap:0,children:[Se(J,{children:["ID: ",a.id]}),Se(J,{children:["Platform: ",a.platform]}),Se(J,{children:["Status: ",V(J,{color:_n[a.status]??"white",children:a.status})]}),Se(J,{children:["Enabled: ",a.enabled?"yes":"no"]}),Se(J,{children:["Messages: ",a.messageCount]}),Se(J,{children:["Config: ",JSON.stringify(a.config)]})]}),V(ne,{marginTop:1,children:V(J,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),s&&V(J,{color:"yellow",children:s})]}):Se(ne,{flexDirection:"column",children:[Se(ne,{marginBottom:1,children:[V(J,{bold:!0,children:"Channels"}),Se(J,{dimColor:!0,children:[" (",t.length," total) "]}),V(J,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?V(J,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):Se(ne,{flexDirection:"column",children:[Se(ne,{children:[V(ne,{width:3,children:V(J,{dimColor:!0,children:" "})}),V(ne,{width:12,children:V(J,{bold:!0,dimColor:!0,children:"ID"})}),V(ne,{width:16,children:V(J,{bold:!0,dimColor:!0,children:"Name"})}),V(ne,{width:12,children:V(J,{bold:!0,dimColor:!0,children:"Platform"})}),V(ne,{width:14,children:V(J,{bold:!0,dimColor:!0,children:"Status"})}),V(ne,{width:10,children:V(J,{bold:!0,dimColor:!0,children:"Enabled"})}),V(ne,{width:10,children:V(J,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((k,r)=>Se(ne,{children:[V(ne,{width:3,children:V(J,{children:r===m?">":" "})}),V(ne,{width:12,children:V(J,{inverse:r===m,children:k.id.slice(0,8)})}),V(ne,{width:16,children:V(J,{children:k.name})}),V(ne,{width:12,children:V(J,{children:k.platform})}),V(ne,{width:14,children:Se(J,{color:_n[k.status]??"white",children:[k.status==="connected"?"\u25CF":k.status==="error"?"\u2717":"\u25CB"," ",k.status]})}),V(ne,{width:10,children:V(J,{color:k.enabled?"green":"gray",children:k.enabled?"yes":"no"})}),V(ne,{width:10,children:V(J,{children:k.messageCount})})]},k.id))]})]})}import{Box as jt,Text as Ze,useInput as ea}from"ink";import{useEffect as ta,useState as uo,useCallback as oa}from"react";import{Box as D,Text as T,useInput as Ji}from"ink";import Je from"ink-text-input";import{useEffect as On,useState as G,useCallback as at}from"react";kr();import{Fragment as Vo,jsx as y,jsxs as B}from"react/jsx-runtime";var Zi=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function Fn({roleId:e,onBack:t}){let[o,g]=G(null),[n,m]=G([]),[d,a]=G(!0),[i,s]=G("view"),[p,f]=G(""),[S,b]=G(0),[k,r]=G(""),[l,E]=G([]),[C,A]=G(0),[X,Q]=G(new Set),[N,F]=G("inline"),[q,I]=G(""),[Z,se]=G(""),[ie,et]=G(""),[De,pe]=G([]),[ke,Be]=G(new Set),[yt,wt]=G(0),[L,x]=G("default"),[w,R]=G(""),[j,ce]=G(""),[me,M]=G("mode"),[Dt,Gn]=G([]),[Mt,Hn]=G(null),[jo,jn]=G([]),[$t,Ko]=G([]),[xr,zo]=G(""),[kt,fo]=G(0),[po,Tr]=G(""),[hr,yr]=G(""),[br,vr]=G(""),[xo,Xo]=G(0),[Yt,Cr]=G([]),[To,Qo]=G(0),[ho,yo]=G(!1),[Nt,Kn]=G(""),{message:$,setMessage:_}=Ge(),te=at(()=>{a(!0),v(`/roles/${e}`).then(({role:c,projectPlugins:h,workspacePath:u})=>{g(c),m(h??[]),Kn(u??""),f(c.cagPrompt??""),Q(new Set(c.allowedTools??[])),F(c.executionMode??"inline"),I(c.model??""),se(c.effortTier??""),et(c.maxBudgetUsd!=null?String(c.maxBudgetUsd):""),a(!1)}).catch(()=>a(!1))},[e]);On(()=>{te(),v("/config").then(c=>{let h=c.config["defaults.deniedReadPaths"]?.value;Array.isArray(h)&&Gn(h),Hn(c.sandbox),jn(c.osCapabilities?.registry??[])}).catch(()=>{})},[te]),On(()=>{F(o?.executionMode??"inline"),I(o?.model??""),se(o?.effortTier??""),et(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),x(o?.permissionMode??"default"),R((o?.allowedBashPatterns??[]).join(", ")),ce((o?.deniedBashPatterns??[]).join(", ")),Ko(o?.osCapabilities??[]);let c=o?.osCapabilities?.find(h=>h.id==="automation")?.targets??[];zo(c.join(", "))},[o?.id,o?.executionMode,o?.model,o?.effortTier,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let zn=at(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:p}}),_("CAG prompt saved","success"),s("view"),te()}catch(c){_(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,p,te,_]),Xn=at(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Ke}}),_("Directories saved","success"),s("view"),te()}catch(c){_(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,te,_]),Qn=at(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(X)}}),_("Tool permissions saved","success"),s("view"),te()}catch(c){_(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,X,te,_]),Yn=at(async()=>{if(!o)return;let c={executionMode:N};q!==void 0&&(c.model=q),c.effortTier=Z===""?null:Z;let h=parseFloat(ie);isNaN(h)||(c.maxBudgetUsd=h);try{await v(`/roles/${o.id}`,{method:"PATCH",body:c}),_("Execution config saved","success"),s("view"),te()}catch(u){_(`Save failed: ${u instanceof Error?u.message:String(u)}`,"error")}},[o,N,q,Z,ie,te,_]),Jn=at(async()=>{if(!o)return;let c={permissionMode:L},h=w.split(",").map(P=>P.trim()).filter(Boolean),u=j.split(",").map(P=>P.trim()).filter(Boolean);c.allowedBashPatterns=h.length>0?h:[],c.deniedBashPatterns=u.length>0?u:[];try{await v(`/roles/${o.id}`,{method:"PATCH",body:c}),_("Permission config saved","success"),s("view"),te()}catch(P){_(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[o,L,w,j,te,_]),Sr=at(c=>{let h=new Map;for(let u of c){if(!u.id)continue;let P={id:u.id};u.targets?.length&&(P.targets=Array.from(new Set(u.targets.map(O=>O.trim()).filter(Boolean)))),h.set(u.id,P)}return Array.from(h.values()).sort((u,P)=>u.id.localeCompare(P.id))},[]),Zn=at(async()=>{if(!o)return;let c=Sr($t),h=c.find(u=>u.id==="automation")?.targets??[];if(c.some(u=>u.id==="automation")&&(h.length===0||h.some(u=>!Zi.test(u)))){_("Automation requires valid bundle id targets","error");return}try{await v(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:c}}),_("OS capabilities saved","success"),s("view"),te()}catch(u){_(`Save failed: ${u instanceof Error?u.message:String(u)}`,"error")}},[o,$t,Sr,te,_]),es=at(async c=>{if(!Nt){_("workspace path not loaded yet","error");return}yo(!0);try{await v(`/plugins/install/${encodeURIComponent(c)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:Nt})}),_(`Bound ${c.split("@")[0]}`,"success"),te()}catch(h){_(`Bind failed: ${h instanceof Error?h.message:"unknown"}`,"error")}finally{yo(!1)}},[Nt,te,_]),ts=at(async c=>{if(!Nt){_("workspace path not loaded yet","error");return}yo(!0);try{await v(`/plugins/uninstall/${encodeURIComponent(c)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:Nt})}),_(`Unbound ${c.split("@")[0]}`,"success"),te()}catch(h){_(`Unbind failed: ${h instanceof Error?h.message:"unknown"}`,"error")}finally{yo(!1)}},[Nt,te,_]),Ke=o?.additionalDirectories??[];if(Ji((c,h)=>{if(h.escape){s("view");return}if(c==="r"){te();return}switch(i){case"view":{if(c==="c"){s("edit-cag");return}if(c==="d"){s("edit-dirs"),b(0),r("");return}if(c==="t"){s("edit-tools");return}if(c==="o"){s("edit-oscaps");return}if(c==="x"){s("edit-exec");return}if(c==="h"){v("/channels?enabled=true").then(({channels:u})=>{pe(u.map(P=>({name:P.name,id:P.id}))),Be(new Set(o?.allowedChannels??[])),wt(0),s("edit-channels")}).catch(()=>_("Failed to load channels","error"));return}if(c==="p"){x(o?.permissionMode??"default"),R((o?.allowedBashPatterns??[]).join(", ")),ce((o?.deniedBashPatterns??[]).join(", ")),M("mode"),s("edit-permissions");return}if(c==="v"){fo(0),s("edit-env");return}if(c==="b"){Xo(0),s("edit-plugins");return}if(c==="i"){if(!o)return;let u=!o.inheritUserSettings;v(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:u}}).then(()=>{_(`Inherit user settings: ${u?"ON":"OFF"}`,"success"),te()}).catch(()=>_("Failed to toggle","error"));return}if(c==="R"&&o?.presetId){v(`/presets/role/${o.presetId}/restore`,{method:"POST"}).then(()=>{_("Preset restored","success"),te()}).catch(u=>_(`Restore failed: ${u instanceof Error?u.message:String(u)}`,"error"));return}break}case"edit-cag":{if(h.ctrl&&c==="s"){zn();return}break}case"edit-dirs":{if(c==="s"){Xn();return}if(c==="a"){s("edit-dirs-add");return}if(c==="m"&&Ke.length>0){let u=Ke[S];if(u){g(O=>O&&{...O,additionalDirectories:O.additionalDirectories?.map((de,ct)=>ct===S?{...typeof de=="string"?{path:de}:de,mode:de.mode==="ro"?"rw":"ro"}:de)});let P=u.mode==="ro"?"rw":"ro";_(`Mode set to ${P.toUpperCase()}`,"success")}return}if(c==="x"&&Ke.length>0){g(u=>u&&{...u,additionalDirectories:Ke.filter((P,O)=>O!==S)}),b(u=>Math.max(0,Math.min(u,Ke.length-2)));return}if(h.upArrow){b(u=>Math.max(0,u-1));return}if(h.downArrow){b(u=>Math.min(Ke.length-1,u+1));return}break}case"edit-dirs-add":{if(h.escape){s("edit-dirs"),r(""),E([]);return}if(h.return&&l.length>0){let u=l[C];u&&(r(u.endsWith("/")?u:u+"/"),E([]));return}if(h.return){let u=k.trim();u&&u.startsWith("/")?(g(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:u,mode:"rw"}]}),r(""),E([]),s("edit-dirs")):_("Path must be absolute (must start with /)","error");return}if(h.tab){let u=k.trim();if(!u||!u.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(u)}`).then(({suggestions:P})=>{P.length===1?(r(P[0]+"/"),E([])):P.length>1&&(E(P),A(0))}).catch(()=>{E([])});return}if(h.upArrow&&l.length>0){A(u=>Math.max(0,u-1));return}if(h.downArrow&&l.length>0){A(u=>Math.min(l.length-1,u+1));return}break}case"edit-tools":{if(c==="s"){Qn();return}let u=parseInt(c,10)-1;if(!isNaN(u)&&u>=0&&u<bo.length){let P=bo[u];Q(O=>{let de=new Set(O);return de.has(P)?de.delete(P):de.add(P),de});return}break}case"edit-oscaps":{if(c==="s"){Zn();return}if(c==="a"&&$t.some(O=>O.id==="automation")){let O=$t.find(de=>de.id==="automation")?.targets??[];zo(O.join(", ")),s("edit-oscaps-targets");return}let u=jo.filter(O=>O.editable),P=parseInt(c,10)-1;if(!isNaN(P)&&P>=0&&P<u.length){let O=u[P];Ko(de=>de.some(Jt=>Jt.id===O.id)?de.filter(Jt=>Jt.id!==O.id):[...de,{id:O.id,targets:O.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(h.return){let u=xr.split(",").map(P=>P.trim()).filter(Boolean);Ko(P=>P.map(O=>O.id==="automation"?{...O,targets:u}:O)),s("edit-oscaps");return}break}case"edit-exec":{if(c==="s"){Yn();return}if(h.tab){F(u=>u==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(c==="s"){Jn();return}if(h.tab){M(u=>u==="mode"?"allowed":u==="allowed"?"denied":"mode");return}if(me==="mode"&&(h.upArrow||h.downArrow)){let u=["default","acceptEdits","dontAsk","bypassPermissions"],P=u.indexOf(L);h.upArrow&&x(u[Math.max(0,P-1)]),h.downArrow&&x(u[Math.min(u.length-1,P+1)]);return}break}case"edit-channels":{if(c==="s"){if(!o)return;let u=ke.size>0?Array.from(ke):[];v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:u}}).then(()=>{_("Channels saved","success"),s("view"),te()}).catch(()=>_("Save failed","error"));return}if(c==="u"){if(!o)return;v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{_("Channels: unrestricted","success"),s("view"),te()}).catch(()=>_("Save failed","error"));return}if(c===" "){let u=De[yt];u&&Be(P=>{let O=new Set(P);return O.has(u.name)?O.delete(u.name):O.add(u.name),O});return}if(h.upArrow){wt(u=>Math.max(0,u-1));return}if(h.downArrow){wt(u=>Math.min(De.length-1,u+1));return}break}case"edit-env":{let u=Object.keys(o?.envVars??{});if(c==="a"){Tr(""),s("edit-env-add-key");return}if(c==="d"&&u.length>0){let P=u[kt],O={...o?.envVars??{}};delete O[P],v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{_("Deleted","success"),te()}).catch(()=>_("Delete failed","error")),kt>=u.length-1&&kt>0&&fo(de=>de-1);return}if(h.return&&u.length>0){vr((o?.envVars??{})[u[kt]]??""),s("edit-env-edit-value");return}h.upArrow&&kt>0&&fo(P=>P-1),h.downArrow&&kt<u.length-1&&fo(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break;case"edit-plugins":{if(ho)return;if(c==="a"){v("/plugins").then(({plugins:u})=>{let P=new Set(n.map(O=>O.id));Cr(u.filter(O=>!P.has(O.id))),Qo(0),s("edit-plugins-add")}).catch(()=>_("Failed to load plugins","error"));return}if(c==="x"&&n.length>0){let u=n[xo];u&&ts(u.id);return}if(h.upArrow){Xo(u=>Math.max(0,u-1));return}if(h.downArrow){Xo(u=>Math.min(n.length-1,u+1));return}break}case"edit-plugins-add":{if(ho)return;if(h.escape){s("edit-plugins"),Cr([]);return}if(h.return&&Yt.length>0){let u=Yt[To];u&&es(u.id);return}if(h.upArrow){Qo(u=>Math.max(0,u-1));return}if(h.downArrow){Qo(u=>Math.min(Yt.length-1,u+1));return}break}}}),d)return y(T,{dimColor:!0,children:"Loading role..."});if(!o)return y(T,{dimColor:!0,children:"Role not found."});if(i==="edit-plugins")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Plugins (\u2191\u2193 navigate, x:unbind a:add Esc:cancel)"}),ho&&y(T,{dimColor:!0,children:"Binding..."}),n.length===0?y(T,{dimColor:!0,children:"No plugins bound. Press a to add."}):n.map((c,h)=>B(D,{children:[B(T,{color:h===xo?"cyan":void 0,bold:h===xo,children:[h===xo?"> ":" ",c.name]}),B(T,{dimColor:!0,children:[" v",c.version]})]},c.id)),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i==="edit-plugins-add")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Add Plugin (\u2191\u2193 navigate, Enter:bind Esc:cancel)"}),ho&&y(T,{dimColor:!0,children:"Binding..."}),Yt.length===0?y(T,{dimColor:!0,children:"No available plugins."}):Yt.map((c,h)=>B(D,{children:[B(T,{color:h===To?"cyan":void 0,bold:h===To,children:[h===To?"> ":" ",c.name]}),B(T,{dimColor:!0,children:[" v",c.version]})]},c.id)),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i==="edit-cag")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),y(Je,{value:p,onChange:f,placeholder:"Character And Guidance prompt..."}),$&&y(D,{marginTop:1,children:y(T,{color:$.type==="error"?"red":"green",children:$.text})})]});if(i==="edit-dirs-add")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),y(Je,{value:k,onChange:c=>{r(c),E([])},placeholder:"/absolute/path/to/directory"}),l.length>0&&B(D,{flexDirection:"column",marginTop:1,children:[l.map((c,h)=>B(T,{color:h===C?"cyan":void 0,dimColor:h!==C,children:[h===C?"> ":" ",c,"/"]},c)),y(T,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),$&&y(D,{marginTop:1,children:y(T,{color:$.type==="error"?"red":"green",children:$.text})})]});if(i==="edit-dirs")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),Ke.length===0?y(T,{dimColor:!0,children:"No directories. Press a to add one."}):Ke.map((c,h)=>{let u=typeof c=="string"?{path:c,mode:"rw"}:c,P=u.mode!=="ro";return B(D,{children:[y(T,{color:h===S?"cyan":void 0,bold:h===S,children:h===S?"> ":" "}),B(T,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),y(T,{color:h===S?"cyan":void 0,children:u.path})]},u.path)})]});if(i==="edit-tools")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),bo.map((c,h)=>{let u=X.has(c);return B(D,{children:[B(T,{dimColor:!0,children:[h+1,". "]}),y(T,{color:u?"green":"red",children:u?"[ON] ":"[OFF] "}),y(T,{children:c})]},c)})]});if(i==="edit-oscaps"){let c=jo.filter(h=>h.editable);return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),Mt&&B(T,{dimColor:!0,children:["Platform: ",Mt.platform," ",Mt.available?"(sandbox active)":"(sandbox unavailable)"]}),jo.map(h=>{let u=c.findIndex(ct=>ct.id===h.id),P=$t.some(ct=>ct.id===h.id),O=u>=0?`${u+1}.`:" -",de=h.id==="automation"?(()=>{let ct=$t.find(Jt=>Jt.id===h.id)?.targets??[];return ct.length>0?` targets: ${ct.join(", ")}`:" targets: (none)"})():"";return B(D,{flexDirection:"column",marginBottom:1,children:[B(T,{color:P?"green":h.editable?"red":"gray",children:[O," ",P?"[ON]":"[OFF]"," ",h.label," [",h.availability,"]"]}),B(T,{dimColor:!0,children:[" ",h.description,de]}),h.effectiveDisabledReason&&!h.editable&&B(T,{dimColor:!0,children:[" ",h.effectiveDisabledReason]})]},h.id)}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]})}if(i==="edit-oscaps-targets")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),y(Je,{value:xr,onChange:zo,placeholder:"com.apple.mail, com.apple.systemevents"}),y(T,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i==="edit-exec")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(D,{children:[y(T,{bold:!0,children:" Mode: "}),y(T,{color:"cyan",children:N}),y(T,{dimColor:!0,children:" (Tab to toggle)"})]}),B(D,{children:[y(T,{bold:!0,children:" Model: "}),y(Je,{value:q,onChange:I,placeholder:"sonnet, opus, haiku, or blank"})]}),B(D,{children:[y(T,{bold:!0,children:" Effort Tier: "}),y(Je,{value:Z,onChange:se,placeholder:"low, medium, high, or blank to inherit"})]}),B(D,{children:[y(T,{bold:!0,children:" Max Budget (USD): "}),y(Je,{value:ie,onChange:et,placeholder:"0 = unlimited"})]}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i==="edit-permissions")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(D,{children:[y(T,{bold:!0,color:me==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(h=>B(T,{color:h===L?"green":"gray",children:[h===L?`[${h}]`:` ${h} `," "]},h))]}),B(D,{children:[y(T,{bold:!0,color:me==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),me==="allowed"?y(Je,{value:w,onChange:R,placeholder:"git add *, pnpm test*"}):y(T,{children:w||"(none)"})]}),B(D,{children:[y(T,{bold:!0,color:me==="denied"?"cyan":void 0,children:" Denied Bash: "}),me==="denied"?y(Je,{value:j,onChange:ce,placeholder:"rm -rf *, ssh *"}):y(T,{children:j||"(none)"})]}),y(T,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i==="edit-channels")return B(D,{flexDirection:"column",children:[y(T,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),De.length===0?y(T,{dimColor:!0,children:"No channels available"}):De.map((c,h)=>B(D,{children:[B(T,{children:[h===yt?">":" "," "]}),B(T,{color:ke.has(c.name)?"green":"gray",children:["[",ke.has(c.name)?"x":" ","] ",c.name]})]},c.id)),B(T,{dimColor:!0,children:["Selected: ",ke.size>0?Array.from(ke).join(", "):"none (= block all)"]}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})})]});if(i.startsWith("edit-env")){let c=Object.keys(o.envVars??{});return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Environment Variables (",c.length,")"]}),c.length===0&&i==="edit-env"&&y(T,{dimColor:!0,children:" No env vars. Press a to add."}),c.map((h,u)=>{let P=u===kt;return i==="edit-env-edit-value"&&P?B(D,{children:[B(T,{color:"cyan",children:["> ",h," = "]}),y(Je,{value:br,onChange:vr,onSubmit:()=>{let O={...o.envVars??{},[h]:br};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{_("Saved","success"),te(),s("edit-env")}).catch(()=>_("Save failed","error"))}})]},h):B(T,{color:P&&i==="edit-env"?"cyan":"white",children:[P&&i==="edit-env"?"> ":" ",h," = ",(o.envVars??{})[h]]},h)}),i==="edit-env-add-key"&&B(D,{children:[y(T,{color:"green",children:" New key: "}),y(Je,{value:po,onChange:Tr,onSubmit:()=>{po.trim()&&(yr(""),s("edit-env-add-value"))}})]}),i==="edit-env-add-value"&&B(D,{children:[B(T,{color:"green",children:[" ",po," = "]}),y(Je,{value:hr,onChange:yr,onSubmit:()=>{let h={...o.envVars??{},[po.trim()]:hr};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:h}}).then(()=>{_("Added","success"),te(),s("edit-env")}).catch(()=>_("Add failed","error"))}})]}),y(T,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),$&&y(T,{color:$.type==="error"?"red":"green",children:$.text})]})}return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Role: ",o.name]}),B(D,{children:[y(T,{dimColor:!0,children:"ID: "}),y(T,{children:o.id})]}),B(D,{children:[y(T,{dimColor:!0,children:"Status: "}),y(T,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&B(D,{children:[y(T,{dimColor:!0,children:"Score: "}),B(T,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"Created: "}),y(T,{children:new Date(o.createdAt).toLocaleString()})]}),B(D,{children:[y(T,{dimColor:!0,children:"Execution: "}),B(T,{children:[o.executionMode??"inline"," / tier:",o.effortTier??"\u2014"," / model:",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"OS Capabilities: "}),y(T,{children:(o.osCapabilities?.length??0)>0?o.osCapabilities.map(c=>c.id==="automation"&&c.targets?.length?`automation(${c.targets.join(",")})`:c.id).join(", "):"None"})]}),Mt&&B(D,{children:[y(T,{dimColor:!0,children:"Sandbox Platform: "}),B(T,{children:[Mt.platform," ",Mt.available?"(active)":"(unavailable)"]})]}),Ke.length>0&&B(Vo,{children:[y(T,{bold:!0,children:"Additional Directories:"}),Ke.map(c=>B(T,{dimColor:!0,children:[" ",c.path]},c.path))]}),B(D,{children:[y(T,{dimColor:!0,children:"Permission: "}),y(T,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(D,{children:[y(T,{dimColor:!0,children:" Bash Allow: "}),y(T,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(D,{children:[y(T,{dimColor:!0,children:" Bash Deny: "}),y(T,{children:o.deniedBashPatterns.join(", ")})]}),Dt.length>0&&B(D,{flexDirection:"column",children:[y(T,{dimColor:!0,children:"Denied Read Paths (global):"}),Dt.map(c=>B(T,{dimColor:!0,children:[" ",c]},c)),B(T,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(D,{children:[y(T,{dimColor:!0,children:"Channels: "}),y(T,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(D,{children:[y(T,{dimColor:!0,children:"Inherit User Settings: "}),y(T,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.stylePreferences.length>0&&B(Vo,{children:[y(T,{bold:!0,children:"Style Preferences:"}),o.learnedRules.stylePreferences.map(c=>B(T,{dimColor:!0,children:[" - ",c]},c))]}),o.learnedRules.avoidedActions.length>0&&B(Vo,{children:[y(T,{bold:!0,children:"Avoided Actions:"}),o.learnedRules.avoidedActions.map(c=>B(T,{dimColor:!0,children:[" - ",c]},c))]}),o.learnedRules.pinnedParameters.length>0&&B(Vo,{children:[y(T,{bold:!0,children:"Pinned Parameters:"}),o.learnedRules.pinnedParameters.map(c=>{let h=Object.entries(c.params).map(([P,O])=>`${P}=${JSON.stringify(O)}`).join(", "),u=c.condition?` [when: ${c.condition}]`:"";return B(T,{dimColor:!0,children:[" - ",c.tool," \u2192 ",h,u]},`${c.tool}-${c.pinnedAt}`)})]}),B(D,{children:[y(T,{dimColor:!0,children:"Plugins: "}),n.length===0?y(T,{dimColor:!0,children:"None"}):n.map(c=>B(T,{children:[c.name," "]},c.id))]}),$&&y(D,{children:y(T,{color:$.type==="error"?"red":$.type==="success"?"green":"gray",children:$.text})}),y(D,{marginTop:1,children:B(T,{dimColor:!0,children:["c:CAG d:dirs t:tools b:plugins o:oscaps x:exec p:perms h:channels v:env i:inherit"," ",o?.presetId?"R:restore-preset ":"","r:refresh Esc:back"]})})]})}import{jsx as Ve,jsxs as mo}from"react/jsx-runtime";function qn({onBack:e}){let[t,o]=uo([]),[g,n]=uo(!0),[m,d]=uo(0),[a,i]=uo("list"),[s,p]=uo(null),{message:f,setMessage:S,clearMessage:b}=Ge(),k=oa(()=>{n(!0),v("/roles").then(({roles:r})=>{o(r.map(l=>({id:l.id,name:l.name,status:l.status,performanceScore:l.performanceScore,createdAt:l.createdAt,presetId:l.presetId,contractComplianceEma:l.contractComplianceEma}))),n(!1)}).catch(()=>n(!1))},[]);return ta(()=>{k()},[k]),ea((r,l)=>{if(l.escape||r==="q"){e();return}if(l.upArrow){d(E=>Math.max(0,E-1));return}if(l.downArrow){d(E=>Math.min(t.length-1,E+1));return}if(r==="r"&&(k(),b()),r===`
11
+ `||r==="o"||r==="e"){t.length>0&&(p(t[m].id),i("detail"));return}}),g?Ve(Ze,{dimColor:!0,children:"Loading roles..."}):a==="detail"&&s?Ve(Fn,{roleId:s,onBack:()=>i("list")}):mo(jt,{flexDirection:"column",children:[mo(Ze,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),f&&Ve(jt,{marginTop:1,children:mo(Ze,{color:f.type==="success"?"green":f.type==="error"?"red":"gray",children:[f.type==="success"?"\u2713 ":f.type==="error"?"\u2717 ":"\u2192 ",f.text]})}),t.length===0?Ve(jt,{marginTop:1,children:Ve(Ze,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ve(jt,{marginTop:1,flexDirection:"column",children:t.map((r,l)=>{let E=l===m,C=r.performanceScore!=null?`${(r.performanceScore*100).toFixed(0)}%`:"\u2014",A=r.contractComplianceEma!=null?`[\u5951\u7EA6 ${r.contractComplianceEma.toFixed(2)}]`:"[\u5951\u7EA6 \u2014]";return mo(jt,{children:[Ve(Ze,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),Ve(Ze,{color:E?"cyan":void 0,bold:E,children:fr(r.name,24)}),r.presetId&&mo(Ze,{dimColor:!0,children:["[",r.presetId,"]"]}),Ve(Ze,{color:ra(r.status),children:fr(r.status,12)}),Ve(Ze,{dimColor:!0,children:fr(C,8)}),Ve(Ze,{dimColor:!0,children:A})]},r.id)})}),Ve(jt,{marginTop:1,children:Ve(Ze,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function ra(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function fr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as na,Text as pr}from"ink";import sa from"react";import{jsx as Uo,jsxs as aa}from"react/jsx-runtime";var Le={key:"Esc",label:"back"},ia={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},Le],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},Le],config:[Le],evolution:[Le],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},Le],strategies:[Le],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"},Le],webhooks:[Le],memories:[Le],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},Le],roles:[Le],settings:[Le],channels:[Le]};function Vn(){let{state:e}=tt(),t=ia[e.view]??[Le];return Uo(na,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,g)=>aa(sa.Fragment,{children:[g>0&&Uo(pr,{dimColor:!0,children:" "}),Uo(pr,{color:"cyan",children:o.key}),Uo(pr,{dimColor:!0,children:` ${o.label}`})]},`${o.key}-${o.label}`))})}import{Box as Kt,Text as je,useInput as la}from"ink";import{useEffect as ca,useState as Wo,useCallback as da}from"react";import{jsx as Tt,jsxs as xt}from"react/jsx-runtime";function Un({onBack:e}){let[t,o]=Wo([]),[g,n]=Wo(!0),[m,d]=Wo(0),[a,i]=Wo("all"),{message:s,setMessage:p}=Ge(),f=da(()=>{n(!0);let l=a!=="all"?`?status=${a}`:"";v(`/feature-requests${l}`).then(({featureRequests:E})=>{o(E),d(0),n(!1)}).catch(()=>n(!1))},[a]);ca(()=>{f()},[f]);let S=async(l,E)=>{try{await v(`/feature-requests/${l}/status`,{method:"PATCH",body:{status:E}}),p(`Marked as ${E}`,"success"),await f()}catch(C){p(`Failed: ${C instanceof Error?C.message:String(C)}`,"error")}},b=t;la((l,E)=>{if(E.escape||l==="q"){e();return}if(E.upArrow){d(A=>Math.max(0,A-1));return}if(E.downArrow){d(A=>Math.min(b.length-1,A+1));return}if(l==="r"){f();return}let C={0:"all",1:"new",2:"reviewed",3:"dismissed",4:"converted"};if(C[l]){i(C[l]);return}if(l==="s"&&b.length>0){let A=b[m];if(A&&A.status==="new"){S(A.id,"reviewed");return}}if(l==="d"&&b.length>0){let A=b[m];if(A){S(A.id,"dismissed");return}}if(l==="c"&&b.length>0){let A=b[m];if(A){S(A.id,"converted");return}}});let k=l=>l==="new"?"cyan":l==="reviewed"?"green":l==="dismissed"?"gray":l==="converted"?"yellow":"white",r=l=>{let E=Date.now()-l;if(Math.floor(E/6e4)<1)return"now";let A=Math.floor(E/36e5);return A<24?`${A}h ago`:`${Math.floor(A/24)}d ago`};return xt(Kt,{flexDirection:"column",children:[xt(je,{bold:!0,children:["Feature Requests (",b.length,") (Esc:back q:quit r:refresh)"]}),s&&Tt(Kt,{marginTop:1,children:xt(je,{color:s.type==="error"?"red":"green",children:[s.type==="success"?"\u2713 ":"\u2717 ",s.text]})}),Tt(je,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),Tt(je,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),g?Tt(je,{dimColor:!0,children:"Loading..."}):b.length===0?Tt(je,{dimColor:!0,children:"No feature requests found."}):Tt(Kt,{marginTop:1,flexDirection:"column",children:b.map((l,E)=>{let C=E===m,A=l.content.length>80?l.content.slice(0,80)+"...":l.content;return xt(Kt,{flexDirection:"column",children:[xt(Kt,{children:[Tt(je,{color:C?"cyan":void 0,bold:C,children:C?"> ":" "}),xt(je,{color:k(l.status),children:["[",l.status,"]"]}),xt(je,{dimColor:!0,children:[" ",r(l.extractedAt)]}),l.tags&&l.tags.length>0&&xt(je,{dimColor:!0,children:[" ",l.tags.slice(0,3).join(", ")]})]}),xt(Kt,{paddingLeft:4,flexDirection:"column",children:[l.summary&&Tt(je,{color:C?"cyan":"white",children:l.summary}),Tt(je,{dimColor:!0,children:A})]})]},l.id)})})]})}import{Box as zt,Text as Ue,useInput as ua}from"ink";import{useEffect as ma,useState as Go,useCallback as ga}from"react";import{jsx as ht,jsxs as lt}from"react/jsx-runtime";function Wn({onBack:e}){let[t,o]=Go([]),[g,n]=Go(!0),[m,d]=Go(0),[a,i]=Go("all"),{message:s,setMessage:p}=Ge(),f=ga(()=>{n(!0);let r=a!=="all"?`?status=${a}`:"";v(`/mistake-patterns${r}`).then(({mistakePatterns:l})=>{o(l),d(0),n(!1)}).catch(()=>n(!1))},[a]);ma(()=>{f()},[f]);let S=async(r,l)=>{try{await v(`/mistake-patterns/${r}`,{method:"PATCH",body:{status:l}}),p(`Marked as ${l}`,"success"),await f()}catch(E){p(`Failed: ${E instanceof Error?E.message:String(E)}`,"error")}};ua((r,l)=>{if(l.escape||r==="q"){e();return}if(l.upArrow){d(C=>Math.max(0,C-1));return}if(l.downArrow){d(C=>Math.min(t.length-1,C+1));return}if(r==="r"){f();return}let E={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(E[r]){i(E[r]);return}if(r==="a"&&t.length>0){let C=t[m];if(C&&C.status!=="acknowledged"){S(C.id,"acknowledged");return}}if(r==="d"&&t.length>0){let C=t[m];if(C&&C.status!=="dismissed"){S(C.id,"dismissed");return}}if(r==="n"&&t.length>0){let C=t[m];if(C&&C.status!=="new"){S(C.id,"new");return}}});let b=r=>r==="new"?"cyan":r==="acknowledged"?"green":r==="dismissed"?"gray":"white",k=r=>{let l=Date.now()-r;if(Math.floor(l/6e4)<1)return"now";let C=Math.floor(l/36e5);return C<24?`${C}h ago`:`${Math.floor(C/24)}d ago`};return lt(zt,{flexDirection:"column",children:[lt(Ue,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),s&&ht(zt,{marginTop:1,children:lt(Ue,{color:s.type==="error"?"red":"green",children:[s.type==="success"?"\u2713 ":"\u2717 ",s.text]})}),ht(Ue,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),ht(Ue,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),g?ht(Ue,{dimColor:!0,children:"Loading..."}):t.length===0?ht(Ue,{dimColor:!0,children:"No mistake patterns found."}):ht(zt,{marginTop:1,flexDirection:"column",children:t.map((r,l)=>{let E=l===m,C=r.dimensionValue.length>80?r.dimensionValue.slice(0,80)+"...":r.dimensionValue;return lt(zt,{flexDirection:"column",children:[lt(zt,{children:[ht(Ue,{color:E?"cyan":void 0,bold:E,children:E?"> ":" "}),lt(Ue,{color:b(r.status),children:["[",r.status,"]"]}),lt(Ue,{dimColor:!0,children:[" ",k(r.lastSeen)]}),lt(Ue,{dimColor:!0,children:[" [",r.dimensionType,"]"]}),lt(Ue,{dimColor:!0,children:[" ",r.roleIds.length," role(s)"]}),lt(Ue,{dimColor:!0,children:[" x",r.count]})]}),ht(zt,{paddingLeft:4,flexDirection:"column",children:ht(Ue,{color:E?"cyan":"white",children:C})})]},r.id)})})]})}import{Fragment as ba,jsx as z,jsxs as Qt}from"react/jsx-runtime";function Ta(){let{state:e,dispatch:t}=tt(),{session:o,sendMessage:g,createNewSession:n,archiveCurrentSession:m}=$r(),[d,a]=pa([]);Ho(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Rr();let{latestMessage:i}=_r(o?.id??null),s=Rt(null),p=Rt(new Set),f=Rt(new Set),S=Rt(new Set),b=Rt(new Set),[,k]=xa(I=>I+1,0);Ho(()=>{if(!i||i.id===s.current)return;s.current=i.id;let I=!i.kind||i.kind==="result_delivery"||i.kind==="assistant_text";if(I&&i.taskId&&f.current.has(i.taskId)){p.current.add(i.taskId);return}I&&i.taskId&&p.current.add(i.taskId),a(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:r,isStreaming:l,clearEvents:E}=Mr(e.activeTaskId),C=r[r.length-1],A=C?.type==="complete"&&!l,X=Rt(null),Q=Rt("");Ho(()=>{Q.current=r.filter(I=>I.type==="reasoning").map(I=>I.content).join("")},[r]),Ho(()=>{if(A&&e.activeTaskId!==X.current){if(X.current=e.activeTaskId,e.activeTaskId&&p.current.has(e.activeTaskId))return;let I=C?.content||Q.current;I&&(e.activeTaskId&&f.current.add(e.activeTaskId),a(Z=>[...Z,{role:"assistant",content:I,taskId:e.activeTaskId??void 0,kind:"assistant_text"}]))}},[A,C,e.activeTaskId]);let N=async I=>{let Z=I.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(Z)&&process.exit(0),I.startsWith("/")){let ie=I.slice(1),De={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins","feature-requests":"featureRequests",mistakes:"mistakes",back:"chat"}[ie];if(De){t({type:"SET_VIEW",view:De});return}if(ie==="new"){if(await m()){let ke=await n();a([]),E(),p.current.clear(),f.current.clear(),S.current.clear(),b.current.clear(),ke&&a([{role:"assistant",content:`Session archived. New session started: ${ke.id.slice(0,8)}`}])}return}if(ie==="session"){let pe=o?`Session: ${o.id}
12
+ Turns: ${o.messageCount}
13
+ Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";a(ke=>[...ke,{role:"assistant",content:pe}]);return}}if(a(ie=>[...ie,{role:"user",content:I}]),E(),!await g(I)){a(ie=>[...ie,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},F=d.some(I=>I.kind==="approval_prompt"&&I.promptId&&!S.current.has(I.promptId)&&!b.current.has(I.promptId)),q=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval&&!F;return Qt(go,{flexDirection:"column",paddingX:1,children:[z(Or,{}),Qt(go,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Qt(ba,{children:[z(tn,{messages:d,onApprovalSubmitted:I=>{S.current.add(I),k()},onApprovalFailed:I=>{b.current.add(I),k()}}),z(Vr,{events:r,isStreaming:l}),!e.connected&&!e.serverUnreachable&&z(go,{children:z(Xt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Qt(go,{flexDirection:"column",children:[z(Xt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),z(Xt,{dimColor:!0,children:"Check: adam server logs"}),z(Xt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&z(Nn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&z(No,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&z(xn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&z(bn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&z(Lo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&z(Cn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&z(Fo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&z(Bn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&z(An,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&z(Mn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&z(qn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&z(Un,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&z(Wn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&z(Dn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&z(Ln,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?z(rn,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?z(on,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):q?z(qr,{onSubmit:N}):z(Vn,{}),e.planTimeoutNotice&&z(ha,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function ha({planId:e,onDismiss:t}){return fa(o=>{o==="d"&&t()}),Qt(go,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Qt(Xt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),z(Xt,{dimColor:!0,children:" [d] Dismiss"})]})}function ya(){return z(Er,{children:z(Ta,{})})}export{ya as default};
@@ -0,0 +1 @@
1
+ import{c as a,d as b,e as c,f as d,g as e}from"./chunk-42V6ZPCS.js";import"./chunk-UFWMUBFH.js";import"./chunk-LU3D53ZV.js";import"./chunk-NPGZRSGL.js";import"./chunk-3KNR2F6H.js";import"./chunk-NWGRLNUM.js";import"./chunk-CLNYHWZ6.js";import"./chunk-BKNXRSJU.js";import"./chunk-RBJPQYV3.js";import"./chunk-KJNAORKM.js";import"./chunk-L7JP7DUO.js";import"./chunk-IRUR4DVD.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-L47LZYVG.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
@@ -0,0 +1 @@
1
+ import{a,b,d as c}from"./chunk-BKNXRSJU.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
@@ -0,0 +1 @@
1
+ import{P as a,Q as b,R as c,S as d,T as e,U as f,V as g}from"./chunk-6NWIZ3BH.js";import"./chunk-TLP4ZMJB.js";import"./chunk-J3VYLSJI.js";import"./chunk-XYZVMTNN.js";import"./chunk-ICAM2GUU.js";import"./chunk-TZCMK3UG.js";import"./chunk-SVUP3F4V.js";import"./chunk-FD4IKMXV.js";import"./chunk-F6U5TMM3.js";import"./chunk-D3SPXZZY.js";import"./chunk-ISKCTUI7.js";import"./chunk-DRO3DG7X.js";import"./chunk-XIVFVKMB.js";import"./chunk-XF7YHFVR.js";import"./chunk-LU3D53ZV.js";import"./chunk-NPGZRSGL.js";import"./chunk-QMW7VEPC.js";import"./chunk-XZEBYOFR.js";import"./chunk-VNXTBIPI.js";import"./chunk-RBJPQYV3.js";import"./chunk-KJNAORKM.js";import"./chunk-L7JP7DUO.js";import"./chunk-N2OLEUAQ.js";import"./chunk-IRUR4DVD.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-L47LZYVG.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-OQ3JOTPK.js";import"./chunk-APAOIZN4.js";import"./chunk-TLP4ZMJB.js";import"./chunk-J3VYLSJI.js";import"./chunk-XYZVMTNN.js";import"./chunk-I7LJ4432.js";import"./chunk-NUJSTEV4.js";import"./chunk-ICAM2GUU.js";import"./chunk-FD4IKMXV.js";import"./chunk-F6U5TMM3.js";import"./chunk-DRO3DG7X.js";import"./chunk-XIVFVKMB.js";import"./chunk-XF7YHFVR.js";import"./chunk-NNMQGISW.js";import"./chunk-UFWMUBFH.js";import"./chunk-LU3D53ZV.js";import"./chunk-NPGZRSGL.js";import"./chunk-3KNR2F6H.js";import"./chunk-NWGRLNUM.js";import"./chunk-CLNYHWZ6.js";import"./chunk-BKNXRSJU.js";import"./chunk-VNXTBIPI.js";import"./chunk-RBJPQYV3.js";import"./chunk-KJNAORKM.js";import"./chunk-L7JP7DUO.js";import"./chunk-IRUR4DVD.js";import"./chunk-VKKDSXMR.js";import"./chunk-ASPPM7TQ.js";import"./chunk-TLMG5W3L.js";import"./chunk-Z6LHGA27.js";import"./chunk-L47LZYVG.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunk-Y5FFL6UO.js";import"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
1
+ import{a,b,c,d,e,f}from"./chunk-CLNYHWZ6.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
@@ -0,0 +1 @@
1
+ import{i as a,j as b,k as c}from"./chunk-EVUZ5LH2.js";import"./chunk-XF7YHFVR.js";import"./chunk-NNMQGISW.js";import"./chunk-3KNR2F6H.js";import"./chunk-NWGRLNUM.js";import"./chunk-CLNYHWZ6.js";import"./chunk-BKNXRSJU.js";import"./chunk-ASPPM7TQ.js";import"./chunk-Z6LHGA27.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-245WE5AF.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-3BRHWRZ5.js";import"./chunk-BPXS4QEO.js";import"./chunk-WBAPIPST.js";import"./chunk-BLCNUT53.js";import"./chunk-FCV2DPZQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
@@ -0,0 +1 @@
1
+ import{c as o}from"./chunk-FCV2DPZQ.js";import{AsyncLocalStorage as a}from"async_hooks";import{v4 as c}from"uuid";function g(e,t){return r.run({traceId:c(),origin:e},t)}function S(e,t,n){return r.run({traceId:e,origin:t},n)}function d(){return r.getStore()?.traceId}function f(){return r.getStore()}var r,i=o(()=>{r=new a});export{g as a,S as b,d as c,f as d,i as e};
@@ -0,0 +1,9 @@
1
+ import{b as E,c as A,i as R}from"./chunk-ICAM2GUU.js";import{e as C,i as T}from"./chunk-VNXTBIPI.js";import{F as _,I}from"./chunk-KJNAORKM.js";import{l as w,n as F}from"./chunk-BPXS4QEO.js";I();T();import{existsSync as W,readdirSync as L,readFileSync as j}from"fs";import{join as P}from"path";function v(l){let s=l.split(`
2
+ `),n=s[0]??"";return n.startsWith("```yaml")||n.startsWith("```")?s.slice(1).join(`
3
+ `):l}function H(l){let s={},o=v(l).split(`
4
+ `);for(let t of o){let u=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*):\s*(.*)$/);if(u)s[u[1].toLowerCase()]=u[2].trim();else if(t.trim()&&!t.startsWith("#")&&!t.startsWith(" ")&&!t.startsWith(" "))break}return s}function M(l,s){let n=[];try{let o=C(s),t=P(o,".claude","skills");if(!W(t))return n;let u=L(t,{withFileTypes:!0});for(let e of u){if(!e.isDirectory()&&!e.isSymbolicLink())continue;let i=P(t,e.name,"SKILL.md");if(W(i))try{let a=j(i,"utf-8"),r=H(a),m=r.name??e.name,c=r.description??"";n.push({name:m,description:c,roleName:s,roleId:l,path:i,rawFrontmatter:r})}catch{}}}catch{}return n}F();var O=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","dare","ought","used","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","above","below","between","under","again","further","then","once","here","there","when","where","why","how","all","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","and","but","or","if","because","until","while","about","against","this","that","these","those","it","its"]);function S(l){return l.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(s=>s.length>1&&!O.has(s))}function g(l,s){if(s.length===0)return 0;let n=S(l),o=0;for(let t of s){n.includes(t)&&o++;for(let u of n)u.startsWith(t)&&u!==t&&(o+=.5)}return o}function D(l){let s=w(),n=new Map;if(l.length===0)return n;let o=l.map(()=>"?").join(","),t=s.prepare(`
5
+ SELECT rs.task_type, rs.score_json, t.status, t.error_category, t.completed_at, rs.created_at
6
+ FROM role_scores rs
7
+ JOIN tasks t ON t.id = rs.task_id
8
+ WHERE rs.task_type IN (${o})
9
+ `).all(...l),u=new Map;for(let e of t){let i=e.task_type,a=u.get(i);a||(a={successes:0,failures:0,lastSuccessAt:null,lastFailureAt:null,errorCounts:new Map},u.set(i,a));let r=JSON.parse(e.score_json);e.status==="completed"||r.taskSuccess===1?(a.successes++,e.completed_at?a.lastSuccessAt=e.completed_at:e.created_at&&(a.lastSuccessAt=e.created_at)):(a.failures++,e.completed_at&&(a.lastFailureAt=e.completed_at),e.error_category&&a.errorCounts.set(e.error_category,(a.errorCounts.get(e.error_category)??0)+1))}for(let[e,i]of u){let a=i.successes+i.failures,r=Array.from(i.errorCounts.entries()).map(([m,c])=>({category:m,count:c})).sort((m,c)=>c.count-m.count);n.set(e,{totalTasks:a,successCount:i.successes,failureCount:i.failures,successRate:a>0?i.successes/a:0,lastSuccessAt:i.lastSuccessAt,lastFailureAt:i.lastFailureAt,commonErrors:r})}return n}var k=null,y=0,z=3e4,x=class l{static build(s=!1){let n=Date.now();if(!s&&k&&n-y<z)return k;let o=[],t=_("active"),u=new Map,e=A();for(let r of e){if(!r.enabled)continue;let m=E(r.installPath);if(m)for(let c of m.skills){let d=[];for(let f of t){let h=u.get(f.id);h||(h=R(f),u.set(f.id,h)),h.plugins.some(b=>b.name===r.name||b.name===r.id)&&d.push({roleId:f.id,roleName:f.name})}let p=N(c.name,c.description);o.push({name:c.name,description:c.description,source:"plugin",sourceName:r.name??r.id,boundRoles:d,triggers:p,errorPatterns:c.error_patterns?.map(f=>({pattern:f.pattern,category:f.category,userAction:f.user_action}))})}}for(let r of t){let m=M(r.id,r.name);for(let c of m){let d=r.name==="adam-automator"?"adam-automator":"role-workspace",p=o.find(f=>f.name===c.name&&f.sourceName===c.roleName);if(p)p.boundRoles.some(f=>f.roleId===r.id)||p.boundRoles.push({roleId:r.id,roleName:r.name});else{let f=N(c.name,c.description);o.push({name:c.name,description:c.description,source:d,sourceName:c.roleName,boundRoles:[{roleId:r.id,roleName:r.name}],triggers:f})}}}k=o,y=n;let i=o.map(r=>r.name),a=D(i);for(let r of o){let m=a.get(r.name);m&&(r.health=m)}return o}static query(s){return l.build().filter(o=>{if(s.source&&o.source!==s.source||s.roleId&&!o.boundRoles.some(t=>t.roleId===s.roleId))return!1;if(s.query){let t=S(s.query),u=g(o.name,t),e=g(o.description,t),i=Math.max(...o.triggers.map(r=>g(r,t)));if(u+e+i===0)return!1}return!0})}static match(s,n=3){let o=l.build(),t=S(s);return t.length===0?[]:o.map(e=>{let i=g(e.name,t)*2,a=g(e.description,t),r=Math.max(...e.triggers.map(m=>g(m,t)*1.5));return{entry:e,score:i+a+r}}).filter(e=>e.score>0).sort((e,i)=>i.score-e.score).slice(0,n).map(e=>e.entry)}static invalidateCache(){k=null,y=0}};function N(l,s){let n=[];for(let t of l.split(/[_-]/))t.length>2&&n.push(t.toLowerCase());let o=s.slice(0,200).toLowerCase();for(let t of o.split(/\W+/))t.length>4&&n.push(t);return[...new Set(n)]}export{x as a};
@@ -0,0 +1,2 @@
1
+ import{l as e,n as s}from"./chunk-BPXS4QEO.js";s();import{v4 as u}from"uuid";var r,a;function i(){return r||(r=e().prepare(`INSERT INTO chat_tool_calls (id, trace_id, session_id, tool_name, tool_input_json, tool_output_summary, called_at)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)),r}function d(){return a||(a=e().prepare("SELECT * FROM chat_tool_calls WHERE trace_id = ? ORDER BY called_at ASC")),a}function I(t){let o=u(),n=t.calledAt??Date.now(),l=t.toolInput!==void 0?JSON.stringify(t.toolInput):null;return i().run(o,t.traceId,t.sessionId??null,t.toolName,l,t.toolOutputSummary??null,n),{id:o,traceId:t.traceId,sessionId:t.sessionId,toolName:t.toolName,toolInput:t.toolInput,toolOutputSummary:t.toolOutputSummary,calledAt:n}}function g(t){return d().all(t).map(n=>({id:n.id,traceId:n.trace_id,sessionId:n.session_id??void 0,toolName:n.tool_name,toolInput:n.tool_input_json?c(n.tool_input_json):void 0,toolOutputSummary:n.tool_output_summary??void 0,calledAt:n.called_at}))}function f(t,o){if(o.length===0)return!1;let l=`SELECT 1 FROM chat_tool_calls WHERE trace_id = ? AND tool_name IN (${o.map(()=>"?").join(",")}) LIMIT 1`;return e().prepare(l).get(t,...o)!==void 0}function c(t){try{return JSON.parse(t)}catch{return}}export{I as a,g as b,f as c};
@@ -0,0 +1,3 @@
1
+ import{b as m}from"./chunk-NWGRLNUM.js";import{b as a}from"./chunk-CLNYHWZ6.js";import{a as d,d as f}from"./chunk-BKNXRSJU.js";import{a as s}from"./chunk-ASPPM7TQ.js";import{d as p}from"./chunk-Z6LHGA27.js";import{c,h as g}from"./chunk-BLCNUT53.js";function k(e,n,i){switch(n){case"wechat":return l(e);case"telegram":return e;case"slack":return w(e);case"email":return e;case"webhook":return JSON.stringify({result:e,taskId:i,timestamp:new Date().toISOString()});default:return l(e)}}function l(e){return e.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,n=>n.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
2
+
3
+ `).trim()}function w(e){return e.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}f();g();var t=c("message-handler");function x(){try{let e=p().identity?.ownerViewerKey;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return s.identity?.ownerViewerKey??"local-owner"}function u(e){if(e.type==="web"||e.type==="tui"||e.type==="api")return x();if(e.type!=="channel"||!e.channelId){t.warn({source:e},"Viewer identity unavailable for chat source"),r("chat source has no resolvable viewer identity",void 0);return}let i=a(e.channelId)?.viewerKey;if(typeof i=="string"&&i.trim().length>0)return i;t.warn({channelId:e.channelId},"Channel viewerKey missing; recent delivery context disabled"),r("channel viewerKey missing; recent delivery context disabled",e.channelId)}function E(e){if(e.type==="channel"){let o=a(e.channelId)?.viewerKey;if(typeof o=="string"&&o.trim().length>0)return o;t.warn({channelId:e.channelId},"Channel viewerKey missing; ledger recording skipped"),r("channel viewerKey missing; ledger recording skipped",e.channelId);return}let n=m(e.sessionId);if(!n){t.warn({sessionId:e.sessionId},"Session target missing; ledger recording skipped"),r("session target missing; ledger recording skipped",e.sessionId);return}return u(n.source)}function r(e,n){try{d({source:"viewer_identity",severity:"warning",sourceId:n,message:e})}catch{}}import v from"path";var h={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".md":"text/markdown",".html":"text/html",".json":"application/json",".xml":"text/xml",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},y={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv","text/markdown":".md","audio/mp3":".mp3","text/html":".html","application/json":".json","application/xml":".xml","text/xml":".xml","application/vnd.openxmlformats-officedocument.wordprocessingml.document":".docx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":".xlsx","application/vnd.openxmlformats-officedocument.presentationml.presentation":".pptx","application/msword":".doc","application/vnd.ms-excel":".xls","application/vnd.ms-powerpoint":".ppt"};function $(e){let n=v.extname(e).toLowerCase();return h[n]??"application/octet-stream"}function F(e){let n=e.split(";")[0].trim().toLowerCase();return y[n]??".bin"}export{k as a,l as b,x as c,u as d,E as e,$ as f,F as g};
@@ -0,0 +1,5 @@
1
+ import{e as y}from"./chunk-UFWMUBFH.js";import{b as m}from"./chunk-CLNYHWZ6.js";import{c as h,h as w}from"./chunk-BLCNUT53.js";w();var v="",I=Buffer.alloc(0);function O(o){v=o,I=Buffer.from(o)}function g(){return v}function C(){return I}var p=h("channels"),u=new Map,x=3e5,$=new Set(["telegram"]);function T(o){let e=o.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,r=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:r?"allow":"deny"}}function P(o){let n=m(o);return n?$.has(n.platform):!1}var b={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},k={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function _(o){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of o.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let r=e.description.indexOf(": "),s=r>0?e.description.slice(0,r):"Operation";if(n.push(`\u64CD\u4F5C: ${s}`),s==="Bash"&&r>0)try{let t=JSON.parse(e.description.slice(r+2));if(t.command){let i=String(t.command).trim();n.push(`\u547D\u4EE4: ${i.length>120?i.slice(0,117)+"...":i}`)}}catch{let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}else if(r>0){let t=e.description.slice(r+2,r+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>r+122?"...":""}`)}}let c=b[e.riskLevel]??"\u{1F7E1}",l=k[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
2
+ `).trimEnd()}async function q(o,n,e,c,l,r=x){let s=e,t=s.slice(0,8);u.set(t,{planId:e,taskId:c,channelId:o,chatId:n,requestId:s,timestamp:Date.now(),timeoutMs:r});let i=y(),d=P(o);if(d){let a=`${l}
3
+
4
+ `;await i.send({channelId:o,chatId:n,content:a,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${t}`},{text:"\u274C Deny",callbackData:`no ${t}`}]]}})}else{let a=[l,"",`Reply 'yes ${t}' or 'no ${t}'`].join(`
5
+ `);await i.send({channelId:o,chatId:n,content:a,messageType:"approval"})}setTimeout(()=>{let a=u.get(t);if(a&&Date.now()-a.timestamp>=a.timeoutMs){u.delete(t),p.warn({requestId:s,shortId:t,taskId:c},"Approval timed out, auto-denying"),i.send({channelId:a.channelId,chatId:a.chatId,content:`\u23F0 Approval ${t} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(f=>p.error({requestId:s,error:f},"Failed to notify timeout"));let A=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${A}/tasks/${a.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":g()},body:JSON.stringify({planId:a.planId,decision:"deny"})}).catch(f=>p.error({requestId:s,error:f},"Failed to auto-deny"))}},r+1e3),p.info({channelId:o,chatId:n,planId:e,shortId:t,interactive:d},"Interactive approval sent to channel")}async function B(o,n,e,c){let r=T(c??e);if(!r)return!1;let{requestId:s,decision:t}=r,i=u.get(s);if(!i)return!1;if(i.channelId!==o||i.chatId!==n)return p.debug({shortId:s,expectedChannel:i.channelId,gotChannel:o},"Approval reply from different channel"),!1;u.delete(s),p.info({shortId:s,requestId:i.requestId,decision:t},"Channel approval reply received");try{let d=process.env.ADAM_PORT??"7100",a=await fetch(`http://localhost:${d}/tasks/${i.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":g()},body:JSON.stringify({planId:i.planId,decision:t}),signal:AbortSignal.timeout(1e4)});a.ok||p.error({shortId:s,status:a.status},"Failed to forward approval to API")}catch(d){p.error({shortId:s,error:d},"Error forwarding approval to API")}return!0}function D(){return[...u.keys()]}export{O as a,C as b,T as c,_ as d,q as e,B as f,D as g};