adam-agent-server 1.3.0 → 1.4.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 (135) hide show
  1. package/README.md +22 -9
  2. package/dist/App-JGH6G5US.js +13 -0
  3. package/dist/adam-tools-KTLBI4PA.js +1 -0
  4. package/dist/{approval-handler-RIJO3OBO.js → approval-handler-JZSXM4AD.js} +1 -1
  5. package/dist/audit-manager-BPJEAX22.js +1 -0
  6. package/dist/bree-engine-CRK73AI4.js +1 -0
  7. package/dist/{channels-LUJ7GTSP.js → channels-PUOPR5Y2.js} +1 -1
  8. package/dist/channels-WMTZJAO4.js +1 -0
  9. package/dist/{chunk-7IXLL673.js → chunk-24GTCFEV.js} +1 -1
  10. package/dist/{chunk-DBUEHITK.js → chunk-3567PCEJ.js} +1 -1
  11. package/dist/{chunk-4MJF77RD.js → chunk-4VHBKJD5.js} +3 -2
  12. package/dist/{chunk-AKPLOO2V.js → chunk-6THDALGC.js} +1 -1
  13. package/dist/{chunk-IZGTTLTG.js → chunk-7BSWC62F.js} +1 -1
  14. package/dist/{chunk-WTRM5VO7.js → chunk-CKIVKM5T.js} +2 -2
  15. package/dist/chunk-DBI36EGR.js +83 -0
  16. package/dist/{chunk-4NW2DNDZ.js → chunk-DMZM7RU6.js} +1 -1
  17. package/dist/{chunk-NUTUI5KM.js → chunk-EZGMA3VV.js} +1 -1
  18. package/dist/{chunk-AZBNUSM2.js → chunk-GYHOPV4Q.js} +1 -1
  19. package/dist/chunk-HQ66TFYI.js +12 -0
  20. package/dist/{chunk-YPOTHL7X.js → chunk-HYDCXE5K.js} +1 -1
  21. package/dist/{chunk-ZQYKT5UY.js → chunk-I5IUTZA3.js} +1 -1
  22. package/dist/{chunk-XTHP5JMO.js → chunk-I67UMGJM.js} +1 -1
  23. package/dist/chunk-J3NIPZ73.js +8 -0
  24. package/dist/{chunk-TKDT7EQO.js → chunk-JKPSEMUZ.js} +1 -1
  25. package/dist/{chunk-CLHSPXZ6.js → chunk-KO5AFX5U.js} +1 -1
  26. package/dist/chunk-KOWFPY2J.js +1 -0
  27. package/dist/{chunk-NDP6LWXX.js → chunk-L4Y3GR6W.js} +1 -1
  28. package/dist/{chunk-NLD7WK3R.js → chunk-NOUSHXGX.js} +1 -1
  29. package/dist/{chunk-P6KWAGAY.js → chunk-NZEDILAK.js} +1 -1
  30. package/dist/{chunk-WKS7QVIX.js → chunk-QQWRV23T.js} +1 -1
  31. package/dist/{chunk-TCHBOWQ5.js → chunk-RUY23IJK.js} +1 -1
  32. package/dist/{chunk-IKUBP3SY.js → chunk-T7GEINGZ.js} +2 -2
  33. package/dist/chunk-WRETNOC3.js +99 -0
  34. package/dist/{chunk-JZNBFZ7W.js → chunk-XAMLLKKA.js} +1 -1
  35. package/dist/{chunk-4LSIHSCO.js → chunk-XF4IERYF.js} +1 -1
  36. package/dist/{chunk-HFN7Y3IM.js → chunk-YHH3QMLL.js} +1 -1
  37. package/dist/{chunk-7CJGPCSJ.js → chunk-ZRUVORAJ.js} +1 -1
  38. package/dist/cli.js +2 -2
  39. package/dist/{config-HR4MBTIS.js → config-CBNOT66B.js} +1 -1
  40. package/dist/{db-6KUGCGVR.js → db-XQUI4IBL.js} +1 -1
  41. package/dist/{delivery-log-7DJJTPXL.js → delivery-log-T56ZYDWO.js} +1 -1
  42. package/dist/engine-7DFJOADQ.js +1 -0
  43. package/dist/{evolution-audit-I2ITWAEC.js → evolution-audit-JZ2U7J4C.js} +1 -1
  44. package/dist/index.js +10 -10
  45. package/dist/learner-4EO7ZKK4.js +1 -0
  46. package/dist/{memories-HBBW44MG.js → memories-EKREXLT6.js} +1 -1
  47. package/dist/{memory-extractor-XO2HJ22Y.js → memory-extractor-JO7OHBZP.js} +2 -2
  48. package/dist/memory-service-Y3HVQYHM.js +1 -0
  49. package/dist/outbound-gateway-U5LP54JG.js +1 -0
  50. package/dist/role-presets-HWZHXBBA.js +1 -0
  51. package/dist/roles-3AEHVOEW.js +1 -0
  52. package/dist/{session-manager-JICVE4CO.js → session-manager-PWJLU6KZ.js} +1 -1
  53. package/dist/{task-templates-NC7XIZIC.js → task-templates-ED2UCUPE.js} +1 -1
  54. package/dist/workflow-executor-XFTTJQNE.js +1 -0
  55. package/package.json +2 -2
  56. package/web/dist/assets/AlertDialog-r3y6IhpW.js +51 -0
  57. package/web/dist/assets/Button-BjXgrQ95.js +1 -0
  58. package/web/dist/assets/Card-C153tGfJ.js +1 -0
  59. package/web/dist/assets/ChannelDetail-C2uAZv1u.js +1 -0
  60. package/web/dist/assets/Channels-C62Qrg-n.js +12 -0
  61. package/web/dist/assets/Chat-kH2owmB_.js +1 -0
  62. package/web/dist/assets/Dashboard-BhD8SpFb.js +1 -0
  63. package/web/dist/assets/EmptyState-CXwJFCDQ.js +1 -0
  64. package/web/dist/assets/EnvVarEditor-GSapLD96.js +1 -0
  65. package/web/dist/assets/Evolution-BO5hysLD.js +6 -0
  66. package/web/dist/assets/GoalDetail-cxa8OvEi.js +1 -0
  67. package/web/dist/assets/Goals-Dz3qqp_l.js +1 -0
  68. package/web/dist/assets/Logs-Ckp3-hYV.js +1 -0
  69. package/web/dist/assets/Memories-DEuSRoP3.js +1 -0
  70. package/web/dist/assets/NotFound-Bvn39vSk.js +1 -0
  71. package/web/dist/assets/PageHeader-BMvN0xiB.js +1 -0
  72. package/web/dist/assets/Plugins-CRym22JF.js +1 -0
  73. package/web/dist/assets/RoleDetail-BWMjP9aZ.js +33 -0
  74. package/web/dist/assets/Roles-DD7NBDku.js +1 -0
  75. package/web/dist/assets/SectionHeader-CiCj3Is0.js +1 -0
  76. package/web/dist/assets/Settings-BlU19KuR.js +1 -0
  77. package/web/dist/assets/Strategies-CJ_q94-v.js +1 -0
  78. package/web/dist/assets/Switch-CoUUy5jr.js +1 -0
  79. package/web/dist/assets/Table-CaFJieh_.js +1 -0
  80. package/web/dist/assets/TaskDetail-DVrjU-E6.js +2 -0
  81. package/web/dist/assets/Work-BMl61RRi.js +1 -0
  82. package/web/dist/assets/dist-Bdqp1ixJ.js +1 -0
  83. package/web/dist/assets/index-DcXMQByM.css +2 -0
  84. package/web/dist/assets/index-pF--tN9F.js +2 -0
  85. package/web/dist/assets/ui-B_uMx2Fy.js +1 -0
  86. package/web/dist/assets/useIsMobileLayout-Bwrm84kJ.js +1 -0
  87. package/web/dist/assets/vendor-icons-BlMaTTx3.js +1 -0
  88. package/web/dist/assets/{vendor-react-DLRtONKt.js → vendor-react-7e01TWy7.js} +2 -2
  89. package/web/dist/assets/vendor-state-Bj70wnRm.js +1 -0
  90. package/web/dist/index.html +8 -6
  91. package/dist/App-3OBJDI2C.js +0 -9
  92. package/dist/adam-tools-4LZYFB6J.js +0 -1
  93. package/dist/audit-manager-6FFPXID3.js +0 -1
  94. package/dist/bree-engine-2NOTIBAZ.js +0 -1
  95. package/dist/channels-TSZLEU3L.js +0 -1
  96. package/dist/chunk-6NUHSHS5.js +0 -4
  97. package/dist/chunk-72VLUJ2S.js +0 -1
  98. package/dist/chunk-OTH4M5L3.js +0 -8
  99. package/dist/chunk-PVYEGQEG.js +0 -83
  100. package/dist/chunk-ZKMDHQJY.js +0 -104
  101. package/dist/engine-HJUE6I4I.js +0 -1
  102. package/dist/learner-CBPQZ3HL.js +0 -1
  103. package/dist/memory-service-HIFTKEW2.js +0 -1
  104. package/dist/outbound-gateway-GGFMU5JW.js +0 -1
  105. package/dist/role-presets-W452Y3RV.js +0 -1
  106. package/dist/roles-NYGWZMQI.js +0 -1
  107. package/dist/workflow-executor-QN4KP7B4.js +0 -1
  108. package/web/dist/assets/Card-4mOZntHG.js +0 -1
  109. package/web/dist/assets/ChannelDetail-DX4QnE8j.js +0 -1
  110. package/web/dist/assets/Channels-EXkNOQpB.js +0 -12
  111. package/web/dist/assets/Chat-Da-mCR0c.js +0 -1
  112. package/web/dist/assets/Dashboard-Bq6sEDdP.js +0 -1
  113. package/web/dist/assets/EmptyState-BlgMMAr-.js +0 -1
  114. package/web/dist/assets/EnvVarEditor-CNxXpVbD.js +0 -1
  115. package/web/dist/assets/Evolution-DPdmbooj.js +0 -6
  116. package/web/dist/assets/GoalDetail-BamCfVzS.js +0 -1
  117. package/web/dist/assets/Goals-CHPEg0RK.js +0 -1
  118. package/web/dist/assets/Logs-BHkBvH0T.js +0 -1
  119. package/web/dist/assets/Memories-BY2pJhVd.js +0 -1
  120. package/web/dist/assets/NotFound-CSjhzSGa.js +0 -1
  121. package/web/dist/assets/Plugins-C5xLM0BU.js +0 -1
  122. package/web/dist/assets/RoleDetail-Dnp-W14x.js +0 -33
  123. package/web/dist/assets/Roles-BVOVoHvc.js +0 -1
  124. package/web/dist/assets/Settings-eBHvn6s_.js +0 -1
  125. package/web/dist/assets/Strategies-BbFbLKBJ.js +0 -1
  126. package/web/dist/assets/Switch-Q-inggPs.js +0 -1
  127. package/web/dist/assets/Table-BxbnOSbq.js +0 -1
  128. package/web/dist/assets/TaskDetail-BEjZ1gco.js +0 -2
  129. package/web/dist/assets/Work-CF2iLs8i.js +0 -1
  130. package/web/dist/assets/dist-HyCSN_hp.js +0 -1
  131. package/web/dist/assets/index-CaHdOfAc.js +0 -52
  132. package/web/dist/assets/index-D0SvKqKc.css +0 -2
  133. package/web/dist/assets/vendor-icons-CkI4-NxL.js +0 -1
  134. package/web/dist/assets/vendor-state-B_-GdGNJ.js +0 -1
  135. /package/web/dist/assets/{format-DvtQjPZn.js → format-CHfBBLog.js} +0 -0
package/README.md CHANGED
@@ -69,9 +69,9 @@ Manages task lifecycle, concurrent execution pool, real-time streaming, remote h
69
69
  | **Execution Pool** | Configurable concurrent slot pool; event-driven task pickup; poll-based fallback; crash resilience |
70
70
  | **Scheduling** | Cron expressions (5-field); event-driven triggers (`template_complete:<id>`); multi-step workflows with dependency DAGs |
71
71
  | **Goal System** | Natural language SMART goals; metric trees; Thompson Sampling strategy selection |
72
- | **Role Model** | Role (identity/personality) with allowedTools/disallowedTools; learned rules; memory with hybrid search |
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 |
74
- | **Security** | 5-layer model: disallowed tools, allowed tools, file path checks, human approval, secret redaction |
74
+ | **Security** | 6-layer model: disallowed tools, allowed tools, role OS capabilities, file path checks, human approval, secret redaction |
75
75
  | **Plugin Support** | Plugin registry (global + project); MCP server passthrough |
76
76
  | **Web UI** | React SPA with 20 pages; real-time WebSocket updates; mobile responsive (shadcn/ui + Tailwind) |
77
77
  | **TUI** | Ink-based terminal UI; live streaming; approval prompts; 11 slash commands |
@@ -221,7 +221,7 @@ WebSocket events: [docs/websocket-events.md](docs/websocket-events.md)
221
221
  | Resource | Endpoints | Description |
222
222
  |----------|-----------|-------------|
223
223
  | **Tasks** | `POST` `GET` `GET/:id` `POST/:id/cancel` `POST/:id/approve` `POST/:id/reject` `POST/:id/approve-plan` `GET/:id/plan` `GET/:id/logs` `POST /batch-cancel` | Full task lifecycle + batch ops |
224
- | **Roles** | `POST` `GET` `GET/:id` `PATCH/:id` `DELETE/:id` `GET /:id/scores` `GET /:id/presets` | Role CRUD + scores + workspace management |
224
+ | **Roles** | `POST` `GET` `GET/:id` `PATCH/:id` `DELETE/:id` `GET /:id/scores` `GET /:id/presets` | Role CRUD + tool permissions + OS capabilities + workspace management |
225
225
  | **Memories** | `GET/:roleId` `POST/query` `GET /stats` `GET /:roleId/:memoryId` `DELETE /:roleId/:memoryId` | Role memory with hybrid search |
226
226
  | **Goals** | `POST` `GET` `GET/:id` `PATCH/:id` `DELETE/:id` | Natural language SMART goals |
227
227
  | **Strategies** | `GET` `GET /:role/:taskType/probabilities` | Thompson Sampling |
@@ -232,7 +232,7 @@ WebSocket events: [docs/websocket-events.md](docs/websocket-events.md)
232
232
  | **Plugins** | `GET` `GET /:id` `POST` `DELETE/:id` `POST /:id/sync` `GET /installed` `GET /available` `POST /scan-directory` `POST /register` | Plugin registry + discovery |
233
233
  | **Chat** | `POST /messages` `GET /sessions` `GET /sessions/:id` `POST /sessions/:id/restore` `GET /sessions/:id/messages` `DELETE /sessions/:id` `POST /sessions/:id/archive` `POST /sessions` | Chat sessions + messaging + restore |
234
234
  | **Evolution** | `GET` `GET /:roleId` | Role evolution audit trail |
235
- | **Config** | `GET` `PATCH` `GET /diff` `PATCH /override` `POST /reset` | Runtime configuration |
235
+ | **Config** | `GET` `PATCH` `GET /diff` `PATCH /override` `POST /reset` | Runtime configuration + sandbox status + OS capability registry |
236
236
  | **FS** | `GET /read` `GET /list` `POST /write` `POST /mkdir` | File system operations |
237
237
  | **Health** | `GET /healthz` `GET /readyz` `GET /metrics` | Liveness + readiness + metrics |
238
238
  | **WebSocket** | `WS /tasks/:id/stream` `WS /events` `WS /chat/:sessionId` | Real-time streaming |
@@ -245,9 +245,22 @@ For full request/response examples, see [docs/CLAUDE-API.md](docs/CLAUDE-API.md)
245
245
  |-------|-----------|----------|
246
246
  | 1 | `disallowedTools` | Hard block |
247
247
  | 2 | `allowedTools` | Auto-approve |
248
- | 3 | `PreToolUse` hook | File path validation |
249
- | 4 | `canUseTool` callback | Remote human approval |
250
- | 5 | `PostToolUse` hook | Log capture + secret redaction |
248
+ | 3 | `role.osCapabilities` + sandbox provider | Role-level macOS system capability gating |
249
+ | 4 | Filesystem sandbox + `PreToolUse` hook | Write scope restriction, deniedReadPaths, file path validation |
250
+ | 5 | `canUseTool` callback | Remote human approval |
251
+ | 6 | `PostToolUse` hook | Log capture + secret redaction |
252
+
253
+ macOS capability registry is exposed from `GET /config`, mirrored in `adam-tools.get_capabilities`, and rendered in Web/TUI Role settings.
254
+
255
+ - `runtime-enforced`: editable and enforced by Adam runtime
256
+ - `runtime-unavailable`: registered on macOS, but current runtime has no usable sandbox backend so Adam cannot enforce it
257
+ - `host-only`: shown for diagnosis, not saved on roles
258
+ - `registered-unwired`: shown in the registry, not enforced yet
259
+
260
+ Current runtime-enforced macOS capabilities:
261
+
262
+ - `Automation`: launch/control other apps; stored as bundle-id targets such as `com.apple.mail`
263
+ - `Accessibility`: desktop UI automation surfaces
251
264
 
252
265
  ## Project Structure
253
266
 
@@ -368,9 +381,9 @@ Adam 是一个基于 [Claude Agent SDK](https://docs.anthropic.com/en/docs/agent
368
381
  - **并发执行池**: 可配置 slot 数、事件驱动任务拾取、poll 兜底、崩溃恢复
369
382
  - **定时调度**: 5 字段 Cron 表达式、事件驱动触发(`template_complete:<id>`)、多步工作流(依赖 DAG)
370
383
  - **目标系统**: 自然语言 SMART 目标、指标树、Thompson Sampling 策略选择
371
- - **Role 模型**: Role(人格/身份),含 allowedTools/disallowedTools;学习规则、混合搜索记忆
384
+ - **Role 模型**: Role(人格/身份),含 allowedTools/disallowedTools、Role 级 macOS OS Capabilities;学习规则、混合搜索记忆
372
385
  - **实时流**: WebSocket 任务流 + 全局事件总线、pino 结构化日志
373
- - **5 层安全**: 工具禁用、工具白名单、文件路径检查、人工审批、敏感信息脱敏
386
+ - **6 层安全**: 工具禁用、工具白名单、Role 级 OS Capabilities、文件路径检查、人工审批、敏感信息脱敏
374
387
  - **插件支持**: 通过 `plugins` 配置加载 Claude Code 插件、MCP Server 透传
375
388
  - **Web UI**: React SPA,20 个页面,WebSocket 实时更新,移动端响应式(shadcn/ui + Tailwind)
376
389
  - **终端 UI**: 基于 Ink 的 TUI,实时流、审批提示、11 个斜杠命令
@@ -0,0 +1,13 @@
1
+ import{b,d as Qt,e as Go}from"./chunk-VRP4LTHY.js";import{a as Xt,f as Uo,h as Wo}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as Ht,Text as Mt,useInput as Hs}from"ink";import{useState as js,useEffect as mo,useRef as No}from"react";import{createContext as on,useContext as rn,useReducer as nn}from"react";import{jsx as ln}from"react/jsx-runtime";var sn={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 an(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};case"SET_VERSION":return{...e,version:t.version};default:return e}}var Ho=on(null);function jo({children:e}){let[t,o]=nn(an,sn);return ln(Ho.Provider,{value:{state:t,dispatch:o},children:e})}function He(){let e=rn(Ho);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Ko,useRef as zo}from"react";var cn=15e3;function Xo(){let{state:e,dispatch:t}=He(),o=zo(null),u=zo(null);Ko(()=>{u.current=e.session?.id??null},[e.session?.id]),Ko(()=>{let m=!0,g=null,a=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{a(),o.current=setTimeout(()=>{m&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},cn)};return(()=>{try{g=new Qt("/events"),g.on("task_status_change",()=>{}),g.on("approval_request",r=>{if(!m)return;let d=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:d.taskId,approvalId:d.approvalId,toolName:d.toolName,toolInput:d.toolInput,matchedPattern:d.matchedPattern}})}),g.on("plan_approval_request",r=>{if(!m)return;let d=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:d.taskId,planId:d.planId,roleId:d.roleId,plan:d.plan}})}),g.on("plan_approval_decision",()=>{m&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),g.on("config_changed",()=>{m&&t({type:"CONFIG_CHANGED"})}),g.on("execution_task_start",r=>{if(!m)return;let d=r,f=u.current;f&&(async()=>{try{let S=await b(`/tasks/${d.taskId}`);m&&S.sourceSessionId===f&&t({type:"SET_ACTIVE_TASK",taskId:d.taskId})}catch{}})()}),g.on("stats_update",r=>{if(!m)return;let d=r;t({type:"UPDATE_STATS",activeTasks:d.activeTasks,queuedTasks:d.queuedTasks,costToday:d.totalCostToday})}),g.connect().then(async()=>{if(m){a(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await b("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{m&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{m&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{m=!1,a(),g?.close()}},[t])}import{useEffect as dn,useRef as un,useState as Qo,useCallback as mn}from"react";function Yo(e){let[t,o]=Qo([]),[u,m]=Qo(!1),g=un(null),a=mn(()=>{o([]),m(!1)},[]);return dn(()=>{if(!e)return;let i=!0;o([]),m(!0);try{let s=new Go(e);return g.current=s,s.on("reasoning",r=>{if(!i)return;let f=r.content??"";o(S=>{let h=S[S.length-1];if(h?.type==="reasoning"){let C=[...S];return C[C.length-1]={...h,content:h.content+f},C}return[...S,{type:"reasoning",content:f,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"tool_call",content:d.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:d.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"tool_result",content:d.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"error",content:d.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let d=r;o(f=>[...f,{type:"complete",content:d.result??"",timestamp:Date.now(),metadata:{cost:d.costUsd,turns:d.numTurns,duration:d.totalDurationMs}}]),m(!1)}),s.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),m(!1))}),()=>{i=!1,s.close()}}catch{m(!1)}},[e]),{events:t,isStreaming:u,clearEvents:a}}import{useState as xo,useEffect as gn,useCallback as Lt}from"react";function To(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function Zo(){let[e,t]=xo(null),[o,u]=xo(!0),[m,g]=xo(null),a=Lt(async()=>{try{let S=(await b("/chat/sessions?status=active")).sessions.find(h=>h.source.type==="tui");return S?To(S):null}catch{return null}},[]),i=Lt(async()=>{try{let f=await b("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),S=To(f.session);return t(S),S}catch{return g("Failed to create session"),null}},[]),s=Lt(async f=>{try{let S=await b("/chat/messages",{method:"POST",body:{content:f,source:{type:"tui"}}});return t(h=>h&&{...h,messageCount:h.messageCount+1,lastActiveAt:Date.now()}),S}catch{return null}},[]),r=Lt(async()=>{if(!e)return!1;try{return await b(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),d=Lt(async()=>{if(e)try{let f=await b(`/chat/sessions/${e.id}`);t(To(f.session))}catch{t(null)}},[e]);return gn(()=>{let f=!1;async function S(){u(!0);let h=await a();f||(h?t(h):await i(),f||u(!1))}return S(),()=>{f=!0}},[]),{session:e,loading:o,error:m,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:d,setSession:t}}import{useEffect as Jo,useRef as fn,useState as pn}from"react";function er(e){let[t,o]=pn(null),u=fn(new Set);return Jo(()=>{if(!e)return;let m=!0,g=null;try{g=new Qt("/chat/stream"),g.on("chat_message",a=>{if(!m)return;let s=a.message;s&&s.sessionId===e&&s.role==="assistant"&&(u.current.has(s.id)||(u.current.add(s.id),o(s)))}),g.connect().catch(()=>{})}catch{}return()=>{m=!1,g?.close()}},[e]),Jo(()=>{u.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as ho,Text as Ae}from"ink";import{Fragment as Yt,jsx as xe,jsxs as Ct}from"react/jsx-runtime";var xn=90;function tr({children:e}){return xe(ho,{children:e})}function or(){let{state:e}=He(),t=e.session,u=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,m=e.connected?"up":"down",g=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),a=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,s=(process.stdout.columns??100)<xn,r=Ct(Yt,{children:[xe(Ae,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),xe(Ae,{children:` ${m}`}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:g.toLowerCase()})]}),d=Ct(Yt,{children:[xe(Ae,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&Ct(Yt,{children:[xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{children:a}),u&&Ct(Yt,{children:[xe(Ae,{dimColor:!0,children:" | "}),xe(Ae,{color:"yellow",children:"timeout"})]})]})]});return s?Ct(ho,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[xe(tr,{children:r}),xe(tr,{children:d})]}):Ct(ho,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[r,xe(Ae,{dimColor:!0,children:" | "}),d]})}import{Box as Zt,Text as Jt,useInput as hn}from"ink";import{useState as bo,useMemo as yn}from"react";import bn from"ink-text-input";var Tn=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function yo(e){let t=e.toLowerCase();return Tn.filter(o=>o.name.startsWith(t))}function rr(e){let t=yo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as eo,jsxs as _t}from"react/jsx-runtime";function nr({onSubmit:e}){let[t,o]=bo(""),[u,m]=bo(0),[g,a]=bo(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=yn(()=>i?yo(s):[],[i,s]),d=h=>{o(h),h.startsWith("/")?(a(!0),m(0)):a(!1)},f=()=>{let h=t.trim();if(h){if(h.startsWith("/")){let C=h.slice(1),n=rr(C);e(n?`/${n.name}`:h)}else e(h);o(""),a(!1)}},S=h=>{e(`/${h.name}`),o(""),a(!1)};return hn((h,C)=>{if(!(!g||!i||r.length===0)){if(C.upArrow){m(n=>n<=0?r.length-1:n-1);return}if(C.downArrow){m(n=>n>=r.length-1?0:n+1);return}if(C.tab){let n=r[u];n&&S(n);return}if(C.escape){a(!1),o("");return}}},{isActive:g&&i&&r.length>0}),_t(Zt,{flexDirection:"column",children:[g&&i&&r.length>0&&eo(Zt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((h,C)=>{let n=C===u;return _t(Zt,{children:[eo(Jt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),_t(Jt,{color:n?"cyan":"white",bold:n,children:["/",h.name]}),_t(Jt,{dimColor:!0,children:[" \u2014 ",h.description]})]},h.name)})}),_t(Zt,{borderStyle:"round",borderDimColor:!0,children:[eo(Jt,{bold:!0,children:"\u25B8 "}),eo(bn,{value:t,onChange:d,onSubmit:f,placeholder:"Type a message or / for commands..."})]})]})}import{Box as St,Text as Se,useInput as vn}from"ink";import{useState as Cn}from"react";import{jsx as $e,jsxs as je}from"react/jsx-runtime";function Sn({content:e,expanded:t}){let o=e.split(`
2
+ `);return o.length<=5?$e(Se,{color:"green",children:e}):t?$e(Se,{color:"green",children:e}):je(Se,{color:"green",children:[o.slice(0,3).join(`
3
+ `),`
4
+ `,je(Se,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function wn({event:e,expanded:t}){switch(e.type){case"reasoning":return $e(St,{children:$e(Se,{color:"gray",children:e.content})});case"tool_call":return $e(St,{children:je(Se,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return je(St,{flexDirection:"column",children:[$e(Se,{color:"blue",dimColor:!0,children:"[result]"}),$e(Sn,{content:e.content,expanded:t})]});case"error":return $e(St,{children:je(Se,{color:"red",children:["[error] ",e.content]})});case"complete":return je(St,{flexDirection:"column",marginTop:1,children:[e.content&&$e(Se,{children:e.content}),$e(Se,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&je(Se,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&je(Se,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&je(Se,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function sr({events:e,isStreaming:t}){let[o,u]=Cn(!1),m=e.some(g=>g.type==="tool_result"&&g.content.split(`
5
+ `).length>5);return vn((g,a)=>{a.ctrl&&g==="o"&&u(i=>!i)},{isActive:m}),e.length===0&&!t?null:je(St,{flexDirection:"column",children:[t&&e.length===0&&$e(Se,{dimColor:!0,children:"Waiting for response..."}),e.map((g,a)=>$e(wn,{event:g,expanded:o},a)),m&&$e(Se,{dimColor:!0,children:o?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as ir,Text as ar}from"ink";import{jsx as vo,jsxs as Bn}from"react/jsx-runtime";function lr({messages:e}){return e.length===0?null:vo(ir,{flexDirection:"column",children:e.map((t,o)=>Bn(ir,{flexDirection:"column",marginBottom:1,children:[vo(ar,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),vo(ar,{children:t.content})]},o))})}import{Box as Ot,Text as Ke,useInput as En}from"ink";import{jsx as ze,jsxs as Vt}from"react/jsx-runtime";function cr({approval:e,onResolved:t}){return En(o=>{o==="a"?b(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&b(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Vt(Ot,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[ze(Ke,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Vt(Ot,{marginTop:1,children:[ze(Ke,{children:"Tool: "}),ze(Ke,{bold:!0,children:e.toolName})]}),Vt(Ot,{children:[ze(Ke,{children:"Input: "}),ze(Ke,{children:JSON.stringify(e.toolInput)})]}),Vt(Ot,{children:[ze(Ke,{children:"Pattern: "}),ze(Ke,{dimColor:!0,children:e.matchedPattern})]}),Vt(Ot,{marginTop:1,children:[ze(Ke,{color:"green",children:"[a] Approve"}),ze(Ke,{children:" "}),ze(Ke,{color:"red",children:"[r] Reject"})]})]})}import{Box as qt,Text as we,useInput as kn}from"ink";import{useState as In,useEffect as An}from"react";import{jsx as ot,jsxs as Fe}from"react/jsx-runtime";var Pn=300;function dr({approval:e,onResolved:t,onTimeout:o}){let[u,m]=In(Pn);An(()=>{let a=setInterval(()=>{m(i=>i<=1?(clearInterval(a),o(),0):i-1)},1e3);return()=>clearInterval(a)},[o]),kn(a=>{a==="a"?b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):a==="r"?b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):a==="p"&&b(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let g=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Fe(qt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ot(we,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Fe(we,{dimColor:!0,children:["Plan ID: ",e.planId]}),Fe(we,{dimColor:!0,children:["Time remaining: ",u,"s"]}),Fe(qt,{marginTop:1,children:[ot(we,{children:"Overall Risk: "}),ot(we,{bold:!0,color:g,children:e.plan.overallRisk.toUpperCase()})]}),Fe(we,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(a=>{let i=a.riskLevel==="high"?"red":a.riskLevel==="medium"?"yellow":"green";return Fe(qt,{paddingLeft:2,children:[Fe(we,{children:["[",a.index,"] "]}),ot(we,{children:a.description}),Fe(we,{dimColor:!0,children:[" (",a.toolsNeeded.join(", "),")"]}),Fe(we,{color:i,children:[" [",a.riskLevel,"]"]})]},a.index)}),Fe(qt,{marginTop:1,children:[ot(we,{dimColor:!0,children:"Permissions: "}),ot(we,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Fe(qt,{marginTop:1,children:[ot(we,{color:"green",children:"[a] Allow once "}),ot(we,{color:"green",children:"[p] Allow permanent "}),ot(we,{color:"red",children:"[r] Deny"})]})]})}import{Box as Te,Text as j,useInput as Vn}from"ink";import{useEffect as qn,useState as ct,useCallback as xr}from"react";import{Box as fe,Text as F,useInput as Dn}from"ink";import{useEffect as Rn,useState as wt}from"react";import{jsx as ie,jsxs as W}from"react/jsx-runtime";var ur={plan:!0,result:!1,routing:!0,error:!0},Mn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"};function pr({taskId:e,onBack:t}){let[o,u]=wt(null),[m,g]=wt([]),[a,i]=wt([]),[s,r]=wt(null),[d,f]=wt(ur),[S,h]=wt(!1);Rn(()=>{let E=!1;return u(null),g([]),i([]),r(null),f(ur),h(!1),b(`/tasks/${e}`).then(({task:k})=>{E||u(k)}).catch(k=>{E||r(k instanceof Error?k.message:String(k))}),b(`/tasks/${e}/plan`).then(({plans:k})=>{E||g(k)}).catch(()=>{E||g([])}),b(`/tasks/${e}/delivery-log?limit=8`).then(({logs:k})=>{E||i(k)}).catch(()=>{E||i([])}),()=>{E=!0}},[e]);let C=E=>{f(k=>({...k,[E]:!k[E]}))};if(Dn((E,k)=>{if(E==="b"||k.escape){t();return}E==="1"&&C("plan"),E==="2"&&C("result"),E==="3"&&C("routing"),E==="4"&&C("error"),E==="5"&&h(H=>!H)}),s)return W(fe,{flexDirection:"column",children:[W(F,{color:"red",children:["Task detail failed: ",s]}),ie(F,{dimColor:!0,children:"[b] Back"})]});if(!o)return W(F,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let n=m[0],T=_n(o.deliverTo,o.reportTo),_=a.length>0?`${a.length} delivery event${a.length===1?"":"s"}`:"No delivery events";return W(fe,{flexDirection:"column",children:[W(fe,{children:[W(F,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ie(F,{dimColor:!0,children:" \u2022 "}),ie(F,{color:Mn[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),W(F,{dimColor:!0,children:[o.roleId?`role ${o.roleId}`:"no role"," \u2022 ",fr(o.createdAt)," \u2022 ",Ln(o.totalDurationMs)]}),W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{bold:!0,children:"Summary"}),ie(F,{children:S?o.prompt:Nn(o.prompt,240)}),o.prompt.length>240&&W(F,{dimColor:!0,children:["[5] ",S?"collapse prompt":"expand prompt"]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{dimColor:!0,children:["Cost: ",$n(o.costUsd)]}),W(F,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),W(F,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),W(F,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[1] Plan ",d.plan?"hide":"show"]}),ie(F,{dimColor:!0,children:n?`${n.plan.steps.length} planned step${n.plan.steps.length===1?"":"s"} \u2022 ${n.plan.overallRisk} risk \u2022 ${n.status}`:"No execution plan"}),d.plan&&n&&W(fe,{marginTop:1,flexDirection:"column",children:[n.plan.steps.map(E=>W(fe,{flexDirection:"column",marginBottom:1,children:[W(F,{children:[E.index,". ",E.description]}),W(F,{dimColor:!0,children:[E.riskLevel," risk \u2022 ",E.toolsNeeded.join(", ")||"no tools listed"]}),E.expectedOutput?W(F,{dimColor:!0,children:["Expected: ",E.expectedOutput]}):null]},E.index)),n.learnedRules&&n.learnedRules.length>0&&W(fe,{flexDirection:"column",children:[ie(F,{color:"blue",bold:!0,children:"Learned Rules"}),n.learnedRules.map((E,k)=>W(F,{dimColor:!0,children:["\u2022 ",E]},k))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[2] Result ",d.result?"hide":"show"]}),ie(F,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),d.result&&ie(fe,{marginTop:1,children:ie(F,{children:o.result?gr(o.result,18):"No result yet."})})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[3] Routing ",d.routing?"hide":"show"]}),W(F,{dimColor:!0,children:[T," \u2022 ",_]}),d.routing&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Deliver To"}),mr(o.deliverTo),ie(F,{color:"cyan",children:"Report To"}),mr(o.reportTo),a.length>0&&W(fe,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Recent Delivery"}),a.map(E=>W(F,{dimColor:!0,children:[E.status," \u2022 ",On(E)," \u2022 ",fr(E.createdAt)]},E.id))]})]})]}),W(fe,{marginTop:1,flexDirection:"column",children:[W(F,{bold:!0,children:["[4] Error ",d.error?"hide":"show"]}),ie(F,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),d.error&&o.error&&ie(fe,{marginTop:1,children:ie(F,{color:"red",children:gr(o.error,16)})})]}),ie(fe,{marginTop:1,children:ie(F,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function mr(e){return!e||e.length===0?ie(F,{dimColor:!0,children:" none"}):ie(fe,{flexDirection:"column",children:e.map((t,o)=>ie(F,{dimColor:!0,children:t.type==="channel"?` channel ${t.channelId.slice(0,8)}${t.chatId?` / ${t.chatId.slice(0,8)}`:""}`:` session ${t.sessionId.slice(0,8)}`},`${t.type}-${o}`))})}function gr(e,t){let o=e.split(`
6
+ `);return o.length<=t?e:`${o.slice(0,t).join(`
7
+ `)}
8
+ \u2026`}function Nn(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function $n(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Ln(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let o=Math.floor(t/60),u=t%60;return u===0?`${o}m`:`${o}m ${u}s`}function fr(e){return new Date(e).toLocaleString()}function _n(e,t){let o=e?.length??0,u=t?.length??0;return o===0&&u===0?"No delivery targets":`${o} output target${o===1?"":"s"} \u2022 ${u} report target${u===1?"":"s"}`}function On(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 Un,jsx as ee,jsxs as oe}from"react/jsx-runtime";var Tr={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},to=["all","pending","queued","running","completed","failed","cancelled"],Co=15;function ro({onBack:e}){let[t,o]=ct([]),[u,m]=ct(!0),[g,a]=ct("list"),[i,s]=ct(0),[r,d]=ct("all"),[f,S]=ct(0),[h,C]=ct(0),[n,T]=ct(null),_=xr(async()=>{m(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let O=await b(`/tasks?${I}`);o(O.tasks)}catch{o([])}finally{m(!1)}},[r]);qn(()=>{_()},[_]);let E=Math.max(1,Math.ceil(t.length/Co)),k=t.slice(h*Co,(h+1)*Co),H=xr(async()=>{let I=k[i];if(I)try{await b(`/tasks/${I.id}/cancel`,{method:"POST"}),T(`Cancelled: ${I.id.slice(0,8)}`),a("list"),_()}catch(O){T(`Failed: ${O instanceof Error?O.message:String(O)}`),a("list")}},[k,i,_]);if(Vn((I,O)=>{if(g==="detail"){(O.escape||O.return||I==="q")&&a("list");return}if(g==="cancelling"){I==="y"?H():a("list");return}if(g==="filter"){if(O.escape){a("list");return}O.upArrow&&f>0&&S(R=>R-1),O.downArrow&&f<to.length-1&&S(R=>R+1),O.return&&(d(to[f]),C(0),s(0),a("list"));return}if(O.escape||I==="q"){e();return}if(O.upArrow&&i>0&&s(R=>R-1),O.downArrow&&i<k.length-1&&s(R=>R+1),O.return&&k[i]&&a("detail"),I==="x"&&k[i]){let R=k[i];["running","pending","queued","paused"].includes(R.status)?(a("cancelling"),T(null)):T(`Cannot cancel task in status: ${R.status}`)}I==="f"&&(S(to.indexOf(r)),a("filter")),I==="r"&&_(),(O.pageDown||I==="n")&&h<E-1&&(C(R=>R+1),s(0)),(O.pageUp||I==="p")&&h>0&&(C(R=>R-1),s(0))}),u)return ee(j,{dimColor:!0,children:"Loading tasks..."});if(g==="filter")return oe(Te,{flexDirection:"column",children:[ee(j,{bold:!0,children:"Filter by status:"}),to.map((I,O)=>ee(Te,{children:oe(j,{color:O===f?"cyan":"white",children:[O===f?"> ":" ",I,I===r?" (current)":""]})},I)),ee(j,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(g==="detail"&&k[i])return ee(pr,{taskId:k[i].id,onBack:()=>a("list")});if(g==="cancelling"&&k[i])return oe(Te,{flexDirection:"column",children:[oe(j,{color:"red",children:['Cancel task "',k[i].id.slice(0,8),'"? (y/n)']}),n&&ee(j,{color:"red",children:n})]});let Q=k[i]??null;return oe(Te,{flexDirection:"column",children:[oe(Te,{children:[oe(j,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&oe(j,{dimColor:!0,children:[" [filter: ",r,"]"]}),oe(j,{dimColor:!0,children:[" \u2022 Page ",h+1,"/",E]})]}),n&&ee(j,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?oe(j,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):oe(Te,{marginTop:1,flexDirection:"row",gap:2,children:[ee(Te,{flexDirection:"column",flexGrow:3,children:k.map((I,O)=>{let R=O===i,D=Tr[I.status]??"white";return oe(Te,{flexDirection:"column",marginBottom:1,children:[oe(Te,{children:[ee(j,{color:R?"cyan":"gray",bold:R,children:R?"\u276F ":" "}),ee(j,{color:D,bold:!0,children:I.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${I.id.slice(0,8)}`})]}),ee(Te,{paddingLeft:2,children:ee(j,{color:R?"white":void 0,children:oo(I.prompt,R?72:56)})}),ee(Te,{paddingLeft:2,children:oe(j,{dimColor:!0,children:[br(I.createdAt)," \u2022 ",hr(I)," \u2022 ",yr(I.costUsd)]})})]},I.id)})}),ee(Te,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Q?oe(Un,{children:[ee(j,{bold:!0,children:"Preview"}),oe(Te,{marginTop:1,children:[ee(j,{color:Tr[Q.status]??"white",bold:!0,children:Q.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${Q.id.slice(0,8)}`})]}),ee(j,{children:oo(Q.prompt,220)}),oe(Te,{marginTop:1,flexDirection:"column",children:[oe(j,{dimColor:!0,children:["Role: ",Q.roleId??Q.agentId??"\u2014"]}),oe(j,{dimColor:!0,children:["Created: ",br(Q.createdAt)]}),oe(j,{dimColor:!0,children:["Duration: ",hr(Q)]}),oe(j,{dimColor:!0,children:["Cost: ",yr(Q.costUsd)]}),oe(j,{dimColor:!0,children:["Turns: ",Q.numTurns??"\u2014"]})]}),Q.error?oe(Te,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"red",bold:!0,children:"Error"}),ee(j,{color:"red",children:oo(Q.error,180)})]}):Q.result?oe(Te,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"green",bold:!0,children:"Latest Result"}),ee(j,{children:oo(Q.result,180)})]}):null,ee(Te,{marginTop:1,children:ee(j,{dimColor:!0,children:"Enter opens full detail"})})]}):ee(j,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Fn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function oo(e,t){return Fn(e.replace(/\s+/g," ").trim(),t)}function hr(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let o=Math.max(1,Math.round(t/1e3));if(o<60)return`${o}s`;let u=Math.floor(o/60),m=o%60;return m===0?`${u}m`:`${u}m ${m}s`}function yr(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function br(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let o=Math.floor(t/60);if(o<60)return`${o}m ago`;let u=Math.floor(o/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}Wo();import{Box as ft,Text as Pe,useInput as Wn}from"ink";import{useEffect as Gn,useState as vr}from"react";import{readFileSync as Hn,existsSync as jn}from"fs";import{parse as Kn}from"yaml";import{Fragment as Xn,jsx as Be,jsxs as Le}from"react/jsx-runtime";function Cr({onBack:e}){let[t,o]=vr(null),[u,m]=vr(null);return Wn((g,a)=>{(a.escape||g==="q")&&e()}),Gn(()=>{try{let g=Uo;if(!jn(g)){m(`Config file not found: ${g}`);return}let a=Hn(g,"utf-8");o(Kn(a))}catch(g){m(g.message)}},[]),u?Le(ft,{flexDirection:"column",children:[Be(Pe,{color:"red",children:u}),Be(Pe,{dimColor:!0,children:"Press Esc to go back"})]}):t?Le(ft,{flexDirection:"column",children:[Be(Pe,{bold:!0,children:"Configuration (Esc to go back)"}),Be(ft,{marginTop:1,flexDirection:"column",children:Be(So,{obj:t,indent:0})})]}):Be(Pe,{dimColor:!0,children:"Loading config..."})}function So({obj:e,indent:t}){let o=" ".repeat(t);return Be(Xn,{children:Object.entries(e).map(([u,m])=>Be(zn,{label:u,value:m,indent:t,parentKey:u},u))})}function zn({label:e,value:t,indent:o,parentKey:u}){let m=" ".repeat(o);return Array.isArray(t)?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),":"]}),t.length===0?Le(Pe,{dimColor:!0,children:[m," []"]}):t.map((g,a)=>Be(Sr,{value:g,indent:o+1,parentKey:u,index:a},`${e}-${a}`))]}):t&&typeof t=="object"?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),":"]}),Be(So,{obj:t,indent:o+1})]}):Le(Pe,{children:[m,Be(Pe,{color:"cyan",children:e}),": ",wr(u,Br(t))]})}function Sr({value:e,indent:t,parentKey:o,index:u}){let m=" ".repeat(t);return Array.isArray(e)?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,"- [",u,"]"]}),e.map((g,a)=>Be(Sr,{value:g,indent:t+1,parentKey:o,index:a},`${u}-${a}`))]}):e&&typeof e=="object"?Le(ft,{flexDirection:"column",children:[Le(Pe,{children:[m,"-"]}),Be(So,{obj:e,indent:t+1})]}):Le(Pe,{children:[m,"- ",wr(o,Br(e))]})}function wr(e,t){let o=e.toLowerCase();return o.includes("key")||o.includes("token")||o.includes("secret")||o.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function Br(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as no,Text as Ue,useInput as Qn}from"ink";import{useEffect as Yn,useState as wo}from"react";import{jsx as Ft,jsxs as Xe}from"react/jsx-runtime";function Er({onBack:e}){let[t,o]=wo([]),[u,m]=wo(!0),[g,a]=wo(null);return Qn((i,s)=>{(s.escape||i==="q")&&e()}),Yn(()=>{b("/evolution-audit?limit=20").then(i=>{o(i),m(!1)}).catch(i=>{a(i.message),m(!1)})},[]),u?Ft(Ue,{dimColor:!0,children:"Loading evolution log..."}):g?Xe(no,{flexDirection:"column",children:[Ft(Ue,{color:"red",children:g}),Ft(Ue,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Xe(no,{flexDirection:"column",children:[Ft(Ue,{dimColor:!0,children:"No evolution records yet"}),Ft(Ue,{dimColor:!0,children:"Press Esc to go back"})]}):Xe(no,{flexDirection:"column",children:[Xe(Ue,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>Xe(no,{flexDirection:"column",marginTop:1,children:[Xe(Ue,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&Xe(Ue,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
9
+ `).map((s,r)=>s.startsWith("+")?Xe(Ue,{color:"green",children:[" ",s]},r):s.startsWith("-")?Xe(Ue,{color:"red",children:[" ",s]},r):Xe(Ue,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as rt,Text as ae,useInput as Zn}from"ink";import Jn from"ink-text-input";import{useEffect as es,useState as Bt}from"react";import{jsx as De,jsxs as he}from"react/jsx-runtime";var ts={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function os(e,t=20){let o=Math.round(e*t),u=t-o;return"\u2588".repeat(o)+"\u2591".repeat(u)}function rs(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function so({onBack:e}){let[t,o]=Bt([]),[u,m]=Bt(null),[g,a]=Bt("list"),[i,s]=Bt(""),[r,d]=Bt(!1),[f,S]=Bt(null);Zn((n,T)=>{if(g==="create"){T.escape&&(a("list"),s(""),S(null));return}(T.escape||n==="q")&&e(),n==="c"&&(a("create"),S(null)),n==="r"&&h()});let h=()=>{b("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>m(n.message))};es(()=>{h()},[]);let C=async n=>{if(n.trim()){d(!0),S(null);try{let T=await b("/goals",{method:"POST",body:{input:n.trim()}});S(`Goal created: ${T.goal.name}`),s(""),a("list"),h()}catch(T){S(`Failed: ${T instanceof Error?T.message:String(T)}`)}finally{d(!1)}}};return u?he(rt,{flexDirection:"column",children:[he(ae,{color:"red",children:["Failed to load goals: ",u]}),De(ae,{dimColor:!0,children:"Press Esc or q to return"})]}):g==="create"?he(rt,{flexDirection:"column",children:[De(ae,{bold:!0,children:"Create Goal"}),De(ae,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),he(rt,{marginTop:1,children:[De(ae,{color:"cyan",children:"> "}),De(Jn,{value:i,onChange:s,onSubmit:C})]}),r&&De(ae,{color:"yellow",children:"Creating goal..."}),f&&De(ae,{color:f.startsWith("Failed")?"red":"green",children:f}),De(ae,{dimColor:!0,children:"Press Esc to cancel"})]}):he(rt,{flexDirection:"column",children:[he(ae,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?De(ae,{dimColor:!0,children:"No goals found. Press c to create one."}):De(rt,{marginTop:1,flexDirection:"column",children:t.map(n=>{let T=n.targetValue>0?n.currentValue/n.targetValue:0,_=ts[n.status]??"white";return he(rt,{marginBottom:1,flexDirection:"column",children:[he(rt,{children:[De(ae,{bold:!0,color:_,children:n.name}),he(ae,{dimColor:!0,children:[" (",n.role,")"]}),De(ae,{dimColor:!0,children:" \u2014 "}),De(ae,{color:_,children:n.status})]}),he(rt,{children:[he(ae,{dimColor:!0,children:[" ",os(T)," "]}),he(ae,{color:T>=1?"green":"white",children:[Math.round(T*100),"%"]}),he(ae,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),he(rt,{children:[he(ae,{dimColor:!0,children:[" \u23F0 ",rs(n.deadline)," left"]}),he(ae,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),he(ae,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),De(ae,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as Et,Text as Oe,useInput as ns}from"ink";import{useEffect as ss,useState as kr}from"react";import{jsx as st,jsxs as nt}from"react/jsx-runtime";function is(e,t,o=15){let u=e/(e+t),m=Math.round(u*o);return"\u2593".repeat(m)+"\u2591".repeat(o-m)}function Ir({onBack:e}){let[t,o]=kr([]),[u,m]=kr(null);if(ns((a,i)=>{(i.escape||a==="q")&&e()}),ss(()=>{b("/strategies?limit=50").then(a=>o(a.strategies??[])).catch(a=>m(a.message))},[]),u)return nt(Et,{flexDirection:"column",children:[nt(Oe,{color:"red",children:["Failed to load strategies: ",u]}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return nt(Et,{flexDirection:"column",children:[st(Oe,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]});let g=new Map;for(let a of t){let i=`${a.role}/${a.taskType}`,s=g.get(i)??[];s.push(a),g.set(i,s)}return nt(Et,{flexDirection:"column",children:[st(Oe,{bold:!0,children:"Strategy Lab"}),st(Oe,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),st(Et,{marginTop:1,flexDirection:"column",children:Array.from(g.entries()).map(([a,i])=>nt(Et,{marginBottom:1,flexDirection:"column",children:[st(Oe,{bold:!0,color:"cyan",children:a}),i.sort((s,r)=>{let d=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-d}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return nt(Et,{children:[st(Oe,{dimColor:!0,children:" "}),nt(Oe,{children:[is(s.alpha,s.beta)," "]}),nt(Oe,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),nt(Oe,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},a))}),st(Oe,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as ve,Text as Y,useInput as us}from"ink";import Bo from"ink-text-input";import{useEffect as ms,useState as Qe,useCallback as kt}from"react";import{CronExpressionParser as gs}from"cron-parser";import{useState as as,useEffect as ls,useCallback as Ar,useRef as cs}from"react";var ds=3e3;function dt(){let[e,t]=as(null),o=cs(null),u=Ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),m=Ar((g,a)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:g,type:a}),a==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},ds))},[]);return ls(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:m,clearMessage:u}}import{jsx as te,jsxs as ne}from"react/jsx-runtime";var Eo=["manual","cron","event"],io={name:"",triggerType:"manual",cron:"",stepPrompt:""};function fs(e){try{return gs.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function ao({onBack:e}){let[t,o]=Qe([]),[u,m]=Qe(!0),[g,a]=Qe(0),[i,s]=Qe("list"),[r,d]=Qe({...io}),[f,S]=Qe("name"),[h,C]=Qe(null),{message:n,setMessage:T,clearMessage:_}=dt(),[E,k]=Qe(!1),[H,Q]=Qe(!1),[I,O]=Qe({}),R=kt(()=>{m(!0),b("/task-templates").then(({templates:v})=>{o(v),new Set(v.flatMap(M=>M.steps?.map(J=>J.roleId).filter(Boolean)??[])).size>0?b("/roles").then(({roles:M})=>{if(!Array.isArray(M)){O({});return}O(Object.fromEntries(M.map(J=>[J.id,J.name])))}).catch(()=>O({})):O({}),m(!1)}).catch(()=>m(!1))},[]);ms(()=>{R()},[R]);let D=i==="create"||i==="edit",Z=kt(async()=>{let v=t[g];if(!(!v||E)){k(!0),T(`Triggering ${v.name}...`,"loading");try{let $=await b(`/task-templates/${v.id}/run`,{method:"POST"});T(`Triggered: ${v.name} (${$.executionId})`,"success")}catch($){T(`Trigger failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{k(!1)}}},[t,g,E,T]),le=kt(async()=>{let v=t[g];if(!v||H)return;if(v.trigger?.type!=="cron"&&v.trigger?.type!=="event"){T("Toggle not applicable for manual triggers","error");return}let $=!v.enabled;Q(!0),T(`${v.name} \u2192 ${$?"enabling":"disabling"}...`,"loading");try{await b(`/task-templates/${v.id}`,{method:"PATCH",body:{enabled:$}}),o(M=>M.map(J=>J.id===v.id?{...J,enabled:$}:J)),T(`${v.name} ${$?"enabled":"disabled"}`,"success")}catch(M){T(`Toggle failed: ${M instanceof Error?M.message:String(M)}`,"error")}finally{Q(!1)}},[t,g,H,T]),Je=kt(async()=>{let v=t[g];if(v)try{await b(`/task-templates/${v.id}`,{method:"DELETE"}),T(`Deleted: ${v.name}`,"success"),R(),a($=>Math.max(0,Math.min($,t.length-2)))}catch($){T(`Delete failed: ${$ instanceof Error?$.message:String($)}`,"error")}},[t,g,R]),ht=kt(()=>{let v=t[g];v&&(C(v.id),d({name:v.name,triggerType:v.trigger?.type??"manual",cron:v.trigger?.cron??"",stepPrompt:v.steps?.[0]?.prompt??""}),S("name"),s("edit"))},[t,g]),Ne=kt(async()=>{let v={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await b("/task-templates",{method:"POST",body:v}),T(`Created: ${r.name}`,"success")):i==="edit"&&h&&(await b(`/task-templates/${h}`,{method:"PATCH",body:v}),T(`Updated: ${r.name}`,"success"))}catch($){T(`Save failed: ${$ instanceof Error?$.message:String($)}`,"error")}s("list"),d({...io}),C(null),R()},[r,i,h,R]);return us((v,$)=>{if(D){if($.escape){s("list"),d({...io}),C(null);return}if($.return){let M=["name","triggerType","cron","stepPrompt"],J=M.indexOf(f);if(J<M.length-1){let Ie=J+1;if(M[Ie]==="cron"&&r.triggerType!=="cron"&&Ie++,Ie<M.length){S(M[Ie]);return}}Ne();return}if($.tab&&f==="triggerType"){d(M=>{let J=Eo.indexOf(M.triggerType);return{...M,triggerType:Eo[(J+1)%Eo.length]}});return}return}if($.escape||v==="q"){e();return}if($.upArrow){a(M=>Math.max(0,M-1));return}if($.downArrow){a(M=>Math.min(t.length-1,M+1));return}if(v==="t"){Z();return}if(v==="d"){Je();return}if(v==="e"){ht();return}if(v==="c"){d({...io}),S("name"),s("create");return}if(v==="s"||v===" "){le();return}v==="r"&&(R(),_())}),u?te(Y,{dimColor:!0,children:"Loading templates..."}):D?ne(ve,{flexDirection:"column",children:[ne(Y,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),ne(ve,{marginTop:1,flexDirection:"column",children:[ne(ve,{children:[ne(Y,{bold:f==="name",color:f==="name"?"cyan":void 0,children:["Name:"," "]}),f==="name"?te(Bo,{value:r.name,onChange:v=>d($=>({...$,name:v})),placeholder:"template name"}):te(Y,{children:r.name||"(empty)"})]}),ne(ve,{children:[ne(Y,{bold:f==="triggerType",color:f==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),te(Y,{children:r.triggerType}),f==="triggerType"&&te(Y,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&ne(ve,{children:[ne(Y,{bold:f==="cron",color:f==="cron"?"cyan":void 0,children:["Cron:"," "]}),f==="cron"?te(Bo,{value:r.cron,onChange:v=>d($=>({...$,cron:v})),placeholder:"*/5 * * * *"}):te(Y,{children:r.cron||"(empty)"})]}),ne(ve,{children:[ne(Y,{bold:f==="stepPrompt",color:f==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),f==="stepPrompt"?te(Bo,{value:r.stepPrompt,onChange:v=>d($=>({...$,stepPrompt:v})),placeholder:"What should this template do?"}):te(Y,{children:r.stepPrompt||"(empty)"})]})]}),te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):ne(ve,{flexDirection:"column",children:[ne(Y,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&te(ve,{marginTop:1,children:ne(Y,{color:n.type==="success"?"green":n.type==="error"?"red":"gray",children:[n.type==="success"?"\u2713 ":n.type==="error"?"\u2717 ":"\u2192 ",n.text]})}),t.length===0?te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"No templates found. Press c to create one."})}):te(ve,{marginTop:1,flexDirection:"column",children:t.map((v,$)=>{let M=$===g,J=v.trigger?.type==="cron"&&v.trigger?.cron?fs(v.trigger.cron):"",Ie=new Set(v.steps?.filter(A=>A.roleId).map(A=>A.roleId)),N=v.steps?.length>1?`${v.steps.length} steps${Ie.size>0?` / ${Ie.size} roles`:""}`:`${v.steps?.length??0} step`;return ne(ve,{flexDirection:"column",children:[ne(ve,{children:[te(Y,{color:M?"cyan":void 0,bold:M,children:M?"> ":" "}),te(Y,{color:M?"cyan":void 0,bold:M,children:Ut(v.name,24)}),te(Y,{dimColor:!0,children:Ut(v.trigger?.type,10)}),v.trigger?.type!=="cron"&&v.trigger?.type!=="event"?te(Y,{dimColor:!0,children:Ut("\u2014",6)}):te(Y,{color:v.enabled?"green":"gray",children:Ut(v.enabled?"on":"off",6)}),te(Y,{dimColor:!0,children:Ut(N,18)}),J&&ne(Y,{dimColor:!0,children:["next: ",J]})]}),M&&v.steps?.length>1&&te(ve,{flexDirection:"column",marginLeft:4,marginTop:0,children:v.steps.map((A,G)=>ne(ve,{children:[ne(Y,{dimColor:!0,children:[" ",G+1,". "]}),te(Y,{dimColor:!0,children:A.id}),A.roleId&&ne(Y,{color:"yellow",children:[" @",I[A.roleId]??A.roleId]}),A.dependsOn&&A.dependsOn.length>0&&ne(Y,{dimColor:!0,children:[" (after: ",A.dependsOn.join(", "),")"]}),A.config&&ne(Y,{dimColor:!0,children:[" ","[",[A.config.timeout!==void 0?`timeout:${A.config.timeout}s`:"",A.config.maxTurns!==void 0?`turns:${A.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},A.id))})]},v.id)})}),te(ve,{marginTop:1,children:te(Y,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Ut(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ut,Text as _e,useInput as ps}from"ink";import xs from"ink-text-input";import{useEffect as Ts,useState as It,useCallback as Pr}from"react";import{jsx as Ee,jsxs as pt}from"react/jsx-runtime";function Dr({onBack:e}){let[t,o]=It([]),[u,m]=It(""),[g,a]=It(!0),[i,s]=It(!1),[r,d]=It(""),[f,S]=It(null),h=Pr(()=>{a(!0),b("/webhooks").then(({webhooks:n,auth:T})=>{o(n),m(T),a(!1)}).catch(()=>a(!1))},[]);Ts(()=>{h()},[h]);let C=Pr(async n=>{if(n.trim())try{let T=await b(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});S(`Triggered: ${T.executionId}`)}catch(T){S(`Trigger failed: ${T instanceof Error?T.message:String(T)}`)}},[]);return ps((n,T)=>{if(i){if(T.escape){s(!1),d("");return}if(T.return){C(r),s(!1),d("");return}return}if(T.escape||n==="q"){e();return}if(n==="t"){s(!0),d(""),S(null);return}n==="r"&&(h(),S(null))}),g?Ee(_e,{dimColor:!0,children:"Loading webhooks..."}):pt(ut,{flexDirection:"column",children:[pt(_e,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),pt(_e,{dimColor:!0,children:["Auth: ",u]}),f&&Ee(ut,{marginTop:1,children:Ee(_e,{color:"yellow",children:f})}),i&&pt(ut,{marginTop:1,children:[Ee(_e,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Ee(xs,{value:r,onChange:d,placeholder:"webhook name or ID"}),Ee(_e,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Ee(ut,{marginTop:1,children:Ee(_e,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):pt(ut,{marginTop:1,flexDirection:"column",children:[Ee(ut,{children:pt(_e,{bold:!0,children:[At("NAME",24),At("DESCRIPTION",36),At("TRIGGER",28),"TAGS"]})}),t.map(n=>pt(ut,{children:[Ee(_e,{children:At(n.displayName,24)}),Ee(_e,{dimColor:!0,children:At(hs(n.description??"",34),36)}),Ee(_e,{dimColor:!0,children:At(n.trigger,28)}),Ee(_e,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),Ee(ut,{marginTop:1,children:Ee(_e,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function At(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function hs(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ye,Text as me,useInput as ys}from"ink";import bs from"ink-text-input";import{useEffect as Rr,useState as it,useCallback as ko}from"react";import{jsx as ge,jsxs as We}from"react/jsx-runtime";function vs(e){return e>=4?"red":e===3?"yellow":"gray"}function Cs(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Ss(e){return new Date(e).toLocaleDateString()}function Nr({onBack:e}){let[t,o]=it([]),[u,m]=it(0),[g,a]=it([]),[i,s]=it(!0),[r,d]=it(!1),[f,S]=it(""),[h,C]=it("all"),[n,T]=it(null),[_,E]=it(!1),k=ko(()=>{b("/agents").then(({agents:D})=>{o(D),s(!1)}).catch(()=>s(!1))},[]);Rr(()=>{k()},[k]);let H=t[u],Q=ko(()=>{H&&(E(!1),b(`/memories/${H.id}`).then(({memories:D})=>{a(D),T(null)}).catch(D=>T(`Failed: ${D instanceof Error?D.message:String(D)}`)))},[H]);Rr(()=>{H&&Q()},[H,Q]);let I=ko(async D=>{if(!(!H||!D.trim()))try{let Z=await b("/memories/query",{method:"POST",body:{agentId:H.id,prompt:D.trim()}});a(Z.memories),E(!0),T(`Search: ${Z.count} results`)}catch(Z){T(`Search failed: ${Z instanceof Error?Z.message:String(Z)}`)}},[H]),O=r,R=g.filter(D=>h==="all"?!0:h==="high"?D.importance>3:h==="medium"?D.importance===3:D.importance<3);return ys((D,Z)=>{if(O){if(Z.escape){d(!1),S("");return}if(Z.return){I(f),d(!1),S("");return}return}if(Z.escape||D==="q"){e();return}if(D==="a"){m(le=>(le+1)%Math.max(1,t.length));return}if(Z.leftArrow){m(le=>(le-1+t.length)%Math.max(1,t.length));return}if(Z.rightArrow){m(le=>(le+1)%Math.max(1,t.length));return}if(D==="s"){d(!0),S(""),T(null);return}if(D==="h"){C(le=>le==="high"?"all":"high");return}if(D==="m"){C(le=>le==="medium"?"all":"medium");return}if(D==="l"){C(le=>le==="low"?"all":"low");return}D==="r"&&Q()}),i?ge(me,{dimColor:!0,children:"Loading agents..."}):t.length===0?We(Ye,{flexDirection:"column",children:[ge(me,{dimColor:!0,children:"No agents found"}),ge(me,{dimColor:!0,children:"Press Esc to go back"})]}):We(Ye,{flexDirection:"column",children:[ge(me,{bold:!0,children:"Memories (Esc to go back)"}),We(Ye,{marginTop:1,children:[ge(me,{children:"Agent: "}),ge(me,{bold:!0,color:"cyan",children:H?.name??"?"}),We(me,{dimColor:!0,children:[" (",u+1,"/",t.length,") [a/arrows to switch]"]})]}),ge(Ye,{children:We(me,{dimColor:!0,children:["Filter: ",h==="all"?"all":h," | ",_?"search results":"all memories"," (",R.length,")"]})}),n&&ge(Ye,{children:ge(me,{color:"yellow",children:n})}),r&&We(Ye,{marginTop:1,children:[ge(me,{bold:!0,color:"cyan",children:"Search: "}),ge(bs,{value:f,onChange:S,placeholder:"search query..."}),ge(me,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),R.length===0?ge(Ye,{marginTop:1,children:We(me,{dimColor:!0,children:["No memories",h!=="all"?` matching filter '${h}'`:""]})}):ge(Ye,{marginTop:1,flexDirection:"column",children:R.map(D=>We(Ye,{marginBottom:0,children:[We(me,{color:vs(D.importance),bold:!0,children:[Cs(D.importance)," "]}),ge(me,{dimColor:!0,children:Mr(D.type??"?",12)}),ge(me,{dimColor:!0,children:Mr(`\xD7${D.retrievedCount??0}`,5)}),We(me,{children:[ws(D.content,55)," "]}),ge(me,{dimColor:!0,children:Ss(D.createdAt)}),D.score!==void 0&&We(me,{dimColor:!0,children:[" (",D.score.toFixed(2),")"]})]},D.id))}),ge(Ye,{marginTop:1,children:ge(me,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Mr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function ws(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ge,Text as de,useInput as Bs}from"ink";import lo from"ink-text-input";import{useState as Re,useEffect as $r,useCallback as Io}from"react";import{jsx as ye,jsxs as pe}from"react/jsx-runtime";var Lr={Anthropic:["anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel"],Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","defaults.approvalTimeout"],Server:["server.port","server.host","server.apiKey","server.timezone"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"],Workflow:["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},Es={"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 _r({onBack:e}){let{state:t}=He(),[o,u]=Re({}),[m,g]=Re([]),[a,i]=Re(null),[s,r]=Re("view"),[d,f]=Re(0),[S,h]=Re(""),[C,n]=Re(null),[T,_]=Re(!1),[E,k]=Re([]),[H,Q]=Re({}),[I,O]=Re(0),[R,D]=Re(""),[Z,le]=Re(""),[Je,ht]=Re(""),Ne=Object.values(Lr).flat(),v=Io(()=>{b("/config").then(N=>{u(N.config),g(N.mutable)}).catch(N=>i(N.message)),b("/config/env-diff").then(N=>{k(N.diffs)}).catch(()=>{}),b("/config/env").then(N=>Q(N.env??{})).catch(()=>{})},[]);$r(()=>{v()},[v]),$r(()=>{t.configVersion>0&&v()},[t.configVersion,v]);let $=Io(async()=>{let N=Ne[d];if(N){_(!0),n(null);try{let A=S,G=o[N];if(G&&typeof G.value=="number"&&(A=Number(S),isNaN(A))){n("Invalid number"),_(!1);return}let ue=await b("/config",{method:"PATCH",body:{[N]:A}});ue.updated.length>0&&(n(`Updated: ${N}`),v()),ue.errors.length>0&&n(ue.errors[0]),r("view")}catch(A){n(`Failed: ${A instanceof Error?A.message:String(A)}`)}finally{_(!1)}}},[Ne,d,S,o,v]),M=Object.keys(H),J=Io(async N=>{try{await b("/config/env",{method:"PUT",body:N}),n("Env vars saved"),v()}catch(A){n(`Failed: ${A instanceof Error?A.message:String(A)}`)}},[v]);if(Bs((N,A)=>{if(s==="edit"){if(A.escape){r("view");return}return}if(s==="env-list"){if(A.escape){r("view");return}if(A.upArrow&&I>0&&O(G=>G-1),A.downArrow&&I<M.length-1&&O(G=>G+1),N==="a"){D(""),r("env-add-key");return}if(N==="d"&&M.length>0){let G=M[I],ue={...H};delete ue[G],J(ue),I>=M.length-1&&I>0&&O(et=>et-1);return}if(A.return&&M.length>0){ht(H[M[I]]??""),r("env-edit-value");return}return}if(s==="env-add-key"){if(A.escape){r("env-list");return}return}if(s==="env-add-value"){if(A.escape){r("env-list");return}return}if(s==="env-edit-value"){if(A.escape){r("env-list");return}return}if(A.escape||N==="q"){e();return}if(A.upArrow&&d>0&&f(G=>G-1),A.downArrow&&d<Ne.length-1&&f(G=>G+1),A.return||N==="e"){let G=Ne[d],ue=o[G];ue&&ue.mutable?(h(String(ue.value??"")),r("edit"),n(null)):ue&&!ue.mutable&&n("This setting requires a restart to change")}N==="v"&&(O(0),r("env-list"),n(null)),N==="r"&&(v(),n("Refreshed")),N==="s"&&E.length>0&&b("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),k([]),v()}),N==="l"&&E.length>0&&b("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),v()})}),a)return pe(Ge,{flexDirection:"column",children:[pe(de,{color:"red",children:["Failed to load config: ",a]}),ye(de,{dimColor:!0,children:"Press Esc or q to return"})]});let Ie=0;return pe(Ge,{flexDirection:"column",children:[ye(de,{bold:!0,children:"Settings"}),C&&ye(de,{color:C.startsWith("Failed")||C.startsWith("This setting")?"yellow":"green",children:C}),E&&E.length>0&&pe(Ge,{flexDirection:"column",marginBottom:1,children:[pe(de,{color:"yellow",children:[".env differs from DB (",E.length," key(s)): ",E.map(N=>N.envKey).join(", ")]}),ye(de,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ye(Ge,{marginTop:1,flexDirection:"column",children:Object.entries(Lr).map(([N,A])=>pe(Ge,{marginBottom:1,flexDirection:"column",children:[ye(de,{bold:!0,color:"cyan",children:N}),A.map(G=>{let ue=o[G],yt=Ie++===d,bt=m.includes(G),jt=Es[G]??G,lt=ue?String(ue.value??""):"...";return s==="edit"&&yt?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",jt,": "]}),ye(lo,{value:S,onChange:h,onSubmit:()=>{$()}}),T&&ye(de,{color:"yellow",children:" saving..."})]},G):pe(Ge,{children:[pe(de,{color:yt?"cyan":"white",children:[yt?"> ":" ",bt?" ":"\u{1F512} ",jt,": "," "]}),ye(de,{color:bt?"white":"gray",children:lt}),!bt&&ye(de,{dimColor:!0,children:" (restart required)"})]},G)})]},N))}),ye(de,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),s.startsWith("env")&&pe(Ge,{flexDirection:"column",marginTop:1,children:[pe(de,{bold:!0,color:"cyan",children:["Environment Variables (",M.length,")"]}),M.length===0&&s==="env-list"&&ye(de,{dimColor:!0,children:" No env vars. Press a to add."}),M.map((N,A)=>{let G=A===I;return s==="env-edit-value"&&G?pe(Ge,{children:[pe(de,{color:"cyan",children:["> ",N," = "]}),ye(lo,{value:Je,onChange:ht,onSubmit:()=>{J({...H,[N]:Je}),r("env-list")}})]},N):pe(de,{color:G&&s==="env-list"?"cyan":"white",children:[G&&s==="env-list"?"> ":" ",N," = ",H[N]]},N)}),s==="env-add-key"&&pe(Ge,{children:[ye(de,{color:"green",children:" New key: "}),ye(lo,{value:R,onChange:D,onSubmit:()=>{R.trim()&&(le(""),r("env-add-value"))}})]}),s==="env-add-value"&&pe(Ge,{children:[pe(de,{color:"green",children:[" ",R," = "]}),ye(lo,{value:Z,onChange:le,onSubmit:()=>{J({...H,[R.trim()]:Z}),r("env-list")}})]}),ye(de,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as xt,Text as ke,useInput as ks}from"ink";import{useEffect as Is,useState as Ao,useCallback as As}from"react";import{jsx as Ce,jsxs as Dt}from"react/jsx-runtime";function Or({onBack:e}){let[t,o]=Ao([]),[u,m]=Ao(!0),[g,a]=Ao(0),{message:i,setMessage:s,clearMessage:r}=dt(),d=As(()=>{m(!0),b("/plugins").then(({plugins:f})=>{o(f),m(!1)}).catch(()=>m(!1))},[]);return Is(()=>{d()},[d]),ks((f,S)=>{if(S.escape||f==="q"){e();return}if(S.upArrow){a(h=>Math.max(0,h-1));return}if(S.downArrow){a(h=>Math.min(t.length-1,h+1));return}f==="r"&&(d(),r())}),u?Ce(ke,{dimColor:!0,children:"Loading plugins..."}):Dt(xt,{flexDirection:"column",children:[Dt(ke,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Ce(xt,{marginTop:1,children:Dt(ke,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?Ce(xt,{marginTop:1,children:Ce(ke,{dimColor:!0,children:"No plugins installed."})}):Dt(xt,{marginTop:1,flexDirection:"column",children:[Dt(xt,{children:[Ce(ke,{dimColor:!0,children:" "}),Ce(ke,{dimColor:!0,children:Pt("Name",24)}),Ce(ke,{dimColor:!0,children:Pt("Scope",8)}),Ce(ke,{dimColor:!0,children:Pt("User",6)}),Ce(ke,{dimColor:!0,children:"Path"})]}),t.map((f,S)=>{let h=S===g,C=f.id.split("@")[0];return Dt(xt,{children:[Ce(ke,{color:h?"cyan":void 0,bold:h,children:h?"> ":" "}),Ce(ke,{color:h?"cyan":void 0,bold:h,children:Pt(C,24)}),Ce(ke,{color:h?"cyan":void 0,bold:h,children:Pt(f.scope,8)}),Ce(ke,{color:f.globalEnabled?"green":"gray",children:Pt(f.globalEnabled?"on":"off",6)}),Ce(ke,{dimColor:!0,children:f.installPath})]},f.id)})]}),Ce(xt,{marginTop:1,children:Ce(ke,{dimColor:!0,children:"r:refresh"})})]})}function Pt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Po,Text as Do,useInput as Ps}from"ink";import{useState as Ds}from"react";import{jsx as Tt,jsxs as Vr}from"react/jsx-runtime";var Rs=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function qr({onBack:e}){let[t,o]=Ds("tasks");return Ps((u,m)=>{if(m.escape||u==="q"){e();return}if(u==="1"){o("tasks");return}if(u==="2"){o("automations");return}if(u==="3"){o("goals");return}}),Vr(Po,{flexDirection:"column",children:[Tt(Do,{bold:!0,children:"Work Surface"}),Tt(Do,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Tt(Po,{gap:3,marginBottom:1,marginTop:1,children:Rs.map(u=>{let m=t===u.id;return Tt(Po,{children:Vr(Do,{color:m?"cyan":"gray",bold:m,children:[m?"\u25CF":"\u25CB"," ",u.key,". ",u.label]})},u.id)})}),t==="tasks"&&Tt(ro,{onBack:e}),t==="automations"&&Tt(ao,{onBack:e}),t==="goals"&&Tt(so,{onBack:e})]})}import{Box as re,Text as K,useInput as Ms}from"ink";import{useEffect as Ns,useState as Wt}from"react";import{jsx as q,jsxs as be}from"react/jsx-runtime";var Fr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Ur({onBack:e}){let[t,o]=Wt([]),[u,m]=Wt(!0),[g,a]=Wt(0),[i,s]=Wt(null),[r,d]=Wt("");Ns(()=>{f()},[]);async function f(){try{let C=await b("/channels");o(C.channels)}catch{}m(!1)}async function S(C){if(t.find(T=>T.id===C)?.platform==="wechat")try{d("Starting WeChat QR login...");let T=await b(`/channels/${C}/wechat/qr-start`,{method:"POST"});if(T.qrcodeUrl){d(`Scan QR: ${T.qrcodeUrl}
10
+ Waiting for scan...`);let _=await b(`/channels/${C}/wechat/qr-wait`,{method:"POST",body:{sessionKey:T.sessionKey,timeoutMs:12e4}});d(_.message)}else d(T.message);f()}catch{d("WeChat connect failed")}else try{await b(`/channels/${C}/connect`,{method:"POST"}),d("Connecting..."),f()}catch{d("Connect failed")}}async function h(C){try{await b(`/channels/${C}/disconnect`,{method:"POST"}),d("Disconnected"),f()}catch{d("Disconnect failed")}}return Ms((C,n)=>{if(i){if(n.escape||C==="q"){s(null);return}if(C==="c"){S(i.id);return}if(C==="d"){h(i.id);return}return}if(n.escape){e();return}if(n.upArrow){a(T=>Math.max(0,T-1));return}if(n.downArrow){a(T=>Math.min(t.length-1,T+1));return}if(n.return&&t[g]){s(t[g]),d("");return}}),u?q(re,{flexDirection:"column",children:q(K,{dimColor:!0,children:"Loading channels..."})}):i?be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[be(K,{bold:!0,children:["Channel: ",i.name]}),q(K,{dimColor:!0,children:" (Esc to go back)"})]}),be(re,{flexDirection:"column",gap:0,children:[be(K,{children:["ID: ",i.id]}),be(K,{children:["Platform: ",i.platform]}),be(K,{children:["Status: ",q(K,{color:Fr[i.status]??"white",children:i.status})]}),be(K,{children:["Enabled: ",i.enabled?"yes":"no"]}),be(K,{children:["Messages: ",i.messageCount]}),be(K,{children:["Config: ",JSON.stringify(i.config)]})]}),q(re,{marginTop:1,children:q(K,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&q(K,{color:"yellow",children:r})]}):be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[q(K,{bold:!0,children:"Channels"}),be(K,{dimColor:!0,children:[" (",t.length," total) "]}),q(K,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?q(K,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):be(re,{flexDirection:"column",children:[be(re,{children:[q(re,{width:3,children:q(K,{dimColor:!0,children:" "})}),q(re,{width:12,children:q(K,{bold:!0,dimColor:!0,children:"ID"})}),q(re,{width:16,children:q(K,{bold:!0,dimColor:!0,children:"Name"})}),q(re,{width:12,children:q(K,{bold:!0,dimColor:!0,children:"Platform"})}),q(re,{width:14,children:q(K,{bold:!0,dimColor:!0,children:"Status"})}),q(re,{width:10,children:q(K,{bold:!0,dimColor:!0,children:"Enabled"})}),q(re,{width:10,children:q(K,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((C,n)=>be(re,{children:[q(re,{width:3,children:q(K,{children:n===g?">":" "})}),q(re,{width:12,children:q(K,{inverse:n===g,children:C.id.slice(0,8)})}),q(re,{width:16,children:q(K,{children:C.name})}),q(re,{width:12,children:q(K,{children:C.platform})}),q(re,{width:14,children:be(K,{color:Fr[C.status]??"white",children:[C.status==="connected"?"\u25CF":C.status==="error"?"\u2717":"\u25CB"," ",C.status]})}),q(re,{width:10,children:q(K,{color:C.enabled?"green":"gray",children:C.enabled?"yes":"no"})}),q(re,{width:10,children:q(K,{children:C.messageCount})})]},C.id))]})]})}import{Box as Rt,Text as at,useInput as _s}from"ink";import{useEffect as Os,useState as Gt,useCallback as Vs}from"react";import{Box as P,Text as p,useInput as $s}from"ink";import Ze from"ink-text-input";import{useEffect as Wr,useState as z,useCallback as mt}from"react";Wo();import{Fragment as Gr,jsx as x,jsxs as w}from"react/jsx-runtime";var Ls=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function Hr({roleId:e,onBack:t}){let[o,u]=z(null),[m,g]=z([]),[a,i]=z(!0),[s,r]=z("view"),[d,f]=z(""),[S,h]=z(0),[C,n]=z(""),[T,_]=z([]),[E,k]=z(0),[H,Q]=z(new Set),[I,O]=z("inline"),[R,D]=z(""),[Z,le]=z(""),[Je,ht]=z([]),[Ne,v]=z(new Set),[$,M]=z(0),[J,Ie]=z("default"),[N,A]=z(""),[G,ue]=z(""),[et,yt]=z("mode"),[bt,jt]=z([]),[lt,zr]=z(null),[go,Xr]=z([]),[vt,fo]=z([]),[$o,po]=z(""),[gt,Kt]=z(0),[zt,Lo]=z(""),[_o,Oo]=z(""),[Vo,qo]=z(""),{message:L,setMessage:U}=dt(),se=mt(()=>{i(!0),b(`/roles/${e}`).then(({role:c,boundPlugins:y})=>{u(c),g(y??[]),f(c.cagPrompt??""),Q(new Set(c.allowedTools??[])),O(c.executionMode??"inline"),D(c.model??""),le(c.maxBudgetUsd!=null?String(c.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Wr(()=>{se(),b("/config").then(c=>{let y=c.config["defaults.deniedReadPaths"]?.value;Array.isArray(y)&&jt(y),zr(c.sandbox),Xr(c.osCapabilities?.registry??[])}).catch(()=>{})},[se]),Wr(()=>{O(o?.executionMode??"inline"),D(o?.model??""),le(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Ie(o?.permissionMode??"default"),A((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),fo(o?.osCapabilities??[]);let c=o?.osCapabilities?.find(y=>y.id==="automation")?.targets??[];po(c.join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let Qr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:d}}),U("CAG prompt saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,d,se,U]),Yr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:qe}}),U("Directories saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,se,U]),Zr=mt(async()=>{if(o)try{await b(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),U("Tool permissions saved","success"),r("view"),se()}catch(c){U(`Save failed: ${c instanceof Error?c.message:String(c)}`,"error")}},[o,H,se,U]),Jr=mt(async()=>{if(!o)return;let c={executionMode:I};R!==void 0&&(c.model=R);let y=parseFloat(Z);isNaN(y)||(c.maxBudgetUsd=y);try{await b(`/roles/${o.id}`,{method:"PATCH",body:c}),U("Execution config saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,I,R,Z,se,U]),en=mt(async()=>{if(!o)return;let c={permissionMode:J},y=N.split(",").map(B=>B.trim()).filter(Boolean),l=G.split(",").map(B=>B.trim()).filter(Boolean);c.allowedBashPatterns=y.length>0?y:[],c.deniedBashPatterns=l.length>0?l:[];try{await b(`/roles/${o.id}`,{method:"PATCH",body:c}),U("Permission config saved","success"),r("view"),se()}catch(B){U(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[o,J,N,G,se,U]),Fo=mt(c=>{let y=new Map;for(let l of c){if(!l.id)continue;let B={id:l.id};l.targets?.length&&(B.targets=Array.from(new Set(l.targets.map(V=>V.trim()).filter(Boolean)))),y.set(l.id,B)}return Array.from(y.values()).sort((l,B)=>l.id.localeCompare(B.id))},[]),tn=mt(async()=>{if(!o)return;let c=Fo(vt),y=c.find(l=>l.id==="automation")?.targets??[];if(c.some(l=>l.id==="automation")&&(y.length===0||y.some(l=>!Ls.test(l)))){U("Automation requires valid bundle id targets","error");return}try{await b(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:c}}),U("OS capabilities saved","success"),r("view"),se()}catch(l){U(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,vt,Fo,se,U]),qe=o?.additionalDirectories??[];if($s((c,y)=>{if(y.escape){r("view");return}if(c==="r"){se();return}switch(s){case"view":{if(c==="c"){r("edit-cag");return}if(c==="d"){r("edit-dirs"),h(0),n("");return}if(c==="t"){r("edit-tools");return}if(c==="o"){r("edit-oscaps");return}if(c==="x"){r("edit-exec");return}if(c==="h"){b("/channels?enabled=true").then(({channels:l})=>{ht(l.map(B=>({name:B.name,id:B.id}))),v(new Set(o?.allowedChannels??[])),M(0),r("edit-channels")}).catch(()=>U("Failed to load channels","error"));return}if(c==="p"){Ie(o?.permissionMode??"default"),A((o?.allowedBashPatterns??[]).join(", ")),ue((o?.deniedBashPatterns??[]).join(", ")),yt("mode"),r("edit-permissions");return}if(c==="v"){Kt(0),r("edit-env");return}if(c==="i"){if(!o)return;let l=!o.inheritUserSettings;b(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:l}}).then(()=>{U(`Inherit user settings: ${l?"ON":"OFF"}`,"success"),se()}).catch(()=>U("Failed to toggle","error"));return}break}case"edit-cag":{if(y.ctrl&&c==="s"){Qr();return}break}case"edit-dirs":{if(c==="s"){Yr();return}if(c==="a"){r("edit-dirs-add");return}if(c==="m"&&qe.length>0){let l=qe[S];if(l){u(V=>V&&{...V,additionalDirectories:V.additionalDirectories?.map((ce,tt)=>tt===S?{...typeof ce=="string"?{path:ce}:ce,mode:ce.mode==="ro"?"rw":"ro"}:ce)});let B=l.mode==="ro"?"rw":"ro";U(`Mode set to ${B.toUpperCase()}`,"success")}return}if(c==="x"&&qe.length>0){u(l=>l&&{...l,additionalDirectories:qe.filter((B,V)=>V!==S)}),h(l=>Math.max(0,Math.min(l,qe.length-2)));return}if(y.upArrow){h(l=>Math.max(0,l-1));return}if(y.downArrow){h(l=>Math.min(qe.length-1,l+1));return}break}case"edit-dirs-add":{if(y.escape){r("edit-dirs"),n(""),_([]);return}if(y.return&&T.length>0){let l=T[E];l&&(n(l.endsWith("/")?l:l+"/"),_([]));return}if(y.return){let l=C.trim();l&&l.startsWith("/")?(u(B=>B&&{...B,additionalDirectories:[...B.additionalDirectories??[],{path:l,mode:"rw"}]}),n(""),_([]),r("edit-dirs")):U("Path must be absolute (must start with /)","error");return}if(y.tab){let l=C.trim();if(!l||!l.startsWith("/"))return;b(`/fs/suggest-dirs?prefix=${encodeURIComponent(l)}`).then(({suggestions:B})=>{B.length===1?(n(B[0]+"/"),_([])):B.length>1&&(_(B),k(0))}).catch(()=>{_([])});return}if(y.upArrow&&T.length>0){k(l=>Math.max(0,l-1));return}if(y.downArrow&&T.length>0){k(l=>Math.min(T.length-1,l+1));return}break}case"edit-tools":{if(c==="s"){Zr();return}let l=parseInt(c,10)-1;if(!isNaN(l)&&l>=0&&l<Xt.length){let B=Xt[l];Q(V=>{let ce=new Set(V);return ce.has(B)?ce.delete(B):ce.add(B),ce});return}break}case"edit-oscaps":{if(c==="s"){tn();return}if(c==="a"&&vt.some(V=>V.id==="automation")){let V=vt.find(ce=>ce.id==="automation")?.targets??[];po(V.join(", ")),r("edit-oscaps-targets");return}let l=go.filter(V=>V.editable),B=parseInt(c,10)-1;if(!isNaN(B)&&B>=0&&B<l.length){let V=l[B];fo(ce=>ce.some($t=>$t.id===V.id)?ce.filter($t=>$t.id!==V.id):[...ce,{id:V.id,targets:V.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(y.return){let l=$o.split(",").map(B=>B.trim()).filter(Boolean);fo(B=>B.map(V=>V.id==="automation"?{...V,targets:l}:V)),r("edit-oscaps");return}break}case"edit-exec":{if(c==="s"){Jr();return}if(y.tab){O(l=>l==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(c==="s"){en();return}if(y.tab){yt(l=>l==="mode"?"allowed":l==="allowed"?"denied":"mode");return}if(et==="mode"&&(y.upArrow||y.downArrow)){let l=["default","acceptEdits","dontAsk","bypassPermissions"],B=l.indexOf(J);y.upArrow&&Ie(l[Math.max(0,B-1)]),y.downArrow&&Ie(l[Math.min(l.length-1,B+1)]);return}break}case"edit-channels":{if(c==="s"){if(!o)return;let l=Ne.size>0?Array.from(Ne):[];b(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:l}}).then(()=>{U("Channels saved","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(c==="u"){if(!o)return;b(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{U("Channels: unrestricted","success"),r("view"),se()}).catch(()=>U("Save failed","error"));return}if(c===" "){let l=Je[$];l&&v(B=>{let V=new Set(B);return V.has(l.name)?V.delete(l.name):V.add(l.name),V});return}if(y.upArrow){M(l=>Math.max(0,l-1));return}if(y.downArrow){M(l=>Math.min(Je.length-1,l+1));return}break}case"edit-env":{let l=Object.keys(o?.envVars??{});if(c==="a"){Lo(""),r("edit-env-add-key");return}if(c==="d"&&l.length>0){let B=l[gt],V={...o?.envVars??{}};delete V[B],b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:V}}).then(()=>{U("Deleted","success"),se()}).catch(()=>U("Delete failed","error")),gt>=l.length-1&&gt>0&&Kt(ce=>ce-1);return}if(y.return&&l.length>0){qo((o?.envVars??{})[l[gt]]??""),r("edit-env-edit-value");return}y.upArrow&&gt>0&&Kt(B=>B-1),y.downArrow&&gt<l.length-1&&Kt(B=>B+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),a)return x(p,{dimColor:!0,children:"Loading role..."});if(!o)return x(p,{dimColor:!0,children:"Role not found."});if(s==="edit-cag")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),x(Ze,{value:d,onChange:f,placeholder:"Character And Guidance prompt..."}),L&&x(P,{marginTop:1,children:x(p,{color:L.type==="error"?"red":"green",children:L.text})})]});if(s==="edit-dirs-add")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),x(Ze,{value:C,onChange:c=>{n(c),_([])},placeholder:"/absolute/path/to/directory"}),T.length>0&&w(P,{flexDirection:"column",marginTop:1,children:[T.map((c,y)=>w(p,{color:y===E?"cyan":void 0,dimColor:y!==E,children:[y===E?"> ":" ",c,"/"]},c)),x(p,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),L&&x(P,{marginTop:1,children:x(p,{color:L.type==="error"?"red":"green",children:L.text})})]});if(s==="edit-dirs")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),qe.length===0?x(p,{dimColor:!0,children:"No directories. Press a to add one."}):qe.map((c,y)=>{let l=typeof c=="string"?{path:c,mode:"rw"}:c,B=l.mode!=="ro";return w(P,{children:[x(p,{color:y===S?"cyan":void 0,bold:y===S,children:y===S?"> ":" "}),w(p,{color:B?"green":"yellow",children:["[",B?"RW":"RO","]"," "]}),x(p,{color:y===S?"cyan":void 0,children:l.path})]},l.path)})]});if(s==="edit-tools")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),Xt.map((c,y)=>{let l=H.has(c);return w(P,{children:[w(p,{dimColor:!0,children:[y+1,". "]}),x(p,{color:l?"green":"red",children:l?"[ON] ":"[OFF] "}),x(p,{children:c})]},c)})]});if(s==="edit-oscaps"){let c=go.filter(y=>y.editable);return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),lt&&w(p,{dimColor:!0,children:["Platform: ",lt.platform," ",lt.available?"(sandbox active)":"(sandbox unavailable)"]}),go.map(y=>{let l=c.findIndex(tt=>tt.id===y.id),B=vt.some(tt=>tt.id===y.id),V=l>=0?`${l+1}.`:" -",ce=y.id==="automation"?(()=>{let tt=vt.find($t=>$t.id===y.id)?.targets??[];return tt.length>0?` targets: ${tt.join(", ")}`:" targets: (none)"})():"";return w(P,{flexDirection:"column",marginBottom:1,children:[w(p,{color:B?"green":y.editable?"red":"gray",children:[V," ",B?"[ON]":"[OFF]"," ",y.label," [",y.availability,"]"]}),w(p,{dimColor:!0,children:[" ",y.description,ce]}),y.effectiveDisabledReason&&!y.editable&&w(p,{dimColor:!0,children:[" ",y.effectiveDisabledReason]})]},y.id)}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]})}if(s==="edit-oscaps-targets")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),x(Ze,{value:$o,onChange:po,placeholder:"com.apple.mail, com.apple.systemevents"}),x(p,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-exec")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),w(P,{children:[x(p,{bold:!0,children:" Mode: "}),x(p,{color:"cyan",children:I}),x(p,{dimColor:!0,children:" (Tab to toggle)"})]}),w(P,{children:[x(p,{bold:!0,children:" Model: "}),x(Ze,{value:R,onChange:D,placeholder:"sonnet, opus, haiku, or blank"})]}),w(P,{children:[x(p,{bold:!0,children:" Max Budget (USD): "}),x(Ze,{value:Z,onChange:le,placeholder:"0 = unlimited"})]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-permissions")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),w(P,{children:[x(p,{bold:!0,color:et==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(y=>w(p,{color:y===J?"green":"gray",children:[y===J?`[${y}]`:` ${y} `," "]},y))]}),w(P,{children:[x(p,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?x(Ze,{value:N,onChange:A,placeholder:"git add *, pnpm test*"}):x(p,{children:N||"(none)"})]}),w(P,{children:[x(p,{bold:!0,color:et==="denied"?"cyan":void 0,children:" Denied Bash: "}),et==="denied"?x(Ze,{value:G,onChange:ue,placeholder:"rm -rf *, ssh *"}):x(p,{children:G||"(none)"})]}),x(p,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s==="edit-channels")return w(P,{flexDirection:"column",children:[x(p,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Je.length===0?x(p,{dimColor:!0,children:"No channels available"}):Je.map((c,y)=>w(P,{children:[w(p,{children:[y===$?">":" "," "]}),w(p,{color:Ne.has(c.name)?"green":"gray",children:["[",Ne.has(c.name)?"x":" ","] ",c.name]})]},c.id)),w(p,{dimColor:!0,children:["Selected: ",Ne.size>0?Array.from(Ne).join(", "):"none (= block all)"]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})})]});if(s.startsWith("edit-env")){let c=Object.keys(o.envVars??{});return w(P,{flexDirection:"column",children:[w(p,{bold:!0,children:["Environment Variables (",c.length,")"]}),c.length===0&&s==="edit-env"&&x(p,{dimColor:!0,children:" No env vars. Press a to add."}),c.map((y,l)=>{let B=l===gt;return s==="edit-env-edit-value"&&B?w(P,{children:[w(p,{color:"cyan",children:["> ",y," = "]}),x(Ze,{value:Vo,onChange:qo,onSubmit:()=>{let V={...o.envVars??{},[y]:Vo};b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:V}}).then(()=>{U("Saved","success"),se(),r("edit-env")}).catch(()=>U("Save failed","error"))}})]},y):w(p,{color:B&&s==="edit-env"?"cyan":"white",children:[B&&s==="edit-env"?"> ":" ",y," = ",(o.envVars??{})[y]]},y)}),s==="edit-env-add-key"&&w(P,{children:[x(p,{color:"green",children:" New key: "}),x(Ze,{value:zt,onChange:Lo,onSubmit:()=>{zt.trim()&&(Oo(""),r("edit-env-add-value"))}})]}),s==="edit-env-add-value"&&w(P,{children:[w(p,{color:"green",children:[" ",zt," = "]}),x(Ze,{value:_o,onChange:Oo,onSubmit:()=>{let y={...o.envVars??{},[zt.trim()]:_o};b(`/roles/${o.id}`,{method:"PATCH",body:{envVars:y}}).then(()=>{U("Added","success"),se(),r("edit-env")}).catch(()=>U("Add failed","error"))}})]}),x(p,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),L&&x(p,{color:L.type==="error"?"red":"green",children:L.text})]})}return w(P,{flexDirection:"column",children:[w(p,{bold:!0,children:["Role: ",o.name]}),w(P,{children:[x(p,{dimColor:!0,children:"ID: "}),x(p,{children:o.id})]}),w(P,{children:[x(p,{dimColor:!0,children:"Status: "}),x(p,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&w(P,{children:[x(p,{dimColor:!0,children:"Score: "}),w(p,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"Created: "}),x(p,{children:new Date(o.createdAt).toLocaleString()})]}),w(P,{children:[x(p,{dimColor:!0,children:"Execution: "}),w(p,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"OS Capabilities: "}),x(p,{children:(o.osCapabilities?.length??0)>0?o.osCapabilities.map(c=>c.id==="automation"&&c.targets?.length?`automation(${c.targets.join(",")})`:c.id).join(", "):"None"})]}),lt&&w(P,{children:[x(p,{dimColor:!0,children:"Sandbox Platform: "}),w(p,{children:[lt.platform," ",lt.available?"(active)":"(unavailable)"]})]}),qe.length>0&&w(Gr,{children:[x(p,{bold:!0,children:"Additional Directories:"}),qe.map(c=>w(p,{dimColor:!0,children:[" ",c.path]},c.path))]}),w(P,{children:[x(p,{dimColor:!0,children:"Permission: "}),x(p,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&w(P,{children:[x(p,{dimColor:!0,children:" Bash Allow: "}),x(p,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&w(P,{children:[x(p,{dimColor:!0,children:" Bash Deny: "}),x(p,{children:o.deniedBashPatterns.join(", ")})]}),bt.length>0&&w(P,{flexDirection:"column",children:[x(p,{dimColor:!0,children:"Denied Read Paths (global):"}),bt.map(c=>w(p,{dimColor:!0,children:[" ",c]},c)),w(p,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),w(P,{children:[x(p,{dimColor:!0,children:"Channels: "}),x(p,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),w(P,{children:[x(p,{dimColor:!0,children:"Inherit User Settings: "}),x(p,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&w(Gr,{children:[x(p,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(c=>w(p,{dimColor:!0,children:[" - ",c]},c))]}),L&&x(P,{children:x(p,{color:L.type==="error"?"red":L.type==="success"?"green":"gray",children:L.text})}),x(P,{marginTop:1,children:x(p,{dimColor:!0,children:"c:CAG d:dirs t:tools o:oscaps x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as Ve,jsxs as co}from"react/jsx-runtime";function jr({onBack:e}){let[t,o]=Gt([]),[u,m]=Gt(!0),[g,a]=Gt(0),[i,s]=Gt("list"),[r,d]=Gt(null),{message:f,setMessage:S,clearMessage:h}=dt(),C=Vs(()=>{m(!0),b("/roles").then(({roles:n})=>{o(n.map(T=>({id:T.id,name:T.name,status:T.status,performanceScore:T.performanceScore,createdAt:T.createdAt}))),m(!1)}).catch(()=>m(!1))},[]);return Os(()=>{C()},[C]),_s((n,T)=>{if(T.escape||n==="q"){e();return}if(T.upArrow){a(_=>Math.max(0,_-1));return}if(T.downArrow){a(_=>Math.min(t.length-1,_+1));return}if(n==="r"&&(C(),h()),n===`
11
+ `||n==="o"||n==="e"){t.length>0&&(d(t[g].id),s("detail"));return}}),u?Ve(at,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Ve(Hr,{roleId:r,onBack:()=>s("list")}):co(Rt,{flexDirection:"column",children:[co(at,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),f&&Ve(Rt,{marginTop:1,children:co(at,{color:f.type==="success"?"green":f.type==="error"?"red":"gray",children:[f.type==="success"?"\u2713 ":f.type==="error"?"\u2717 ":"\u2192 ",f.text]})}),t.length===0?Ve(Rt,{marginTop:1,children:Ve(at,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ve(Rt,{marginTop:1,flexDirection:"column",children:t.map((n,T)=>{let _=T===g,E=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return co(Rt,{children:[Ve(at,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),Ve(at,{color:_?"cyan":void 0,bold:_,children:Ro(n.name,24)}),Ve(at,{color:qs(n.status),children:Ro(n.status,12)}),Ve(at,{dimColor:!0,children:Ro(E,8)})]},n.id)})}),Ve(Rt,{marginTop:1,children:Ve(at,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function qs(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Ro(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Fs,Text as Mo}from"ink";import Us from"react";import{jsx as uo,jsxs as Gs}from"react/jsx-runtime";var Me={key:"Esc",label:"back"},Ws={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},Me],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},Me],config:[Me],evolution:[Me],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},Me],strategies:[Me],templates:[{key:"\u2191\u2193",label:"move"},{key:"t",label:"run"},{key:"s",label:"toggle"},{key:"e",label:"edit"},{key:"c",label:"create"},{key:"d",label:"delete"},{key:"r",label:"refresh"},Me],webhooks:[Me],memories:[Me],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},Me],roles:[Me],settings:[Me],channels:[Me]};function Kr(){let{state:e}=He(),t=Ws[e.view]??[Me];return uo(Fs,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,u)=>Gs(Us.Fragment,{children:[u>0&&uo(Mo,{dimColor:!0,children:" "}),uo(Mo,{color:"cyan",children:o.key}),uo(Mo,{dimColor:!0,children:` ${o.label}`})]},`${o.key}-${o.label}`))})}import{Fragment as Qs,jsx as X,jsxs as Nt}from"react/jsx-runtime";function Ks(){let{state:e,dispatch:t}=He(),{session:o,sendMessage:u,createNewSession:m,archiveCurrentSession:g}=Zo(),[a,i]=js([]);mo(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Xo();let{latestMessage:s}=er(o?.id??null),r=No(null);mo(()=>{s&&s.id!==r.current&&(r.current=s.id,i(k=>[...k,{role:"assistant",content:s.content}]))},[s]);let{events:d,isStreaming:f,clearEvents:S}=Yo(e.activeTaskId),h=d[d.length-1],C=h?.type==="complete"&&!f,n=No(null),T=No("");mo(()=>{T.current=d.filter(k=>k.type==="reasoning").map(k=>k.content).join("")},[d]),mo(()=>{if(C&&e.activeTaskId!==n.current){n.current=e.activeTaskId;let k=h?.content||T.current;k&&i(H=>[...H,{role:"assistant",content:k}])}},[C,h,e.activeTaskId]);let _=async k=>{let H=k.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),k.startsWith("/")){let I=k.slice(1),R={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"}[I];if(R){t({type:"SET_VIEW",view:R});return}if(I==="new"){if(await g()){let Z=await m();i([]),S(),Z&&i([{role:"assistant",content:`Session archived. New session started: ${Z.id.slice(0,8)}`}])}return}if(I==="session"){let D=o?`Session: ${o.id}
12
+ Turns: ${o.messageCount}
13
+ Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(Z=>[...Z,{role:"assistant",content:D}]);return}}if(i(I=>[...I,{role:"user",content:k}]),S(),!await u(k)){i(I=>[...I,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},E=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval;return Nt(Ht,{flexDirection:"column",paddingX:1,children:[X(or,{}),Nt(Ht,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Nt(Qs,{children:[X(lr,{messages:a}),X(sr,{events:d,isStreaming:f}),!e.connected&&!e.serverUnreachable&&X(Ht,{children:X(Mt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Nt(Ht,{flexDirection:"column",children:[X(Mt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),X(Mt,{dimColor:!0,children:"Check: adam server logs"}),X(Mt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&X(qr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&X(ro,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&X(Cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&X(Er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&X(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&X(Ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&X(ao,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&X(Dr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&X(Nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&X(Or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&X(jr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&X(_r,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&X(Ur,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?X(dr,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?X(cr,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):E?X(nr,{onSubmit:_}):X(Kr,{}),e.planTimeoutNotice&&X(zs,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function zs({planId:e,onDismiss:t}){return Hs(o=>{o==="d"&&t()}),Nt(Ht,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Nt(Mt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),X(Mt,{dimColor:!0,children:" [d] Dismiss"})]})}function Xs(){return X(jo,{children:X(Ks,{})})}export{Xs as default};
@@ -0,0 +1 @@
1
+ import{n as a,o as b}from"./chunk-DBI36EGR.js";import"./chunk-5V36ACKZ.js";import"./chunk-HQ66TFYI.js";import"./chunk-YHH3QMLL.js";import"./chunk-6THDALGC.js";import"./chunk-L4Y3GR6W.js";import"./chunk-NOUSHXGX.js";import"./chunk-XAMLLKKA.js";import"./chunk-KO5AFX5U.js";import"./chunk-JKPSEMUZ.js";import"./chunk-GYHOPV4Q.js";import"./chunk-I5IUTZA3.js";import"./chunk-24GTCFEV.js";import"./chunk-L7JP7DUO.js";import"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-T7GEINGZ.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -1 +1 @@
1
- import{a,b,c,d,e}from"./chunk-TCHBOWQ5.js";import"./chunk-WTRM5VO7.js";import"./chunk-CLHSPXZ6.js";import"./chunk-NUTUI5KM.js";import"./chunk-L7JP7DUO.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
1
+ import{a,b,c,d,e}from"./chunk-RUY23IJK.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.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{j as a,k as b,l as c,m as d,n as e}from"./chunk-WRETNOC3.js";import"./chunk-HQ66TFYI.js";import"./chunk-YHH3QMLL.js";import"./chunk-6THDALGC.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-HYDCXE5K.js";import"./chunk-DMZM7RU6.js";import"./chunk-24GTCFEV.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-ZRUVORAJ.js";import"./chunk-NOUSHXGX.js";import"./chunk-I67UMGJM.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-7BSWC62F.js";import"./chunk-T7GEINGZ.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.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-CLHSPXZ6.js";import"./chunk-4MJF77RD.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.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-KO5AFX5U.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.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{c as a,d as b,e as c}from"./chunk-KOWFPY2J.js";import"./chunk-KO5AFX5U.js";import"./chunk-I5IUTZA3.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1,4 +1,4 @@
1
- import{g as y,k as T}from"./chunk-OTH4M5L3.js";import{d as h,h as F}from"./chunk-WBAPIPST.js";import{c as R,h as P}from"./chunk-INNDBLZE.js";import{c as v,e as A}from"./chunk-FCV2DPZQ.js";import{readFileSync as b,writeFileSync as C,existsSync as k}from"fs";import{join as W}from"path";function w(e){let n=W(d(e),".env");if(!k(n))return null;let i=b(n,"utf-8"),t={};for(let o of i.split(`
1
+ import{m as y,q as T}from"./chunk-J3NIPZ73.js";import{d as h,h as F}from"./chunk-WBAPIPST.js";import{c as R,h as P}from"./chunk-INNDBLZE.js";import{c as v,e as A}from"./chunk-FCV2DPZQ.js";import{readFileSync as b,writeFileSync as C,existsSync as k}from"fs";import{join as W}from"path";function w(e){let n=W(d(e),".env");if(!k(n))return null;let i=b(n,"utf-8"),t={};for(let o of i.split(`
2
2
  `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let c=s.startsWith("export ")?s.slice(7).trim():s,u=c.indexOf("=");if(u===-1)continue;let f=c.slice(0,u).trim(),r=c.slice(u+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),!(r.includes("$")&&(r=r.replace(/\$\{(\w+)\}|\$(\w+)/g,(p,l,a)=>{let g=l??a;return t[g]??process.env[g]??""}),!r))&&(t[f]=r)}return t}function V(e,n){let i=w(e);if(!i)return n;let t={...n},o=0;for(let[s,c]of Object.entries(i)){if(s.startsWith("ANTHROPIC_")){x.warn({roleName:e,key:s},"Role .env contains ANTHROPIC_* key; ignored (managed globally)");continue}s in t||(t[s]=c,o++)}return o>0&&x.info({roleName:e,seeded:o},"Seeded role envVars from .env file"),Object.keys(t).length>0?t:void 0}function M(e,n){let i=w(e);if(!i)return[];let t=n??{},o=[];for(let[s,c]of Object.entries(i)){if(s.startsWith("ANTHROPIC_"))continue;let u=t[s]??"";u!==c&&o.push({envKey:s,dbValue:u,envValue:c})}for(let[s,c]of Object.entries(t))s in i||o.push({envKey:s,dbValue:c,envValue:""});return o}function N(e,n){let i=W(d(e),".env"),t=n??{},o=[],s=new Set;if(k(i)){let u=b(i,"utf-8");for(let f of u.split(`
3
3
  `)){let r=f.trim();if(!r||r.startsWith("#")){o.push(f);continue}let p=r.startsWith("export ")?r.slice(7).trim():r,l=p.indexOf("=");if(l===-1){o.push(f);continue}let a=p.slice(0,l).trim(),g=r.startsWith("export ")?"export ":"";a in t&&(o.push(`${g}${a}=${t[a]}`),s.add(a))}}let c=0;for(let[u,f]of Object.entries(t)){if(s.has(u)){c++;continue}f&&f.length>0&&(o.push(`${u}=${f}`),c++)}return C(i,o.join(`
4
4
  `)+`
@@ -1,3 +1,3 @@
1
- import{f as S}from"./chunk-NDP6LWXX.js";import{b as y}from"./chunk-TCHBOWQ5.js";import{b as g}from"./chunk-JZNBFZ7W.js";import{b as C}from"./chunk-WTRM5VO7.js";import{b as R}from"./chunk-CLHSPXZ6.js";import{b as v}from"./chunk-AZBNUSM2.js";import{e as m}from"./chunk-ZQYKT5UY.js";import{a as k,b as P,c as o,d as h,e as T,f as x,g as E}from"./chunk-NUTUI5KM.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-RIJO3OBO.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
1
+ import{f as S}from"./chunk-L4Y3GR6W.js";import{b as y}from"./chunk-RUY23IJK.js";import{b as g}from"./chunk-XAMLLKKA.js";import{b as C}from"./chunk-CKIVKM5T.js";import{b as R}from"./chunk-KO5AFX5U.js";import{b as v}from"./chunk-GYHOPV4Q.js";import{e as m}from"./chunk-I5IUTZA3.js";import{a as k,b as P,c as o,d as h,e as T,f as x,g as E}from"./chunk-EZGMA3VV.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-JZSXM4AD.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
2
2
 
3
3
  Task: ${e}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=S(e,n);if(i.length!==0){l.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){l.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:M(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+k,source:"rule"};P(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=C();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=R(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(h(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(h(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),l.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=I.get(e.id);t||(t=[],I.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&(!n.chatId||t.source.chatId===n.chatId):!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=x("rule",50),r=[...e,...n];if(r.length!==0){l.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function $(){return c}function H(){c||(c=new D,u=setInterval(()=>{c?.retryPending().catch(s=>{l.error({error:s},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let s=E();s>0&&l.info({cleaned:s},"Expired delivery log entries cleaned up")}catch(s){l.error({error:s},"Delivery cleanup failed")}},36e5),l.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function J(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,I.clear(),l.info("DeliveryEngine stopped")}export{D as a,$ as b,H as c,J as d};
@@ -392,7 +392,8 @@ import{e as A,h as X}from"./chunk-WBAPIPST.js";import{c as R,h as O}from"./chunk
392
392
  additional_directories TEXT,
393
393
  allowed_channels TEXT,
394
394
  mcp_servers TEXT,
395
- inherit_user_settings INTEGER DEFAULT 0
395
+ inherit_user_settings INTEGER DEFAULT 0,
396
+ os_capabilities TEXT
396
397
  );
397
398
 
398
399
  CREATE INDEX IF NOT EXISTS idx_roles_status ON roles(status);
@@ -632,4 +633,4 @@ import{e as A,h as X}from"./chunk-WBAPIPST.js";import{c as R,h as O}from"./chunk
632
633
  ON artifact_access_log (execution_id, timestamp);
633
634
  CREATE INDEX IF NOT EXISTS idx_artifact_access_log_role
634
635
  ON artifact_access_log (role_id, timestamp);
635
- `;e.exec(E),e.exec(s),e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="step_id")||e.prepare("ALTER TABLE tasks ADD COLUMN step_id TEXT").run(),e.exec("UPDATE server_state SET schema_version = 26 WHERE id = 1")}{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let n of t){let a=!1;for(let[d,r]of E)if(d.test(n)){i.push(...r),a=!0,I.info({from:n,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}a||(/[.+?^${}()|[\]\\]/.test(n)&&I.warn({pattern:n},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(n))}let N=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(N),Date.now(),T.key)}catch{}}}function K(){if(o)return o;let e=process.env.ADAM_DB_PATH||A,l=g(e);return S(l)||u(l,{recursive:!0}),o=new p(e),o.pragma("journal_mode = WAL"),o.pragma("foreign_keys = ON"),o.pragma("trusted_schema = ON"),C(o),o}function W(){o&&(o.close(),o=null)}var I,o,D=m(()=>{X();O();I=R("store"),o=null});export{C as a,K as b,W as c,D as d};
636
+ `;e.exec(E),e.exec(s),e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="step_id")||e.prepare("ALTER TABLE tasks ADD COLUMN step_id TEXT").run(),e.exec("UPDATE server_state SET schema_version = 26 WHERE id = 1")}e.prepare("PRAGMA table_info(roles)").all().some(T=>T.name==="os_capabilities")||e.prepare("ALTER TABLE roles ADD COLUMN os_capabilities TEXT DEFAULT NULL").run(),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<27&&e.prepare("UPDATE server_state SET schema_version = 27 WHERE id = 1").run();{let E=[[/\brm -rf\b/,["rm -rf *"]],[/^git push/,["git push*"]],[/^git reset/,["git reset*"]],[/\bcurl.*POST\b/i,["curl * -X POST*","curl * --request POST*"]]],s=e.prepare("SELECT key, value FROM config WHERE key = 'defaults.approvalRequired'").all();for(let T of s)try{let t=JSON.parse(T.value),i=[];for(let n of t){let a=!1;for(let[d,r]of E)if(d.test(n)){i.push(...r),a=!0,I.info({from:n,to:r},"Config: migrated approvalRequired pattern from regex to glob");break}a||(/[.+?^${}()|[\]\\]/.test(n)&&I.warn({pattern:n},"Config: approvalRequired pattern contains regex metacharacters that won't work with glob matching; update to glob syntax (use * for wildcards)"),i.push(n))}let N=[...new Set(i)];e.prepare("UPDATE config SET value = ?, updated_at = ? WHERE key = ?").run(JSON.stringify(N),Date.now(),T.key)}catch{}}}function K(){if(o)return o;let e=process.env.ADAM_DB_PATH||A,l=g(e);return S(l)||u(l,{recursive:!0}),o=new p(e),o.pragma("journal_mode = WAL"),o.pragma("foreign_keys = ON"),o.pragma("trusted_schema = ON"),C(o),o}function W(){o&&(o.close(),o=null)}var I,o,D=m(()=>{X();O();I=R("store"),o=null});export{C as a,K as b,W as c,D as d};
@@ -1,4 +1,4 @@
1
- import{b as e,d as p}from"./chunk-4MJF77RD.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
1
+ import{b as e,d as p}from"./chunk-4VHBKJD5.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
2
2
  INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
3
3
  tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{e as f,k as h}from"./chunk-OTH4M5L3.js";import{b as u,d as E}from"./chunk-4MJF77RD.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
1
+ import{k as f,q as h}from"./chunk-J3NIPZ73.js";import{b as u,d as E}from"./chunk-4VHBKJD5.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
2
2
  INSERT INTO memories (id, role_id, type, content, embedding, keywords,
3
3
  importance, source_type, source_task_id, evidence,
4
4
  created_at, last_accessed, retrieved_count, tier, superseded_by)
@@ -1,3 +1,3 @@
1
- import{b as C}from"./chunk-CLHSPXZ6.js";import{b as D,c as f,d as w}from"./chunk-NUTUI5KM.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
1
+ import{b as C}from"./chunk-KO5AFX5U.js";import{b as D,c as f,d as w}from"./chunk-EZGMA3VV.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
2
2
 
3
- `).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-TSZLEU3L.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
3
+ `).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-WMTZJAO4.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};