adam-agent-server 1.3.0 → 1.5.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.
- package/README.md +22 -9
- package/dist/App-JGH6G5US.js +13 -0
- package/dist/adam-tools-W5AOIGEQ.js +1 -0
- package/dist/{approval-handler-RIJO3OBO.js → approval-handler-ORD4MUVM.js} +1 -1
- package/dist/audit-manager-YCJT2WP5.js +1 -0
- package/dist/bree-engine-R5YLSDCL.js +1 -0
- package/dist/{channels-LUJ7GTSP.js → channels-HYSB2EEK.js} +1 -1
- package/dist/channels-JCMPPQED.js +1 -0
- package/dist/{chunk-CLHSPXZ6.js → chunk-23VZKIB6.js} +1 -1
- package/dist/{chunk-AZBNUSM2.js → chunk-2DLVAKH7.js} +1 -1
- package/dist/chunk-2YAP4YJV.js +57 -0
- package/dist/{chunk-YPOTHL7X.js → chunk-5S6BMWD2.js} +1 -1
- package/dist/chunk-5XUR3M23.js +12 -0
- package/dist/chunk-6775OYXA.js +47 -0
- package/dist/chunk-6FXNB7NE.js +1 -0
- package/dist/{chunk-WKS7QVIX.js → chunk-7L2WQM7N.js} +1 -1
- package/dist/{chunk-NDP6LWXX.js → chunk-BR2JY5X2.js} +1 -1
- package/dist/{chunk-IZGTTLTG.js → chunk-C6BOQJJF.js} +1 -1
- package/dist/{chunk-4NW2DNDZ.js → chunk-DZEVMYPB.js} +1 -1
- package/dist/chunk-GBTG5B5R.js +8 -0
- package/dist/chunk-GY52JA5I.js +10 -0
- package/dist/{chunk-HFN7Y3IM.js → chunk-H54ZXA26.js} +1 -1
- package/dist/{chunk-DBUEHITK.js → chunk-H7VDC6FY.js} +2 -2
- package/dist/{chunk-ZQYKT5UY.js → chunk-HDP7A4XY.js} +1 -1
- package/dist/{chunk-4LSIHSCO.js → chunk-HTPUEIFT.js} +1 -1
- package/dist/{chunk-JZNBFZ7W.js → chunk-ISZJV72D.js} +1 -1
- package/dist/{chunk-4MJF77RD.js → chunk-JAS3TUZX.js} +4 -3
- package/dist/chunk-MTWLLE26.js +49 -0
- package/dist/{chunk-NUTUI5KM.js → chunk-QVKI7H7W.js} +1 -1
- package/dist/{chunk-7IXLL673.js → chunk-QWCRZDZS.js} +1 -1
- package/dist/{chunk-P6KWAGAY.js → chunk-R4GIIQ7G.js} +1 -1
- package/dist/chunk-RAW263MQ.js +99 -0
- package/dist/{chunk-IKUBP3SY.js → chunk-S3BAIZ4Q.js} +2 -2
- package/dist/chunk-VRJ7R766.js +1 -0
- package/dist/{chunk-WTRM5VO7.js → chunk-XL46AGRZ.js} +2 -2
- package/dist/{chunk-AKPLOO2V.js → chunk-Y3AMO6WC.js} +1 -1
- package/dist/{chunk-TCHBOWQ5.js → chunk-YVS565QY.js} +1 -1
- package/dist/{chunk-TKDT7EQO.js → chunk-Z4D3L2HR.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{config-HR4MBTIS.js → config-EMNKHR3W.js} +1 -1
- package/dist/{db-6KUGCGVR.js → db-YUYXVV3A.js} +1 -1
- package/dist/{delivery-log-7DJJTPXL.js → delivery-log-VKONLSVD.js} +1 -1
- package/dist/engine-BM5BMPIC.js +1 -0
- package/dist/{evolution-audit-I2ITWAEC.js → evolution-audit-LZSQPDHH.js} +1 -1
- package/dist/index.js +18 -12
- package/dist/{learner-CBPQZ3HL.js → learner-IJN6B7KV.js} +1 -1
- package/dist/{memories-HBBW44MG.js → memories-ZII5QSTJ.js} +1 -1
- package/dist/{memory-extractor-XO2HJ22Y.js → memory-extractor-DIYJFBCI.js} +2 -2
- package/dist/memory-service-QMYJPBAE.js +1 -0
- package/dist/outbound-gateway-6K6P2BEH.js +1 -0
- package/dist/role-presets-K2BDRZBS.js +1 -0
- package/dist/roles-L34L5MK3.js +1 -0
- package/dist/{session-manager-JICVE4CO.js → session-manager-GRJ3FV3L.js} +1 -1
- package/dist/{task-templates-NC7XIZIC.js → task-templates-23YOAF3E.js} +1 -1
- package/dist/workflow-executor-JTUWX5DC.js +1 -0
- package/package.json +2 -2
- package/web/dist/assets/AlertDialog-r3y6IhpW.js +51 -0
- package/web/dist/assets/Button-BjXgrQ95.js +1 -0
- package/web/dist/assets/Card-C153tGfJ.js +1 -0
- package/web/dist/assets/ChannelDetail-C2uAZv1u.js +1 -0
- package/web/dist/assets/Channels-C62Qrg-n.js +12 -0
- package/web/dist/assets/Chat-kH2owmB_.js +1 -0
- package/web/dist/assets/Dashboard-BhD8SpFb.js +1 -0
- package/web/dist/assets/EmptyState-CXwJFCDQ.js +1 -0
- package/web/dist/assets/EnvVarEditor-GSapLD96.js +1 -0
- package/web/dist/assets/Evolution-BO5hysLD.js +6 -0
- package/web/dist/assets/GoalDetail-cxa8OvEi.js +1 -0
- package/web/dist/assets/Goals-Dz3qqp_l.js +1 -0
- package/web/dist/assets/Logs-Ckp3-hYV.js +1 -0
- package/web/dist/assets/Memories-DEuSRoP3.js +1 -0
- package/web/dist/assets/NotFound-Bvn39vSk.js +1 -0
- package/web/dist/assets/PageHeader-BMvN0xiB.js +1 -0
- package/web/dist/assets/Plugins-CRym22JF.js +1 -0
- package/web/dist/assets/RoleDetail-BWMjP9aZ.js +33 -0
- package/web/dist/assets/Roles-DD7NBDku.js +1 -0
- package/web/dist/assets/SectionHeader-CiCj3Is0.js +1 -0
- package/web/dist/assets/Settings-BlU19KuR.js +1 -0
- package/web/dist/assets/Strategies-CJ_q94-v.js +1 -0
- package/web/dist/assets/Switch-CoUUy5jr.js +1 -0
- package/web/dist/assets/Table-CaFJieh_.js +1 -0
- package/web/dist/assets/TaskDetail-DVrjU-E6.js +2 -0
- package/web/dist/assets/Work-BMl61RRi.js +1 -0
- package/web/dist/assets/dist-Bdqp1ixJ.js +1 -0
- package/web/dist/assets/index-DcXMQByM.css +2 -0
- package/web/dist/assets/index-pF--tN9F.js +2 -0
- package/web/dist/assets/ui-B_uMx2Fy.js +1 -0
- package/web/dist/assets/useIsMobileLayout-Bwrm84kJ.js +1 -0
- package/web/dist/assets/vendor-icons-BlMaTTx3.js +1 -0
- package/web/dist/assets/{vendor-react-DLRtONKt.js → vendor-react-7e01TWy7.js} +2 -2
- package/web/dist/assets/vendor-state-Bj70wnRm.js +1 -0
- package/web/dist/index.html +8 -6
- package/dist/App-3OBJDI2C.js +0 -9
- package/dist/adam-tools-4LZYFB6J.js +0 -1
- package/dist/audit-manager-6FFPXID3.js +0 -1
- package/dist/bree-engine-2NOTIBAZ.js +0 -1
- package/dist/channels-TSZLEU3L.js +0 -1
- package/dist/chunk-6NUHSHS5.js +0 -4
- package/dist/chunk-72VLUJ2S.js +0 -1
- package/dist/chunk-7CJGPCSJ.js +0 -49
- package/dist/chunk-NLD7WK3R.js +0 -6
- package/dist/chunk-OTH4M5L3.js +0 -8
- package/dist/chunk-PVYEGQEG.js +0 -83
- package/dist/chunk-XTHP5JMO.js +0 -10
- package/dist/chunk-ZKMDHQJY.js +0 -104
- package/dist/engine-HJUE6I4I.js +0 -1
- package/dist/memory-service-HIFTKEW2.js +0 -1
- package/dist/outbound-gateway-GGFMU5JW.js +0 -1
- package/dist/role-presets-W452Y3RV.js +0 -1
- package/dist/roles-NYGWZMQI.js +0 -1
- package/dist/workflow-executor-QN4KP7B4.js +0 -1
- package/web/dist/assets/Card-4mOZntHG.js +0 -1
- package/web/dist/assets/ChannelDetail-DX4QnE8j.js +0 -1
- package/web/dist/assets/Channels-EXkNOQpB.js +0 -12
- package/web/dist/assets/Chat-Da-mCR0c.js +0 -1
- package/web/dist/assets/Dashboard-Bq6sEDdP.js +0 -1
- package/web/dist/assets/EmptyState-BlgMMAr-.js +0 -1
- package/web/dist/assets/EnvVarEditor-CNxXpVbD.js +0 -1
- package/web/dist/assets/Evolution-DPdmbooj.js +0 -6
- package/web/dist/assets/GoalDetail-BamCfVzS.js +0 -1
- package/web/dist/assets/Goals-CHPEg0RK.js +0 -1
- package/web/dist/assets/Logs-BHkBvH0T.js +0 -1
- package/web/dist/assets/Memories-BY2pJhVd.js +0 -1
- package/web/dist/assets/NotFound-CSjhzSGa.js +0 -1
- package/web/dist/assets/Plugins-C5xLM0BU.js +0 -1
- package/web/dist/assets/RoleDetail-Dnp-W14x.js +0 -33
- package/web/dist/assets/Roles-BVOVoHvc.js +0 -1
- package/web/dist/assets/Settings-eBHvn6s_.js +0 -1
- package/web/dist/assets/Strategies-BbFbLKBJ.js +0 -1
- package/web/dist/assets/Switch-Q-inggPs.js +0 -1
- package/web/dist/assets/Table-BxbnOSbq.js +0 -1
- package/web/dist/assets/TaskDetail-BEjZ1gco.js +0 -2
- package/web/dist/assets/Work-CF2iLs8i.js +0 -1
- package/web/dist/assets/dist-HyCSN_hp.js +0 -1
- package/web/dist/assets/index-CaHdOfAc.js +0 -52
- package/web/dist/assets/index-D0SvKqKc.css +0 -2
- package/web/dist/assets/vendor-icons-CkI4-NxL.js +0 -1
- package/web/dist/assets/vendor-state-B_-GdGNJ.js +0 -1
- /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** |
|
|
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 +
|
|
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 | `
|
|
249
|
-
| 4 | `
|
|
250
|
-
| 5 | `
|
|
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
|
-
- **
|
|
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&>>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&>>0&&Kt(B=>B-1),y.downArrow&><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{k as a,l as b}from"./chunk-2YAP4YJV.js";import"./chunk-5XUR3M23.js";import"./chunk-H54ZXA26.js";import"./chunk-BR2JY5X2.js";import"./chunk-6775OYXA.js";import"./chunk-5V36ACKZ.js";import"./chunk-VRJ7R766.js";import"./chunk-Y3AMO6WC.js";import"./chunk-ISZJV72D.js";import"./chunk-23VZKIB6.js";import"./chunk-Z4D3L2HR.js";import"./chunk-2DLVAKH7.js";import"./chunk-HDP7A4XY.js";import"./chunk-QWCRZDZS.js";import"./chunk-L7JP7DUO.js";import"./chunk-R4GIIQ7G.js";import"./chunk-2CMR5AG7.js";import"./chunk-C6BOQJJF.js";import"./chunk-S3BAIZ4Q.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-GBTG5B5R.js";import"./chunk-7L2WQM7N.js";import"./chunk-JAS3TUZX.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-
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-YVS565QY.js";import"./chunk-XL46AGRZ.js";import"./chunk-23VZKIB6.js";import"./chunk-L7JP7DUO.js";import"./chunk-QVKI7H7W.js";import"./chunk-JAS3TUZX.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-RAW263MQ.js";import"./chunk-5XUR3M23.js";import"./chunk-H54ZXA26.js";import"./chunk-YHVFZB6Q.js";import"./chunk-VRJ7R766.js";import"./chunk-Y3AMO6WC.js";import"./chunk-ISZJV72D.js";import"./chunk-5S6BMWD2.js";import"./chunk-DZEVMYPB.js";import"./chunk-QWCRZDZS.js";import"./chunk-L7JP7DUO.js";import"./chunk-QVKI7H7W.js";import"./chunk-R4GIIQ7G.js";import"./chunk-2CMR5AG7.js";import"./chunk-C6BOQJJF.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-GBTG5B5R.js";import"./chunk-7L2WQM7N.js";import"./chunk-JAS3TUZX.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-MTWLLE26.js";import"./chunk-GY52JA5I.js";import"./chunk-6775OYXA.js";import"./chunk-5V36ACKZ.js";import"./chunk-YHVFZB6Q.js";import"./chunk-VRJ7R766.js";import"./chunk-Y3AMO6WC.js";import"./chunk-ISZJV72D.js";import"./chunk-XL46AGRZ.js";import"./chunk-23VZKIB6.js";import"./chunk-QWCRZDZS.js";import"./chunk-L7JP7DUO.js";import"./chunk-QVKI7H7W.js";import"./chunk-C6BOQJJF.js";import"./chunk-S3BAIZ4Q.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-GBTG5B5R.js";import"./chunk-7L2WQM7N.js";import"./chunk-JAS3TUZX.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-
|
|
1
|
+
import{a,b,c,d,e,f}from"./chunk-23VZKIB6.js";import"./chunk-JAS3TUZX.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-6FXNB7NE.js";import"./chunk-23VZKIB6.js";import"./chunk-HDP7A4XY.js";import"./chunk-JAS3TUZX.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{b as s,d as i}from"./chunk-
|
|
1
|
+
import{b as s,d as i}from"./chunk-JAS3TUZX.js";i();function l(e){return{id:e.id,name:e.name,platform:e.platform,enabled:e.enabled===1,status:e.status,config:JSON.parse(e.config),linkedRoleId:e.linked_role_id??void 0,allowedChatIds:e.allowed_chat_ids?JSON.parse(e.allowed_chat_ids):void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function o(e){s().prepare(`
|
|
2
2
|
INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
|
|
3
3
|
allowed_chat_ids, created_at, updated_at, last_message_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-JAS3TUZX.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
|
|
2
2
|
INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
|
|
3
3
|
title, created_at, last_active_at, archived_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import{a as qe,c as We,d as ze,e as Ye}from"./chunk-5XUR3M23.js";import{b as Le,c as se,e as Oe}from"./chunk-H54ZXA26.js";import{a as Be,c as ce,e as Je}from"./chunk-BR2JY5X2.js";import{a as E,b as Ce,c as Pe,d as De,e as xe,f as Ae,h as Me,i as H,j as N,k as Q,l as $e,m as Ne,n as L,o as Ee,p as x,q as ie}from"./chunk-6775OYXA.js";import{a as Ue}from"./chunk-5V36ACKZ.js";import{a as we,b as ke,c as z,d as Te,e as Se,f as Re,g as ct,h as _e,i as _,k as Y}from"./chunk-VRJ7R766.js";import{b as he}from"./chunk-Y3AMO6WC.js";import{b as P,c as U,d as M}from"./chunk-ISZJV72D.js";import{d as le}from"./chunk-23VZKIB6.js";import{j as de}from"./chunk-Z4D3L2HR.js";import{e as ne,f as B,g as ve,i as re,j as J}from"./chunk-QWCRZDZS.js";import{a as oe}from"./chunk-L7JP7DUO.js";import{g as je}from"./chunk-C6BOQJJF.js";import{a as ae,b as O,c as Ge,f as Ve,g as Fe}from"./chunk-S3BAIZ4Q.js";import{d as T,j as ge}from"./chunk-GSMC3VUM.js";import{f as be,g as ee,i as dt,k as ye,l as v,n as $,o as D,p as Ie,q as te,r as W}from"./chunk-GBTG5B5R.js";import{c as A,d as fe,h as Z}from"./chunk-INNDBLZE.js";import{f as C}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Tt,tool as u}from"@anthropic-ai/claude-agent-sdk";import{z as n}from"zod";W();J();import{v4 as q}from"uuid";Z();var ut=A("goal-manager");async function Sn(e){let t;try{let r=JSON.parse(e);t={name:r.name??"",description:r.description,metric:r.metric??"",targetValue:r.targetValue??0,currentValue:r.currentValue??0,deadline:r.deadline??0,budget:r.budget??0,roleId:r.roleId??"engineer",status:"active"}}catch{t=await pt(e)}let o=mt(t);return{goalState:t,validationResult:o,rawInput:e}}async function pt(e){let t=`Extract SMART goal fields from this natural language input.
|
|
2
|
+
|
|
3
|
+
Input: "${e}"
|
|
4
|
+
|
|
5
|
+
Respond ONLY with a JSON object:
|
|
6
|
+
{
|
|
7
|
+
"name": "short goal name (max 100 chars)",
|
|
8
|
+
"description": "detailed description of what the goal aims to achieve",
|
|
9
|
+
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
10
|
+
"targetValue": <number, the target to reach>,
|
|
11
|
+
"deadline_days": <number, days from now to complete>,
|
|
12
|
+
"budget": <number, estimated budget in USD>,
|
|
13
|
+
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
Rules:
|
|
17
|
+
- name: concise, actionable title
|
|
18
|
+
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
19
|
+
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
20
|
+
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
21
|
+
- budget: estimated cost in USD; default 5 if unclear
|
|
22
|
+
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let r=(await Ue(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(r){let i=JSON.parse(r[0]),a=i.deadline_days??7;return{name:(i.name??e.slice(0,100)).slice(0,100),description:i.description??e,metric:i.metric??"completion",targetValue:i.targetValue??1,currentValue:0,deadline:Date.now()+a*24*60*60*1e3,budget:i.budget??5,roleId:i.roleId??"engineer",status:"active"}}}catch(o){ut.warn({error:o},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function mt(e){let t=[],o=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&o.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:o}}function Rn(e,t,o){let r=q(),i=Date.now(),a={id:r,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:i,deliverTo:t,reportTo:o};return H(a),a}function He(e,t){let o=Date.now(),r=[],i={id:q(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:o};r.push(i),L(i);let a={id:q(),goalId:e,level:"L1",parentId:i.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:o};r.push(a),L(a);let l={id:q(),goalId:e,level:"L2",parentId:a.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:o};r.push(l),L(l);let d={id:q(),goalId:e,level:"L3",parentId:l.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:o};return r.push(d),L(d),r}var gt=3,ft=2,K=class{static async generateVariants(t,o,r=gt,i=ft){let a=x.getTopStrategies(t,o,r);if(a.length===0){let d=`baseline-${o}-v1`;return x.addStrategy(t,o,d,this.generateBaselinePrompt(t,o)),[d]}let l=[];for(let d=0;d<i;d++){let m=a[0].totalTrials+d+1,c=`${o}-evolved-v${m}`,f=a[0].promptTemplate,g=this.mutateTemplate(f);x.addStrategy(t,o,c,g),l.push(c)}return l}static generateBaselinePrompt(t,o){return`You are a ${t} agent specializing in ${o}.
|
|
23
|
+
|
|
24
|
+
## Core Focus
|
|
25
|
+
Complete tasks with high quality.
|
|
26
|
+
|
|
27
|
+
## Approach
|
|
28
|
+
1. Understand the task requirements thoroughly
|
|
29
|
+
2. Plan your approach before executing
|
|
30
|
+
3. Execute systematically, checking your work
|
|
31
|
+
4. Verify completion against requirements`}static mutateTemplate(t){let o=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],r=o[Math.floor(Math.random()*o.length)];return`${t}
|
|
32
|
+
|
|
33
|
+
## Evolution
|
|
34
|
+
${r}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,o,r){return{promptTemplate:this.generateBaselinePrompt(t,o),rationale:"Generated baseline - LLM integration in Phase 5"}}};Z();_e();import{v4 as w}from"uuid";import{spawnSync as Qe}from"child_process";import{createRequire as ht}from"module";import{dirname as bt,join as Ke}from"path";import{openSync as yt,readFileSync as It,unlinkSync as vt}from"fs";var wt=3e4,Xe=12e4;function Ze(){let t=ht(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return Ke(bt(t),"cli.js")}function j(e,t){let o=Ze(),r=t?.timeout??wt;if(t?.json){let a=Ke("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),l=yt(a,"w");try{let d=Qe("node",[o,...e],{cwd:t.cwd,timeout:r,stdio:["ignore",l,"pipe"],encoding:"utf-8"});if(d.status!==0)throw new Error(d.stderr?.trim()||`CLI exited with status ${d.status}`);return It(a,"utf-8")}finally{try{vt(a)}catch{}}}let i=Qe("node",[o,...e],{cwd:t?.cwd,timeout:r,encoding:"utf-8"});if(i.status!==0)throw new Error(i.stderr?.trim()||`CLI exited with status ${i.status}`);return i.stdout}function et(){let e=j(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function ue(e,t="user",o){return j(["plugin","install",e,"--scope",t],{cwd:o,timeout:Xe})}function pe(e,t,o){let r=["plugin","uninstall",e];return t&&r.push("--scope",t),j(r,{cwd:o,timeout:Xe})}function tt(e,t){return j(["plugin","enable",e])}function nt(e,t){return j(["plugin","disable",e])}function $n(){try{return!!Ze()}catch{return!1}}Z();import*as rt from"crypto";var G=A("api"),V=class{cancelTask(t){let o=P(t);o&&(U(t,{status:"cancelled",completedAt:Date.now()}),oe.emit({type:"task_status_change",taskId:t,oldStatus:o.status,newStatus:"cancelled"}),G.debug({taskId:t,oldStatus:o.status},"Task cancelled"))}resolveApproval(t,o,r){return G.debug({approvalId:t,action:o,reason:r},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,o,r,i){let a=Le(t);if(!a)return G.warn({planId:t},"Plan not found or already resolved"),!1;let l=P(a.taskId);return l?(Oe(t,o==="allow"?"approved":"denied",r),o==="allow"&&r==="permanent"&&qe({id:rt.randomUUID(),roleId:a.roleId,taskPattern:l.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:a.plan.overallRisk,createdAt:Date.now(),createdByTaskId:l.id}),oe.emit({type:"plan_approval_decision",taskId:l.id,planId:t,decision:o,approvalType:r,reason:i}),G.debug({planId:t,decision:o,approvalType:r},"Plan approval resolved"),!0):(G.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as ot}from"fs";dt();var F=A("manager");function s(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function k(e){let{listChannels:t}=await import("./channels-HYSB2EEK.js"),o=t(),{listSessions:r}=await import("./session-manager-GRJ3FV3L.js"),i=[...r("active"),...r("archived")],a=[];for(let l of e)if(l.type==="session"&&l.sessionId)a.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,m=l.chatId;if(!d&&l.channelName){let c=o.find(f=>f.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!m){let c=i.find(f=>f.source.type==="channel"&&f.source.channelId===d&&f.source.chatId);c?.source.chatId?m=c.source.chatId:m=o.find(g=>g.id===d)?.config?.userId}d&&m?a.push({type:"channel",channelId:d,chatId:m}):F.warn({channelName:l.channelName,channelId:d,chatId:m},"Could not resolve channel notify target")}return a}async function St(e){let{listRoles:t}=await import("./roles-L34L5MK3.js"),o=t(void 0,100,0);for(let r of o)if(r.name.toLowerCase().includes(e.toLowerCase()))return r.id}var Rt={goalId:n.string()},_t={goalId:n.string(),status:n.string().optional(),currentValue:n.number().optional(),budgetUsd:n.number().optional(),notes:n.string().optional()},Ct={goalId:n.string(),goalDescription:n.string(),maxSubtasks:n.number().optional()},S=n.union([n.object({type:n.literal("session"),sessionId:n.string()}),n.object({type:n.literal("channel"),channelName:n.string()}),n.object({type:n.literal("channel"),channelId:n.string(),chatId:n.string().optional()})]),Pt={prompt:n.string(),roleId:n.string().optional().describe("Role ID. Call list_roles(requirements) first to find the best role for the task."),requirements:E.optional(),autoSelectRole:n.boolean().optional(),deliverTo:n.array(S).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:n.array(S).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:n.object({allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional()}).optional()},Dt={taskId:n.string(),goalId:n.string().optional(),strategyId:n.string().optional()},xt={roleId:n.string(),taskType:n.string(),name:n.string().optional()},At={status:n.string().optional(),limit:n.number().optional()},Mt={taskId:n.string(),roleId:n.string()},$t={taskId:n.string().optional(),status:n.string().optional(),limit:n.number().optional()},Nt={roleId:n.string(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional(),allowedChannels:n.array(n.string()).optional(),inheritUserSettings:n.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Ut={roleId:n.string().describe("Role ID to update."),name:n.string().min(1).optional(),cagPrompt:n.string().optional(),learnedRules:n.array(n.string()).optional(),status:n.enum(["active","inactive","retired"]).optional(),executionMode:n.enum(["isolated","inline"]).optional(),model:n.string().optional(),maxBudgetUsd:n.number().optional(),approvalRequired:n.array(n.string()).optional(),preferences:n.object({model:n.string().optional(),effort:n.enum(["low","medium","high","max"]).optional(),maxTurns:n.number().optional()}).optional(),permissionMode:n.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:n.array(n.string()).optional(),deniedBashPatterns:n.array(n.string()).optional(),evaluationCriteria:n.record(n.string(),n.number()).optional(),envVars:n.record(n.string(),n.string()).optional()},Et={roleId:n.string().optional(),limit:n.number().optional()},Lt={name:n.string(),cagPrompt:n.string(),traits:n.array(n.string()).optional(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional()},Ot={roleId:n.string(),reason:n.string().optional()},qt={name:n.string(),description:n.string().optional(),roleId:n.string().optional(),metric:n.string().optional(),targetValue:n.number().optional(),deadline:n.number().optional(),budgetUsd:n.number().optional(),deliverTo:n.array(S).optional().describe("Where to deliver goal completion notifications.")},jt={name:n.string(),description:n.string().optional(),triggerType:n.enum(["cron","event"]),triggerCron:n.string().optional(),triggerEvent:n.string().optional(),prompt:n.string(),roleId:n.string().optional(),requirements:E.optional(),autoSelectRole:n.boolean().optional(),enabled:n.boolean().optional(),goalIds:n.array(n.string()).optional(),deliverTo:n.array(S).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(S).optional().describe("Where to send status reports (completion summary).")},Gt={status:n.enum(["active","retired","probation"]).optional(),limit:n.number().optional(),requirements:E.optional()},Vt={enabled:n.boolean().optional()},Ft={},Wt={},Bt={prompt:n.string().describe("The task prompt to execute after the delay"),delayMinutes:n.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:n.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:n.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:n.array(S).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(S).optional().describe("Where to send status reports (completion summary).")},Jt={roleId:n.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},zt={roleId:n.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:n.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Yt={roleId:n.string().describe("Role ID to uninstall the plugin from."),pluginId:n.string().describe("Plugin ID to uninstall.")},Ht={roleId:n.string().describe("Role ID to bind the MCP server to."),mcpName:n.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:n.record(n.string(),n.unknown()).describe("MCP server configuration object.")},Qt={roleId:n.string().describe("Role ID to unbind the MCP server from."),mcpName:n.string().describe("Name of the MCP server to remove.")},Kt={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Xt={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Zt={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},en={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},tn={},nn={},rn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},on={roleId:n.string().describe("Role ID to associate scanned plugins with."),path:n.string().describe("Directory path to scan for .claude/settings.json.")},sn={taskId:n.string().describe("Task ID to cancel.")},an={taskId:n.string().describe("Task ID to get logs for."),limit:n.number().optional().describe("Max log entries (default 20).")},ln={roleId:n.string().describe("Role ID to delete.")},dn={},cn={updates:n.record(n.string(),n.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},un={roleId:n.string().describe("Role ID to list memories for."),limit:n.number().optional().describe("Max results (default 20).")},pn={templateId:n.string().describe("Template ID to update."),name:n.string().optional(),enabled:n.boolean().optional(),prompt:n.string().optional(),triggerCron:n.string().optional(),triggerEvent:n.string().optional(),roleId:n.string().optional()},mn={templateId:n.string().describe("Template ID to delete.")},gn={templateId:n.string().describe("Template ID to run immediately.")},fn={enabled:n.boolean().optional().describe("Filter by enabled status.")},hn={eventType:n.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:n.string().describe("Channel ID to deliver to."),format:n.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:n.record(n.string(),n.unknown()).optional().describe("JSON match criteria for event fields."),enabled:n.boolean().optional().describe("Enable this rule immediately (default true).")},bn={ruleId:n.string().describe("Delivery rule ID to delete.")},yn={roleId:n.string().optional().describe("Role ID to filter strategies by.")},it=[u("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",Rt,async e=>{let t=N(e.goalId);if(!t)return s({error:"Goal not found"});let o=Date.now(),r=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:r,timeRemainingMs:Math.max(0,t.deadline-o),budgetRemainingUsd:t.budgetUsd})}),u("update_goal_state","Update a goal's status, current value, or budget.",_t,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),Q(e.goalId,t)),s({success:!0})}),u("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Ct,async e=>{let t=T(),o=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),l=`Decompose this goal into ${o} actionable subtasks.
|
|
35
|
+
|
|
36
|
+
Goal: ${e.goalDescription}
|
|
37
|
+
|
|
38
|
+
Respond ONLY with a JSON array. Each item:
|
|
39
|
+
{
|
|
40
|
+
"description": "...",
|
|
41
|
+
"prompt": "detailed task instruction",
|
|
42
|
+
"complexity": "low|medium|high",
|
|
43
|
+
"role": "engineer|analyst|content_creator|reviewer",
|
|
44
|
+
"requirements": {
|
|
45
|
+
"tools": ["Read", "Write"],
|
|
46
|
+
"paths": [{"path": "/abs/path", "access": "ro"}],
|
|
47
|
+
"osCapabilities": [{"id": "automation", "targets": ["bundle.id"]}],
|
|
48
|
+
"network": false
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
Rules:
|
|
53
|
+
- Each subtask must be independently executable
|
|
54
|
+
- Order from foundational to dependent
|
|
55
|
+
- Be specific about what each subtask should accomplish
|
|
56
|
+
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.
|
|
57
|
+
- Include tools and paths required for the subtask where known. If unknown, omit the field.`,d=a({prompt:l,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),m="";for await(let f of d){let g=f;g.type==="result"&&typeof g.result=="string"&&(m=g.result)}let c=m.match(/\[[\s\S]*\]/);if(c){let f=JSON.parse(c[0]),g=[];for(let h=0;h<Math.min(f.length,o);h++){let I=f[h],R=I.role,p=R?await St(R):void 0,b=await ie({prompt:I.prompt,roleId:p,requirements:I.requirements,config:t.defaults});if(!b.ok){g.push({id:`admission-failed-${h}`,description:I.description,prompt:I.prompt,dependencies:h>0&&g.length>0?[g[h-1].id]:[],estimatedComplexity:I.complexity??"medium",role:R,admissionError:`${b.code}: ${b.reason}`});continue}g.push({id:b.taskId,description:I.description,prompt:I.prompt,dependencies:h>0?[g[h-1].id]:[],estimatedComplexity:I.complexity??"medium",role:R})}if(g.length>0)return s({subtasks:g})}}catch(a){F.error({error:a},"LLM decomposition failed, using fallback")}let r=await Ae({taskId:w(),roleId:void 0,autoSelectRole:!1}),i=[];return r.ok||i.push({id:"admission-blocked",description:`Decomposition fallback blocked: ${r.reason}`,prompt:e.goalDescription,dependencies:[],estimatedComplexity:"medium",admissionError:`${r.code}: ${r.reason}`}),s({subtasks:i})}),u("dispatch_task","Create and dispatch a task. Workflow: (1) call list_roles(requirements) to find candidate roles by fit; (2) call dispatch_task with requirements AND the chosen roleId. requirements is STRONGLY RECOMMENDED \u2014 when present, admission validates role fit before creation and returns structured mismatch diagnostics. If you cannot produce clear requirements from the user's message, ASK THE USER instead of dispatching. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Pt,async e=>{if(!e.roleId&&!e.autoSelectRole){let i=D("active",20,0).filter(a=>a.source!=="system").map(a=>({id:a.id,name:a.name,allowedTools:a.allowedTools??[],capabilitySummary:_(a)}));return s({error:"Must provide roleId or autoSelectRole=true with requirements.",availableRoles:i})}let t=e.deliverTo?await k(e.deliverTo):void 0,o=e.reportTo?await k(e.reportTo):void 0,r=await ie({prompt:e.prompt,roleId:e.roleId,requirements:e.requirements,autoSelectRole:e.autoSelectRole,deliverTo:t,reportTo:o,toolOverrides:e.toolOverrides});if(!r.ok){let i=(r.candidates??[]).map(l=>({id:l.roleId,name:l.name,fitScore:l.fitScore,missing:l.missing})),a=i.length>0?i:D("active",20,0).filter(l=>l.source!=="system").map(l=>({id:l.id,name:l.name,allowedTools:l.allowedTools??[],capabilitySummary:_(l)}));return s({error:r.reason,code:r.code,missing:r.missing,availableRoles:a})}return s({taskId:r.taskId,roleId:r.roleId,fitScore:r.fitScore,strategyId:r.strategyId,warnings:r.warnings})}),u("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:n.array(n.object({id:n.string().describe("Unique step identifier"),prompt:n.string().describe("Task prompt for this step"),roleId:n.string().optional().describe("Role ID for this step. Call list_roles first to find roles."),requirements:E.optional().describe("Task requirements for this step (D-012)."),autoSelectRole:n.boolean().optional().describe("Auto-select best role for this step (D-012)."),dependsOn:n.array(n.string()).optional().describe("Step IDs this step depends on"),config:n.object({timeout:n.number().optional(),maxTurns:n.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:n.string().optional().describe("Workflow name for tracking"),deliverTo:n.array(S).optional().describe("Where to deliver the aggregated workflow output"),reportTo:n.array(S).optional().describe("Where to send workflow status reports"),continueOnError:n.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let p of e.steps){if(!p.roleId&&!p.autoSelectRole){t.push(`${p.id} (needs roleId or autoSelectRole)`);continue}if(p.roleId){let b=v(p.roleId);(!b||b.status!=="active")&&t.push(`${p.id} (roleId ${p.roleId} invalid/inactive)`)}}if(t.length>0){let p=D("active",20,0).filter(b=>b.source!=="system").map(b=>({id:b.id,name:b.name,capabilitySummary:_(b)}));return s({error:`Steps missing roleId/autoSelectRole or with invalid roleIds: ${t.join("; ")}.`,availableRoles:p})}let o=new Set(e.steps.map(p=>p.id));for(let p of e.steps)if(p.dependsOn)for(let b of p.dependsOn){if(!o.has(b))return s({error:`Step "${p.id}" depends on unknown step "${b}"`});if(b===p.id)return s({error:`Step "${p.id}" cannot depend on itself`})}let r=new Set,i=new Set,a=new Map(e.steps.map(p=>[p.id,p.dependsOn??[]])),l=p=>{if(i.has(p))return!0;if(r.has(p))return!1;r.add(p),i.add(p);for(let b of a.get(p)??[])if(l(b))return!0;return i.delete(p),!1};for(let p of e.steps)if(l(p.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await k(e.deliverTo):void 0,m=e.reportTo?await k(e.reportTo):void 0,c=w(),f=T(),g={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(p=>({id:p.id,prompt:p.prompt,roleId:p.roleId,requirements:p.requirements,autoSelectRole:p.autoSelectRole,dependsOn:p.dependsOn,config:p.config})),enabled:!0,createdAt:Date.now(),config:{...f.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:m};ae(g);let{WorkflowExecutor:h}=await import("./workflow-executor-JTUWX5DC.js");new h().execute(g,c).catch(p=>{F.error({executionId:c,error:p},"dispatch_workflow execution failed")});let R=e.steps.map(p=>{let b=p.roleId??(p.autoSelectRole?"[auto-selected]":"[no role]");return(p.roleId?v(p.roleId):void 0)?.name??b});return s({executionId:c,templateId:g.id,stepCount:e.steps.length,roles:[...new Set(R)],status:"started"})}),u("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Dt,async e=>{let{goalId:t,taskId:o,strategyId:r}=e,i=Ee(t??"",o);return r&&t&&x.recordTrial(r,t,o,i.reward,i.breakdown.L2||void 0,i.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:i.reward,metricL2Score:i.breakdown.L2||void 0,metricL3Score:i.breakdown.L3||void 0,source:i.source,reasoning:`Evaluated via ${i.source} with confidence ${i.confidence.toFixed(2)}`})}),u("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",xt,async e=>{let{roleId:t,taskType:o}=e;await K.generateVariants(t,o,3,1);let r=x.getStrategies(t,o),i=r[r.length-1];return s(i?{id:i.id,name:i.name,promptTemplate:i.promptTemplate}:{error:`Failed to create strategy for ${t}/${o}`})}),u("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",At,async e=>{let t=e.status;return s($e(t,e.limit??10,0))}),u("delete_goal","Delete a goal by ID.",{goalId:n.string()},async e=>N(e.goalId)?(Ne(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),u("pause_goal","Pause an active goal.",{goalId:n.string()},async e=>N(e.goalId)?(Q(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),u("assign_role","Assign a role to a pending task.",Mt,async e=>{let{taskId:t,roleId:o}=e;if(!P(t))return s({error:`Task not found: ${t}`});let i=v(o);return i?(U(t,{roleId:o}),F.debug({taskId:t,roleId:o,roleName:i.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:o})):s({error:`Role not found: ${o}`})}),...We(),u("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",$t,async e=>{if(e.taskId){let o=P(e.taskId);return s(o??{error:"Task not found"})}let t=e.status;return s(M(t,e.limit??100,0))}),u("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Nt,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let o={};if(e.allowedTools&&(o.allowedTools=e.allowedTools),e.disallowedTools&&(o.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{o.osCapabilities=ee(e.osCapabilities)}catch(r){return s({error:r instanceof Error?r.message:String(r)})}return e.additionalDirectories!==void 0&&(o.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(o.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(o.inheritUserSettings=e.inheritUserSettings),$(e.roleId,o),s({success:!0})}),u("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Ut,async e=>{if(!v(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:o,...r}=e,i={...r,updatedAt:Date.now()};$(o,i);let a=v(o);if(!a)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=ne(a.name);ot(l)&&ve(l,a)}return s({success:!0,role:a})}),u("view_audit_log","View the evolution audit log for role changes.",Et,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-LZSQPDHH.js"),o=t(e.limit??50);return s({entries:o})}),u("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks. Pass requirements to get ranked results with fitScore showing which roles best match the task.",Gt,async e=>{if(e.requirements){let r=e.requirements,a=xe(r).slice(0,e.limit??50).map(l=>{let d=l.role,m=Y(d),c=m.plugins.map(y=>y.name),f=ne(d.name),g=Ce(d,f),h=r.tools?(d.allowedTools??[]).filter(y=>r.tools.includes(y)):void 0,I=r.paths?r.paths.filter(y=>Pe(y,g)):void 0,R=new Set((d.osCapabilities??[]).map(y=>y.id)),p=r.osCapabilities?r.osCapabilities.filter(y=>R.has(y.id)).map(y=>y.id):void 0,b=new Set(c),me=r.plugins?r.plugins.filter(y=>b.has(y)):void 0,st=r.network===!0?(d.osCapabilities??[]).some(y=>y.id==="local-network"):void 0,at=l.missing?.osCapabilities,lt=De(d,r);return{id:d.id,name:d.name,status:d.status,allowedTools:d.allowedTools??[],disallowedTools:d.disallowedTools??[],osCapabilities:d.osCapabilities??[],additionalDirectories:d.additionalDirectories??[],cagPrompt:d.cagPrompt.slice(0,500)+(d.cagPrompt.length>500?"...":""),capabilitySummary:_(d,m),plugins:m.plugins.map(y=>({name:y.name,skills:y.skills.map(X=>X.name),agents:y.agents.map(X=>X.name)})),fitScore:l.fitScore,fits:l.evaluation.ok,matchedTools:h,matchedPaths:I,matchedOsCapabilities:p,matchedPlugins:me,matchedNetwork:st,missingCapabilities:l.missing?{tools:l.missing.tools,paths:l.missing.paths,osCapabilities:at?.map(y=>y.id),plugins:l.missing.plugins,network:l.missing.network}:void 0,warnings:lt,why:l.evaluation.ok?`Role '${d.name}' satisfies all requirements (fitScore: ${l.fitScore.toFixed(2)})`:`Role '${d.name}' does not satisfy requirements: ${l.evaluation.ok?"unknown":l.evaluation.reason}`}});return s({roles:a})}let o=D(e.status,e.limit??50,0).map(r=>{let i=Y(r);return{id:r.id,name:r.name,status:r.status,allowedTools:r.allowedTools??[],disallowedTools:r.disallowedTools??[],osCapabilities:r.osCapabilities??[],additionalDirectories:r.additionalDirectories??[],cagPrompt:r.cagPrompt.slice(0,500)+(r.cagPrompt.length>500?"...":""),capabilitySummary:_(r,i),plugins:i.plugins.map(a=>({name:a.name,skills:a.skills.map(l=>l.name),agents:a.agents.map(l=>l.name)}))}});return s({roles:o})}),u("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",Lt,async e=>{let t;try{t=ee(e.osCapabilities)}catch(i){return s({error:i instanceof Error?i.message:String(i)})}let o=`role-${w().slice(0,8)}`,r={id:o,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${w().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return ye(r),B(r),s({roleId:o,name:e.name,allowedTools:e.allowedTools,osCapabilities:r.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),u("retire_role","Retire a role (marks as retired, stops receiving tasks).",Ot,async e=>v(e.roleId)?($(e.roleId,{status:"retired"}),F.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),u("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",qt,async e=>{let t=w(),o=Date.now(),r=o+10080*60*1e3,i={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??r,budgetUsd:e.budgetUsd??5,status:"active",createdAt:o,deliverTo:e.deliverTo?await k(e.deliverTo):void 0};H(i),He(t,i.metricType);let a=N(t);return s({goalId:a.id,name:a.name,status:a.status})}),u("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",jt,async e=>{let{createTaskTemplate:t}=await import("./task-templates-23YOAF3E.js"),o=w(),r=w(),i=e.deliverTo?await k(e.deliverTo):void 0,a=e.reportTo?await k(e.reportTo):void 0,l={id:o,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:r,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:i,reportTo:a};return t(l),s({templateId:o,name:l.name,trigger:l.trigger})}),u("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:n.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:n.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-23YOAF3E.js"),o=t(e.enabled,e.limit??50,0);return s(o.map(r=>({id:r.id,name:r.name,description:r.description,trigger:r.trigger,enabled:r.enabled,rolePreference:r.rolePreference,deliverTo:r.deliverTo,createdAt:r.createdAt})))}),u("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:n.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:n.string().describe("The message content to send (text caption when sending media)"),mediaUrl:n.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:n.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!ot(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await k([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let o=t[0];if(o.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:r}=await import("./outbound-gateway-6K6P2BEH.js"),a=await r().send({channelId:o.channelId,chatId:o.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:a.success,channelName:e.channelName,...a.error?{error:a.error}:{}})}),u("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Vt,async e=>{let t=le(e.enabled),o=[...de("active"),...de("archived")],r=t.map(i=>{let a,l=o.find(d=>d.source.type==="channel"&&d.source.channelId===i.id&&d.source.chatId);return l?.source.chatId?a=l.source.chatId:a=i.config?.userId,{id:i.id,name:i.name,platform:i.platform,status:i.status,chatId:a}});return s({channels:r})}),u("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Ft,async()=>{let e=T(),t=M("running"),o=M("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:o.length},timestamp:new Date().toISOString()})}),u("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",Bt,async e=>{let t=v(e.roleId);if(!t||t.status!=="active"){let g=D("active",20,0).filter(h=>h.source!=="system").map(h=>({id:h.id,name:h.name,allowedTools:h.allowedTools??[],capabilitySummary:_(h)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let o=Date.now(),r;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)r=o+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(r=new Date(e.runAt).getTime(),isNaN(r))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(r<=o)return s({error:"Scheduled time must be in the future"});let i=10080*60*1e3;if(r-o>i)return s({error:"Schedule exceeds maximum of 7 days"});let a=w(),l=new Date(r).toISOString(),d=e.deliverTo?await k(e.deliverTo):void 0,m=e.reportTo?await k(e.reportTo):void 0;ae({id:a,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...T().defaults},tags:["scheduled","once"],enabled:!0,createdAt:o,deliverTo:d,reportTo:m});let{getBreeEngine:c}=await import("./bree-engine-R5YLSDCL.js"),f=c();return f&&f.scheduleOnceJob(a),s({templateId:a,executeAt:l,prompt:e.prompt})}),u("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:n.string().describe("The template ID returned by schedule_task")},async e=>{let t=O(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Ve(e.templateId);let{getBreeEngine:o}=await import("./bree-engine-R5YLSDCL.js"),r=o();return r&&await r.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),u("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",Jt,async e=>{let t=we(),o=z(),r=e.roleId?(()=>{let{getRoleWorkspacePath:i}=(J(),C(re)),{getRole:a}=(W(),C(te)),{listInstalledPlugins:l}=(_e(),C(ct)),d=a(e.roleId);if(!d)return[];let m=i(d.name);return l({scope:"project",projectPath:m}).map(c=>c.id)})():[];return s({plugins:o.map(i=>({id:i.id,name:i.name,scope:i.scope,projectPath:i.projectPath,enabled:i.enabled,globalEnabled:t[i.id]??i.enabled,isInstalledInRole:r.includes(i.id),description:i.version?`v${i.version}`:void 0}))})}),u("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",zt,async e=>{let{getRole:t}=(W(),C(te)),{getRoleWorkspacePath:o}=(J(),C(re)),r=t(e.roleId);if(!r)return s({error:`Role not found: ${e.roleId}`});let i=o(r.name);try{return ue(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:i})}catch(a){return s({error:`Failed to install plugin: ${a}`})}}),u("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Yt,async e=>{let{getRole:t}=(W(),C(te)),{getRoleWorkspacePath:o}=(J(),C(re)),r=t(e.roleId);if(!r)return s({error:`Role not found: ${e.roleId}`});let i=o(r.name);try{return pe(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return s({error:`Failed to uninstall plugin: ${a}`})}}),u("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Ht,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return $(e.roleId,{mcpServers:r}),B(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:r})}catch(i){return s({error:`Failed to bind MCP server: ${i}`})}}),u("unbind_mcp_from_role","Remove an MCP server binding from a role.",Qt,async e=>{let t=v(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let o={...t.mcpServers??{}};if(!(e.mcpName in o))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete o[e.mcpName];try{return $(e.roleId,{mcpServers:o}),B(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(r){return s({error:`Failed to unbind MCP server: ${r}`})}}),u("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",Wt,async()=>{let{listTaskTemplates:e}=await import("./task-templates-23YOAF3E.js"),t=T(),o=D(void 0,100,0),r=le(),i=e(!0,100,0),a=M("running"),l=M("pending"),d=ze(),m=await Ye();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:o.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let f=Y(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:_(c,f),plugins:f.plugins.map(g=>({name:g.name,skills:g.skills.map(h=>h.name),agents:g.agents.map(h=>h.name)}))}}),retired:o.filter(c=>c.status==="retired").length,probation:o.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:m},registry:be(d.platform,m)},channels:{description:"Send/receive messages via connected platforms",connected:r.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:z().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:i.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),u("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",Kt,async e=>{try{return tt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),u("disable_plugin","Disable a globally installed plugin (removes it from all roles).",Xt,async e=>{try{return nt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),u("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Zt,async e=>{try{return ue(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),u("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",en,async e=>{try{return pe(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),u("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",tn,async()=>{try{let e=et(),t=z();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),u("list_marketplace_sources","List configured plugin marketplace sources.",nn,async()=>{let e=Se();return s({sources:e})}),u("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",rn,async e=>{let t=Te(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let o=ke(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:o})}),u("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",on,async e=>{let{getRole:t}=await import("./roles-L34L5MK3.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let r=Re(e.path);return s({roleId:e.roleId,path:e.path,config:r})}catch(r){return s({error:`Failed to scan directory: ${r}`})}}),u("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",sn,async e=>{let t=P(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let o=t.status;U(e.taskId,{status:"cancelled"});let{serverBus:r}=await import("./server-bus-GEGVMSCA.js");return r.emit({type:"task_status_change",taskId:e.taskId,oldStatus:o,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),u("view_task_logs","Retrieve step-by-step execution logs for a task.",an,async e=>{let t=he(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),u("delete_role","Delete a role by ID. This removes the role and its workspace.",ln,async e=>v(e.roleId)?(Ie(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),u("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",dn,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-VDBZZ4KG.js"),o=T(),r={};try{let d=T().server?.port??7100,m=await fetch(`http://127.0.0.1:${d}/config`);m.ok&&(r=await m.json())}catch{}let i=[...e,...t],a=[...t],l={};for(let d of i){let m=d.split("."),c=o;for(let f of m)if(c&&typeof c=="object")c=c[f];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),u("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",cn,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-VDBZZ4KG.js"),{setConfigValue:o}=await import("./config-EMNKHR3W.js"),r=ge(e.updates,o);if(e.updates["logging.level"]&&fe(e.updates["logging.level"]),r.updated.length>0){let{serverBus:i}=await import("./server-bus-GEGVMSCA.js");i.emit({type:"config_changed",changes:r.updated.map(a=>({path:a,value:e.updates[a]}))})}return s(r)}),u("list_memories","List memories stored under a specific role.",un,async e=>{let t=je(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),u("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",pn,async e=>{let t=O(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let o={};if(e.name!==void 0&&(o.name=e.name),e.enabled!==void 0&&(o.enabled=e.enabled),e.prompt!==void 0){let r=t.steps?.length?[...t.steps]:[];r.length===0?r.push({id:w(),prompt:e.prompt}):r[0]={...r[0],prompt:e.prompt},o.steps=r}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(o.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(o.rolePreference=e.roleId),Ge(e.templateId,o),s({success:!0,templateId:e.templateId,updated:Object.keys(o)})}),u("delete_template","Delete a task template by ID.",mn,async e=>O(e.templateId)?(Fe(e.templateId),s({success:!0,templateId:e.templateId})):s({error:`Template not found: ${e.templateId}`})),u("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",gn,async e=>{let t=O(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let o=T().server?.port??7100,r=await fetch(`http://127.0.0.1:${o}/webhooks/${t.name}`,{method:"POST"}),i=await r.json();return r.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:i}):s({error:`Webhook failed: ${i.code??r.status} \u2014 ${i.message??""}`})}catch(o){return s({error:`Failed to trigger template: ${o}`})}}),u("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",fn,async e=>{let t=ce(e.enabled);return s({count:t.length,rules:t})}),u("create_delivery_rule","Create a new delivery rule for event-driven result routing.",hn,async e=>{let t=w(),o={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return Be(o),s({success:!0,ruleId:t,rule:o})}),u("delete_delivery_rule","Delete a delivery rule by ID.",bn,async e=>ce().find(r=>r.id===e.ruleId)?(Je(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),u("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",yn,async e=>{let t;if(e.roleId)t=Me(e.roleId);else{let{getDb:o}=await import("./db-YUYXVV3A.js");t=o().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(i=>({id:i.id,roleId:i.role_id,name:i.name,taskType:i.task_type,createdAt:i.created_at,updatedAt:i.updated_at??void 0,promptTemplate:i.prompt_template??"",alpha:i.alpha,beta:i.beta,totalTrials:i.trials,avgReward:i.total_reward&&i.trials>0?i.total_reward/i.trials:void 0,enabled:i.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),u("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:n.string(),operationId:n.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:n.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=se(e.taskId),o=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return o?(new V().resolvePlanApproval(o.id,"allow",e.scope),s({success:!0,operationId:o.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),u("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:n.string(),operationId:n.string().optional(),reason:n.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=se(e.taskId),o=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return o?(new V().resolvePlanApproval(o.id,"deny","once",e.reason),s({success:!0,operationId:o.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function br(){return it.map(e=>e.name).sort().join(",")}function yr(){return Tt({name:"adam-tools",version:"1.0.0",tools:it})}export{V as a,Sn as b,Rn as c,He as d,et as e,ue as f,pe as g,tt as h,nt as i,$n as j,br as k,yr as l};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as o,d as u}from"./chunk-
|
|
1
|
+
import{b as o,d as u}from"./chunk-JAS3TUZX.js";u();import{v4 as a}from"uuid";function R(t){o().prepare(`
|
|
2
2
|
INSERT INTO evolution_audit (id, timestamp, old_rules, new_rules, diff, trigger_task_id, role_id, source)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
4
4
|
`).run(a(),t.timestamp,t.oldRules,t.newRules,t.diff,t.triggerTaskId??null,t.roleId??null,t.source??"reflection")}function f(t=100,e=0){return o().prepare(`
|