adam-agent-server 1.5.0 → 1.7.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/dist/App-ZRCRM7WR.js +13 -0
- package/dist/adam-automator-skills-EZGBICHT.js +18 -0
- package/dist/adam-tools-V5LPU47X.js +1 -0
- package/dist/approval-handler-PB7PSLUS.js +1 -0
- package/dist/audit-manager-BSBBDUER.js +1 -0
- package/dist/bree-engine-7S33CWS7.js +1 -0
- package/dist/channels-SITUUC4J.js +1 -0
- package/dist/{channels-HYSB2EEK.js → channels-ULFUCUUZ.js} +1 -1
- package/dist/{chunk-Y3AMO6WC.js → chunk-2L2347UQ.js} +1 -1
- package/dist/{chunk-2DLVAKH7.js → chunk-2YTDCR6A.js} +1 -1
- package/dist/chunk-4PQHGLZH.js +99 -0
- package/dist/{chunk-JAS3TUZX.js → chunk-5EPG2US5.js} +26 -7
- package/dist/{chunk-BR2JY5X2.js → chunk-5QZXYKMS.js} +1 -1
- package/dist/chunk-5XOTPEAK.js +6 -0
- package/dist/{chunk-6775OYXA.js → chunk-6KF7OO2B.js} +1 -1
- package/dist/{chunk-5S6BMWD2.js → chunk-A5OCDYTW.js} +1 -1
- package/dist/{chunk-5XUR3M23.js → chunk-AQ3ASS4B.js} +1 -1
- package/dist/{chunk-HDP7A4XY.js → chunk-B6LOT5CG.js} +1 -1
- package/dist/chunk-BCH2HAIM.js +23 -0
- package/dist/{chunk-YVS565QY.js → chunk-BQ3ZAYHC.js} +1 -1
- package/dist/{chunk-C6BOQJJF.js → chunk-DVN3BFPP.js} +1 -1
- package/dist/{chunk-H7VDC6FY.js → chunk-EQZFOBAJ.js} +1 -1
- package/dist/{chunk-7L2WQM7N.js → chunk-FPZEZYUB.js} +1 -1
- package/dist/{chunk-23VZKIB6.js → chunk-GSFLLRS7.js} +1 -1
- package/dist/{chunk-GBTG5B5R.js → chunk-HQRUJQN7.js} +1 -1
- package/dist/{chunk-R4GIIQ7G.js → chunk-IKPYPZ64.js} +1 -1
- package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
- package/dist/{chunk-6FXNB7NE.js → chunk-JJH2RCVC.js} +1 -1
- package/dist/chunk-K4C43YDD.js +7 -0
- package/dist/{chunk-Z4D3L2HR.js → chunk-M4YI4WVX.js} +1 -1
- package/dist/{chunk-INNDBLZE.js → chunk-MRTJFYPR.js} +1 -1
- package/dist/{chunk-YHVFZB6Q.js → chunk-N4ES7TCL.js} +1 -1
- package/dist/{chunk-HTPUEIFT.js → chunk-NASJH4NT.js} +5 -5
- package/dist/{chunk-H54ZXA26.js → chunk-NUITL62I.js} +1 -1
- package/dist/{chunk-VRJ7R766.js → chunk-NWMOV23A.js} +1 -1
- package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
- package/dist/chunk-PHT24MOV.js +1 -0
- package/dist/chunk-QGYDGZSC.js +49 -0
- package/dist/{chunk-XL46AGRZ.js → chunk-RI3V72RP.js} +2 -2
- package/dist/{chunk-QVKI7H7W.js → chunk-RZ7LCZVK.js} +1 -1
- package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
- package/dist/chunk-TAF2DBBC.js +79 -0
- package/dist/chunk-ULTK7RD6.js +27 -0
- package/dist/{chunk-QWCRZDZS.js → chunk-WMB7P64J.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/{config-EMNKHR3W.js → config-HBQPBIWL.js} +1 -1
- package/dist/config-ZBNGRASI.js +1 -0
- package/dist/db-QEWTZGU3.js +1 -0
- package/dist/delivery-log-AC476GX7.js +1 -0
- package/dist/engine-6K4RG644.js +1 -0
- package/dist/{evolution-audit-LZSQPDHH.js → evolution-audit-XMBDUN3T.js} +1 -1
- package/dist/{external-api-7XV2PXPC.js → external-api-V74YTLBY.js} +1 -1
- package/dist/index.js +19 -13
- package/dist/{learner-IJN6B7KV.js → learner-VCS3Q7BR.js} +1 -1
- package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
- package/dist/{memories-ZII5QSTJ.js → memories-VMOGFVPU.js} +1 -1
- package/dist/{memory-extractor-DIYJFBCI.js → memory-extractor-4WJNHYWR.js} +2 -2
- package/dist/memory-service-ZS6MBUIC.js +1 -0
- package/dist/outbound-gateway-H7RFG6D2.js +1 -0
- package/dist/role-presets-XAEOYEAW.js +1 -0
- package/dist/role-workspace-NKGAH6J6.js +1 -0
- package/dist/roles-ZYCFQMAY.js +1 -0
- package/dist/session-manager-COLCNIB7.js +1 -0
- package/dist/task-templates-4KCZOUN5.js +1 -0
- package/dist/workflow-executor-Z7JFMR56.js +1 -0
- package/package.json +25 -25
- package/web/dist/assets/{AlertDialog-r3y6IhpW.js → AlertDialog-CfeiyMrc.js} +1 -1
- package/web/dist/assets/{Button-BjXgrQ95.js → Button-DuQctNms.js} +1 -1
- package/web/dist/assets/{Card-C153tGfJ.js → Card-rKfViPS2.js} +1 -1
- package/web/dist/assets/{ChannelDetail-C2uAZv1u.js → ChannelDetail-DnL0_h8q.js} +1 -1
- package/web/dist/assets/{Channels-C62Qrg-n.js → Channels-dod8Q4oq.js} +2 -2
- package/web/dist/assets/{Chat-kH2owmB_.js → Chat-Dv_Izjx3.js} +1 -1
- package/web/dist/assets/{Dashboard-BhD8SpFb.js → Dashboard-Dl0vA6Ky.js} +1 -1
- package/web/dist/assets/{EmptyState-CXwJFCDQ.js → EmptyState-CIdIlMbn.js} +1 -1
- package/web/dist/assets/{EnvVarEditor-GSapLD96.js → EnvVarEditor-C-gErAzC.js} +1 -1
- package/web/dist/assets/EventDefDetail-BhJZGNlX.js +1 -0
- package/web/dist/assets/Events-DnNZ9-BN.js +1 -0
- package/web/dist/assets/{Evolution-BO5hysLD.js → Evolution-BBWmrrnr.js} +1 -1
- package/web/dist/assets/{GoalDetail-cxa8OvEi.js → GoalDetail-uqWQCOj3.js} +1 -1
- package/web/dist/assets/{Goals-Dz3qqp_l.js → Goals-CylKmR9j.js} +1 -1
- package/web/dist/assets/{Logs-Ckp3-hYV.js → Logs-6rf0KT0z.js} +1 -1
- package/web/dist/assets/{Memories-DEuSRoP3.js → Memories-CrBTujU7.js} +1 -1
- package/web/dist/assets/{NotFound-Bvn39vSk.js → NotFound-DitXhq_y.js} +1 -1
- package/web/dist/assets/{PageHeader-BMvN0xiB.js → PageHeader-CHSgtxPw.js} +1 -1
- package/web/dist/assets/Plugins-VKUSUcSE.js +1 -0
- package/web/dist/assets/{RoleDetail-BWMjP9aZ.js → RoleDetail-DJc4CWFN.js} +2 -2
- package/web/dist/assets/{Roles-DD7NBDku.js → Roles-6pmjn04G.js} +1 -1
- package/web/dist/assets/{SectionHeader-CiCj3Is0.js → SectionHeader-C2WpiwJ5.js} +1 -1
- package/web/dist/assets/{Settings-BlU19KuR.js → Settings-DW1jmrNj.js} +1 -1
- package/web/dist/assets/{Strategies-CJ_q94-v.js → Strategies-Bmke6qZo.js} +1 -1
- package/web/dist/assets/{Switch-CoUUy5jr.js → Switch-CfTpXW9_.js} +1 -1
- package/web/dist/assets/{Table-CaFJieh_.js → Table-DuOLbyJQ.js} +1 -1
- package/web/dist/assets/{TaskDetail-DVrjU-E6.js → TaskDetail-CwJ_UKgt.js} +2 -2
- package/web/dist/assets/Work-DVdWNBEm.js +1 -0
- package/web/dist/assets/index-D4IubNPI.css +2 -0
- package/web/dist/assets/index-DYsO5Awn.js +2 -0
- package/web/dist/assets/{useIsMobileLayout-Bwrm84kJ.js → useIsMobileLayout-C6KIQjuh.js} +1 -1
- package/web/dist/assets/{vendor-icons-BlMaTTx3.js → vendor-icons-Dk0hMuJz.js} +1 -1
- package/web/dist/assets/{vendor-react-7e01TWy7.js → vendor-react-C6faO6LO.js} +1 -1
- package/web/dist/assets/{vendor-state-Bj70wnRm.js → vendor-state-DahK0J-G.js} +1 -1
- package/web/dist/index.html +7 -7
- package/dist/App-JGH6G5US.js +0 -13
- package/dist/adam-tools-W5AOIGEQ.js +0 -1
- package/dist/approval-handler-ORD4MUVM.js +0 -1
- package/dist/audit-manager-YCJT2WP5.js +0 -1
- package/dist/bree-engine-R5YLSDCL.js +0 -1
- package/dist/channels-JCMPPQED.js +0 -1
- package/dist/chunk-2YAP4YJV.js +0 -57
- package/dist/chunk-DZEVMYPB.js +0 -19
- package/dist/chunk-GY52JA5I.js +0 -10
- package/dist/chunk-ISZJV72D.js +0 -7
- package/dist/chunk-MTWLLE26.js +0 -49
- package/dist/chunk-RAW263MQ.js +0 -99
- package/dist/chunk-S3BAIZ4Q.js +0 -6
- package/dist/chunk-VRP4LTHY.js +0 -1
- package/dist/config-XMQS2NPT.js +0 -1
- package/dist/db-YUYXVV3A.js +0 -1
- package/dist/delivery-log-VKONLSVD.js +0 -1
- package/dist/engine-BM5BMPIC.js +0 -1
- package/dist/memory-service-QMYJPBAE.js +0 -1
- package/dist/outbound-gateway-6K6P2BEH.js +0 -1
- package/dist/role-presets-K2BDRZBS.js +0 -1
- package/dist/roles-L34L5MK3.js +0 -1
- package/dist/session-manager-GRJ3FV3L.js +0 -1
- package/dist/task-templates-23YOAF3E.js +0 -1
- package/dist/workflow-executor-JTUWX5DC.js +0 -1
- package/web/dist/assets/Plugins-CRym22JF.js +0 -1
- package/web/dist/assets/Work-BMl61RRi.js +0 -1
- package/web/dist/assets/index-DcXMQByM.css +0 -2
- package/web/dist/assets/index-pF--tN9F.js +0 -2
package/dist/chunk-MTWLLE26.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{d as _}from"./chunk-GY52JA5I.js";import{i as v,j as y,q as b}from"./chunk-6775OYXA.js";import{b as k}from"./chunk-ISZJV72D.js";import{a as d}from"./chunk-L7JP7DUO.js";import{p as I}from"./chunk-C6BOQJJF.js";import{a as x,b as c,d as u,f as C}from"./chunk-S3BAIZ4Q.js";import{d as w}from"./chunk-7K4AQBDD.js";import{o as T,r as O}from"./chunk-GBTG5B5R.js";import{c as h,h as E}from"./chunk-INNDBLZE.js";E();O();import{v4 as l}from"uuid";import{CronExpressionParser as W}from"cron-parser";var n=h("scheduler"),m="ai-hourly-digest";function D(){if(c(m)){n.debug({templateId:m},"Built-in template already exists");return}let e={id:m,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
2
|
-
|
|
3
|
-
\u641C\u7D22\u6765\u6E90:
|
|
4
|
-
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
5
|
-
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
6
|
-
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
7
|
-
|
|
8
|
-
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
9
|
-
|
|
10
|
-
\u8F93\u51FA\u683C\u5F0F:
|
|
11
|
-
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
12
|
-
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
13
|
-
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
14
|
-
- \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
|
|
15
|
-
|
|
16
|
-
\u6587\u7AE0\u4FE1\u606F:
|
|
17
|
-
{{search_ai_news.result}}
|
|
18
|
-
|
|
19
|
-
\u8BF7:
|
|
20
|
-
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
21
|
-
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
22
|
-
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
23
|
-
|
|
24
|
-
\u603B\u7ED3\u7ED3\u6784:
|
|
25
|
-
## \u6838\u5FC3\u53D1\u73B0
|
|
26
|
-
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
27
|
-
|
|
28
|
-
## \u6280\u672F\u7EC6\u8282
|
|
29
|
-
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
30
|
-
|
|
31
|
-
## \u5F71\u54CD/\u610F\u4E49
|
|
32
|
-
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
33
|
-
|
|
34
|
-
## \u539F\u6587\u94FE\u63A5
|
|
35
|
-
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
36
|
-
|
|
37
|
-
\u603B\u7ED3\u5185\u5BB9:
|
|
38
|
-
{{summarize_article.result}}
|
|
39
|
-
|
|
40
|
-
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
41
|
-
|
|
42
|
-
osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
43
|
-
|
|
44
|
-
\u6CE8\u610F\uFF1A
|
|
45
|
-
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
|
-
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
47
|
-
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
|
-
|
|
49
|
-
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};x(e),n.info({templateId:m,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var A=class{cronJobs=new Map;workflowExecutor=new _;started=!1;taskCompletionHandler=null;workflowCompletionHandler=null;async start(){if(this.started)return;this.started=!0,D();let e=u(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let s=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),s++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(o=>{n.error({taskId:r.taskId,error:o},"Event trigger check failed")})},d.on("task_status_change",this.taskCompletionHandler),this.workflowCompletionHandler=r=>{(r.status==="completed"||r.status==="partial")&&this.checkWorkflowEventTriggers(r.templateId).catch(o=>{n.error({templateId:r.templateId,error:o},"Workflow event trigger check failed")})},d.on("workflow_status_change",this.workflowCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:s},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=T(void 0,1e3,0),t=0;for(let s of e)t+=I(s.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(d.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.workflowCompletionHandler&&(d.off("workflow_status_change",this.workflowCompletionHandler),this.workflowCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let s;try{s=W.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=s.next().getTime()-Date.now();return Math.max(p,1e3)},o=()=>{this.executeCronTrigger(e.id).catch(p=>{n.error({templateId:e.id,error:p},"Cron trigger failed")});let f=setTimeout(o,r());this.cronJobs.set(t,f)},i=r(),a=setTimeout(o,i);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+i).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,l()))}async scheduleJob(e){let t=c(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,s=this.cronJobs.get(t);s&&(clearTimeout(s),this.cronJobs.delete(t))}async runNow(e){let t=c(e);if(!t)throw new Error(`Template ${e} not found`);let s=l();return this.executeWorkflow(t,s).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),s}async checkEventTriggers(e){let t=k(e);if(!t)return;let s=u(!0),r=s.filter(o=>o.trigger.type==="event"&&o.trigger.event==="task_complete");for(let o of r)n.debug({templateName:o.name},"Event trigger matched"),await this.executeWorkflow(o,l());if(t.templateId){let o=s.filter(i=>i.trigger.type!=="event"||!i.trigger.event?!1:i.trigger.event===`template_complete:${t.templateId}`);for(let i of o)n.info({templateName:i.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(i,l())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let r of e.goalIds){let o=y(r);if(!o){n.warn({goalId:r,templateId:e.id},"Goal reference not found, skipping");continue}let i=l();v({id:i,name:o.name,description:o.description,roleId:o.roleId,metricType:o.metricType,targetValue:o.targetValue,currentValue:0,deadline:o.deadline,budgetUsd:o.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let a=await b({prompt:`Decompose and execute goal: ${o.name}. ${o.description??""}`,roleId:e.rolePreference??o.roleId,config:{...w()},deliverTo:e.deliverTo,reportTo:e.reportTo,sourceSessionId:e.sourceSessionId,parentId:i,templateId:e.id});if(!a.ok){n.error({templateId:e.id,sourceGoalId:r,newGoalId:i,code:a.code,reason:a.reason},"Decomposition task admission failed");continue}n.info({templateId:e.id,sourceGoalId:r,newGoalId:i,taskId:a.taskId},"Goal reference triggered, dispatched decomposition task")}return}let s=await this.workflowExecutor.execute(e,t);n.info({templateName:e.name,executionId:t,status:s.status,steps:s.stepResults.size},"Workflow execution finished")}async checkWorkflowEventTriggers(e){let s=u(!0).filter(r=>r.trigger.type!=="event"||!r.trigger.event?!1:r.trigger.event===`workflow_complete:${e}`);for(let r of s)n.info({templateName:r.name,sourceTemplateId:e},"Workflow complete trigger matched"),await this.executeWorkflow(r,l())}scheduleOnceJob(e){let t=c(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let o=`template-${e}`;this.cronJobs.has(o)&&clearTimeout(this.cronJobs.get(o));let i=setTimeout(()=>{this.cronJobs.delete(o),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(o,i),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,l()),C(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},J=null;function V(){return J}function F(g){J=g}export{A as a,V as b,F as c};
|
package/dist/chunk-RAW263MQ.js
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import{b as He,c as Qe,d as N,e as et}from"./chunk-5XUR3M23.js";import{a as pe,d as Ke,e as me}from"./chunk-H54ZXA26.js";import{b as fe,c as Ye,d as Ge,e as Xe,f as Ze}from"./chunk-YHVFZB6Q.js";import{j as je}from"./chunk-VRJ7R766.js";import{a as Le,b as $e}from"./chunk-Y3AMO6WC.js";import{b as B,c as O,d as J,f as Oe}from"./chunk-ISZJV72D.js";import{a as U,e as tt}from"./chunk-5S6BMWD2.js";import{a as Ve}from"./chunk-DZEVMYPB.js";import{e as G,f as We,j as ze}from"./chunk-QWCRZDZS.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as Fe}from"./chunk-QVKI7H7W.js";import{b as Je}from"./chunk-R4GIIQ7G.js";import{b as qe}from"./chunk-T33BLZV2.js";import{d as z,i as Be}from"./chunk-GSMC3VUM.js";import{a as Y,b as Ne,l as R,n as L,o as ue,r as $}from"./chunk-GBTG5B5R.js";import{a as Ue,g as Ft}from"./chunk-7L2WQM7N.js";import{b as _,d as q}from"./chunk-JAS3TUZX.js";import{d as le,h as jt}from"./chunk-WBAPIPST.js";import{c as b,h as P}from"./chunk-INNDBLZE.js";q();function Kt(e){return{id:e.id,roleId:e.role_id,taskId:e.task_id,scores:JSON.parse(e.score_json),emaScore:e.ema_score,createdAt:e.created_at}}function ot(e){_().prepare(`
|
|
2
|
-
INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
|
|
3
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
4
|
-
`).run(e.id,e.roleId,e.taskId,JSON.stringify(e.scores),e.emaScore,e.createdAt)}function X(e,t=50){return _().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(Kt)}function rt(e){return _().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(e)?.ema_score}function nt(e){let r=_().prepare(`
|
|
5
|
-
SELECT token_usage FROM tasks
|
|
6
|
-
WHERE role_id = ? AND status = 'completed' AND token_usage IS NOT NULL
|
|
7
|
-
ORDER BY completed_at DESC LIMIT 50
|
|
8
|
-
`).all(e);if(r.length===0)return 1e4;let i=r.map(s=>{let n=JSON.parse(s.token_usage);return(n.input??0)+(n.output??0)}).sort((s,n)=>s-n);return i[Math.floor(i.length/2)]}P();import{v4 as Ht}from"uuid";var qt=b("audit"),Z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},it=.3;function Jt(e,t){let r=B(e),i=r?.status==="completed"?1:0,s=1,n=Ke(e);n?.deviationReport&&(s=n.deviationReport.overallAccuracy);let o=1,a=$e(e,1e3),c=a.filter(g=>g.type==="tool_result"||g.type==="permission_denied").length,d=a.filter(g=>g.type==="permission_denied").length;c>0&&(o=1-d/c);let u=1;if(r?.tokenUsage){let g=r.tokenUsage.input+r.tokenUsage.output,E=t?nt(t):1e4;g>E&&(u=Math.max(0,1-(g-E)/E))}let l=i*Z.taskSuccess+s*Z.planAccuracy+o*Z.permissionCompliance+u*Z.efficiency;return{taskSuccess:i,planAccuracy:s,permissionCompliance:o,efficiency:u,weighted:l}}function st(e,t){let r=Jt(t,e),i=rt(e),s=i!==void 0?it*r.weighted+(1-it)*i:r.weighted;return ot({id:Ht(),roleId:e,taskId:t,scores:r,emaScore:s,createdAt:Date.now()}),qt.debug({roleId:e,taskId:t,scores:{...r,weighted:r.weighted.toFixed(3)},ema:s.toFixed(3)},"Task score recorded"),s}$();$();P();var Yt=b("audit");function Q(e,t=7){let r=R(e),i=X(e,100),s=Date.now(),n=s-t*24*60*60*1e3,o=i.filter(p=>p.createdAt>=n),a=o.map(p=>p.emaScore),c=o.length>0?o.reduce((p,K)=>p+K.scores.weighted,0)/o.length:1,d=[],u=o.filter(p=>p.scores.taskSuccess<.5);u.length>0&&d.push({category:"task_failures",count:u.length,examples:u.slice(0,3).map(p=>p.taskId)});let l=o.filter(p=>p.scores.planAccuracy<.5);l.length>0&&d.push({category:"plan_deviations",count:l.length,examples:l.slice(0,3).map(p=>p.taskId)});let g=o.filter(p=>p.scores.permissionCompliance<.8);g.length>0&&d.push({category:"permission_violations",count:g.length,examples:g.slice(0,3).map(p=>p.taskId)});let E=o.filter(p=>p.scores.efficiency<.3);E.length>0&&d.push({category:"inefficiency",count:E.length,examples:E.slice(0,3).map(p=>p.taskId)});let W=[],C=[];return u.length>o.length*.3&&(W.push("High task failure rate"),C.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),g.length>0&&(W.push("Permission boundary violations"),C.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),l.length>o.length*.5&&(W.push("Frequent plan deviations"),C.push({action:"add_rule",detail:"Add rule: follow execution plan steps more closely, request plan revision if steps are unclear"})),Yt.info({roleId:e,taskCount:o.length,avgScore:c.toFixed(3),failureCategories:d.map(p=>p.category)},"Diagnostic report generated"),{roleId:e,agentName:r?.name??"Unknown",period:{start:n,end:s},taskCount:o.length,avgScore:c,scoreHistory:a,failureBehaviors:d,rootCauses:W,recommendations:C}}P();var ee=b("audit"),at=.4,Gt=5;function dt(e,t,r=at){if(t>=r)return;let i=R(e);if(!i||i.status==="retired"||i.status==="dead")return;ee.warn({roleId:e,emaScore:t,threshold:r},"Agent EMA below threshold, retiring");let s=Q(e),n=JSON.stringify(i.learnedRules),o=Xt(i.learnedRules,s);L(e,{status:"retired",learnedRules:o});let a=[...s.failureBehaviors.map(d=>`${d.category}: ${d.count} occurrences`),...s.rootCauses.map(d=>`Root cause: ${d}`),...s.recommendations.map(d=>`Recommendation [${d.action}]: ${d.detail}`)].join(`
|
|
9
|
-
`),c=tt(n,JSON.stringify(o));return U({timestamp:Date.now(),oldRules:n,newRules:JSON.stringify(o),diff:a?`--- Diagnostic Report ---
|
|
10
|
-
${a}
|
|
11
|
-
|
|
12
|
-
--- Rules Diff ---
|
|
13
|
-
${c}`:c,roleId:e,source:"audit"}),ee.info({roleId:e,oldRulesCount:i.learnedRules.length,newRulesCount:o.length,recommendations:s.recommendations.length},"Agent retired with targeted learnedRules modification"),s}function ct(e){let t=R(e);return!t||t.status!=="retired"?!1:(L(e,{status:"probation"}),U({timestamp:Date.now(),oldRules:"status: retired",newRules:"status: probation",diff:`- status: retired
|
|
14
|
-
+ status: probation`,roleId:e,source:"audit"}),ee.info({roleId:e},"Agent reinstated to probation"),!0)}function lt(e,t,r=at,i=Gt){let s=R(e);return!s||s.status!=="probation"||X(e,i+1).length<i?!1:t>=r?(L(e,{status:"active"}),U({timestamp:Date.now(),oldRules:"status: probation",newRules:"status: idle",diff:`- status: probation
|
|
15
|
-
+ status: idle (graduated, EMA: ${t.toFixed(3)})`,roleId:e,source:"audit"}),ee.info({roleId:e,emaScore:t},"Agent graduated from probation to active"),!0):!1}function Xt(e,t){let r=[...e];for(let i of t.recommendations){let s=`[audit:${i.action}] ${i.detail}`;r.includes(s)||r.push(s)}if(t.failureBehaviors.length>0){let s=`[audit:diagnostic] Failure patterns detected: ${t.failureBehaviors.map(n=>`${n.category}(${n.count})`).join(", ")}. Review and adjust behavior accordingly.`;r.includes(s)||r.push(s)}return r}import{spawn as Et}from"child_process";$();import{query as po}from"@anthropic-ai/claude-agent-sdk";import{v4 as _t}from"uuid";function ut(e){let t=e.roleName?`## Role Context
|
|
16
|
-
- Role: ${e.roleName}
|
|
17
|
-
${e.roleCagPrompt?`- CAG Prompt: ${e.roleCagPrompt}`:""}`:"",r=e.allowedTools&&e.allowedTools.length>0?`## Available Tools
|
|
18
|
-
You have access to: ${e.allowedTools.join(", ")}. Use them as needed to complete the task.`:"",i=e.workflowStep?`## Workflow Step Context
|
|
19
|
-
You are executing step \`${e.workflowStep.stepId}\` of workflow \`${e.workflowStep.executionId}\`.
|
|
20
|
-
Other workflow steps may have already published structured data or files for you to use, and your output may be consumed by downstream steps.
|
|
21
|
-
|
|
22
|
-
### Artifact tools (use these to share data across steps)
|
|
23
|
-
- \`write_artifact\`: Save small structured JSON for downstream steps. Use for fields, flags, URLs, or summaries. Example: save extracted metadata.
|
|
24
|
-
- \`read_artifact\`: Read structured JSON previously written by an upstream step. Use for fields or state, not files.
|
|
25
|
-
- \`publish_artifact_file\`: Publish a file from your workspace into workflow storage. Use for audio, video, reports, images, or other large outputs.
|
|
26
|
-
- \`fetch_artifact_file\`: Copy an upstream file artifact into your current workspace. Use when you need to process a file produced by another step.
|
|
27
|
-
- \`list_artifacts\`: Discover what upstream artifacts exist before choosing a read or fetch call.
|
|
28
|
-
|
|
29
|
-
### When to use which
|
|
30
|
-
- Small JSON, fields, numbers, status, URLs: \`write_artifact\` and \`read_artifact\`
|
|
31
|
-
- Files such as audio, video, reports, images, or large outputs: \`publish_artifact_file\` and \`fetch_artifact_file\`
|
|
32
|
-
- Discover upstream output first: \`list_artifacts\`
|
|
33
|
-
|
|
34
|
-
The artifact tools handle storage and isolation automatically; never write to ~/.adam/ or other shared directories yourself.`:"";return`# Execution Agent \u2014 Task Focus
|
|
35
|
-
|
|
36
|
-
You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
|
|
37
|
-
|
|
38
|
-
## Task
|
|
39
|
-
- Task ID: ${e.taskId}
|
|
40
|
-
- Prompt: ${e.prompt}
|
|
41
|
-
|
|
42
|
-
${t}
|
|
43
|
-
|
|
44
|
-
${r}
|
|
45
|
-
|
|
46
|
-
${i}
|
|
47
|
-
|
|
48
|
-
## Focus
|
|
49
|
-
- Focus entirely on completing the task
|
|
50
|
-
- Use the standard SDK tools to do the work
|
|
51
|
-
- Do NOT attempt strategic decisions \u2014 just execute
|
|
52
|
-
|
|
53
|
-
## Constraints
|
|
54
|
-
- You have standard SDK tools only (no adam-tools MCP)
|
|
55
|
-
- Stay within your assigned permissions and allowed paths
|
|
56
|
-
- File writes: persistent outputs go under your working directory${e.cwd?` (\`${e.cwd}\`)`:""}. Temporary files may use \`os.tmpdir()\` (auto-redirected by the sandbox to a per-task dir). Do NOT write to absolute paths like \`/tmp/*\`, \`/var/*\`, \`~/Documents/*\`, or anywhere outside your workspace; the sandbox will reject them.
|
|
57
|
-
- Report completion with a clear result summary
|
|
58
|
-
- If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
|
|
59
|
-
- If a tool is unavailable, state it clearly in the result rather than guessing
|
|
60
|
-
`}import{isAbsolute as Zt,relative as Qt,resolve as eo}from"path";Ne();P();var to=new Set(["Read","Glob","Grep","LSP"]),oo=new Set(["Edit","Write","NotebookEdit"]);function ge(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function he(e){return eo(Y(e))}function pt(e,t){return t.some(r=>{let i=he(r),s=Qt(i,e);return s===""||!s.startsWith("..")&&!Zt(s)})}function mt(e,t,r){return async(i,s,{agentID:n,blockedPath:o})=>{if(o){let c=he(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=he(d);if(pt(c,[u]))return ro.warn({toolName:i,blockedPath:o,agentID:n,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${o} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&pt(c,r.roleScope)?{behavior:"allow",updatedInput:s}:t?await t(i,s,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(to.has(i))return{behavior:"allow",updatedInput:s};if(oo.has(i))return{behavior:"allow",updatedInput:s};let a=e(n??"");if(i==="Bash"&&a){let c=s.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(ge(d).test(c))return{behavior:"allow",updatedInput:s}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(ge(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(i))return{behavior:"deny",message:`Tool ${i} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=i==="Bash"?s.command??"":`${i} ${JSON.stringify(s)}`;for(let d of a.approvalRequired)try{if(ge(d).test(c))return await t(i,s,d,n)}catch{}}return{behavior:"allow",updatedInput:s}}}var ro=b("manager");function ft(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,i=e.roleId==="role-chat-manager";if(!i&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-QMYJPBAE.js"),n=e.taskPrompt||"role context and recent interactions",o=i?["semantic","working"]:["semantic","episodic"],a=await s(e.roleId,n,o,{topK:5});if(a.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
|
|
61
|
-
${a.map(u=>`- [${u.tier??"episodic"}] ${u.content}`).join(`
|
|
62
|
-
`)}
|
|
63
|
-
|
|
64
|
-
`}}}catch{}return{}}]}],SubagentStart:[{hooks:[async t=>{let r=e.roleId??t.agent_id;if(!r)return{};try{let i=e.taskPrompt||"role context",s=await Je(i,r,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:i}=await import("./memories-ZII5QSTJ.js"),{getDb:s}=await import("./db-YUYXVV3A.js"),n=t.transcript;if(!n||n.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(e.currentTaskId))return{};let a=`[Task ${e.currentTaskId} reasoning] ${n.slice(0,3e3)}`;i({id:`session-${Date.now()}`,roleId:e.roleId??r,type:"thought",content:a,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:e.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async t=>{if(!e.currentTaskId)return{};let r=t.tool_name,i=t.tool_input,s=t.tool_response,n=typeof s=="string"?s:JSON.stringify(s??"");try{Le({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(i??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:i,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:i}=await import("./memories-ZII5QSTJ.js");i({id:`compact-${Date.now()}`,roleId:e.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}$();ze();jt();P();q();import{randomUUID as no}from"crypto";function gt(e,t,r){let s=_().prepare(`
|
|
65
|
-
INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
|
|
66
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
67
|
-
`),n=Date.now();for(let o of t){let a=o.split("/").pop()??o;s.run(no(),e,o,a,r??null,n)}}function Xo(e){return _().prepare(`
|
|
68
|
-
SELECT plugin_name as pluginName, COUNT(*) as usageCount
|
|
69
|
-
FROM task_plugins
|
|
70
|
-
WHERE role_id = ?
|
|
71
|
-
GROUP BY plugin_path
|
|
72
|
-
ORDER BY usageCount DESC
|
|
73
|
-
`).all(e)}function Zo(e=50){return _().prepare(`
|
|
74
|
-
SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
|
|
75
|
-
FROM task_plugins
|
|
76
|
-
GROUP BY plugin_path
|
|
77
|
-
ORDER BY usageCount DESC
|
|
78
|
-
LIMIT ?
|
|
79
|
-
`).all(e)}$();ze();import{createSdkMcpServer as so,tool as A}from"@anthropic-ai/claude-agent-sdk";import{z as v}from"zod";import{v4 as yt}from"uuid";q();function ht(e){return{id:e.id,executionId:e.execution_id,stepId:e.step_id,key:e.key,kind:e.kind,value:e.value_json?JSON.parse(e.value_json):void 0,blobPath:e.blob_path??void 0,mime:e.mime??void 0,sizeBytes:e.size_bytes,createdAt:e.created_at}}function Ie(e){_().prepare(`
|
|
80
|
-
INSERT INTO workflow_artifacts (
|
|
81
|
-
id, execution_id, step_id, key, kind, value_json, blob_path, mime, size_bytes, created_at
|
|
82
|
-
)
|
|
83
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
84
|
-
`).run(e.id,e.executionId,e.stepId,e.key,e.kind,e.value!==void 0?JSON.stringify(e.value):null,e.blobPath??null,e.mime??null,e.sizeBytes,e.createdAt)}function ye(e,t,r){let s=_().prepare(`
|
|
85
|
-
SELECT * FROM workflow_artifacts
|
|
86
|
-
WHERE execution_id = ? AND step_id = ? AND key = ?
|
|
87
|
-
`).get(e,t,r);return s?ht(s):void 0}function ke(e,t){let r=_(),i="SELECT * FROM workflow_artifacts WHERE execution_id = ?",s=[e];return t&&(i+=" AND step_id = ?",s.push(t)),i+=" ORDER BY created_at ASC",r.prepare(i).all(...s).map(ht)}function tr(e){let t=_(),r=ke(e);return t.prepare("DELETE FROM workflow_artifacts WHERE execution_id = ?").run(e),r}function It(e){_().prepare("DELETE FROM workflow_artifacts WHERE id = ?").run(e)}function or(e){return _().prepare(`
|
|
88
|
-
SELECT id
|
|
89
|
-
FROM workflow_executions
|
|
90
|
-
WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
|
|
91
|
-
`).all(e).map(i=>i.id)}P();q();var io=b("audit");function I(e){try{_().prepare(`
|
|
92
|
-
INSERT INTO artifact_access_log (
|
|
93
|
-
timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
|
|
94
|
-
size_bytes, outcome, error_reason
|
|
95
|
-
)
|
|
96
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
97
|
-
`).run(e.timestamp,e.taskId??null,e.roleId??null,e.executionId,e.stepId??null,e.tool,e.artifactKey??null,e.artifactId??null,e.sizeBytes??null,e.outcome,e.errorReason??null)}catch(t){io.error({err:t,entry:e},"Failed to write artifact access log")}}var ao=/^[A-Za-z0-9._-]{1,256}$/,co=/^[A-Za-z0-9._-]{1,128}$/,kt=256*1024,lo=/^[a-z]+\/[a-z0-9.+-]+$/;async function uo(e){let{listChannels:t}=await import("./channels-HYSB2EEK.js"),r=t(),{listSessions:i}=await import("./session-manager-GRJ3FV3L.js"),s=[...i("active"),...i("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=s.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:a}}function f(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return ao.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function we(e){return co.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function wt(e,t){let r=e?R(e):void 0,i=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=B(t);if(!n)return{error:`task not found: ${t}`};if(!n.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!n.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=n.roleId??e;if(!o)return{error:"this workflow task has no role context"};let a=R(o);return a?{executionId:n.parentId,stepId:n.stepId,roleId:o,roleWorkspacePath:G(a.name),taskId:t}:{error:`role not found: ${o}`}},s=[...Qe(e),A("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-HYSB2EEK.js"),o=n();return f({channels:o.map(a=>({id:a.id,name:a.name,enabled:a.enabled,type:a.config?.type??"unknown"}))})}),A("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:v.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:v.string().describe("The message content to send")},async n=>{if(r?.allowedChannels!==void 0){if(r.allowedChannels.length===0)return f({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return f({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await uo(n.channelName);if(!o)return f({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-6K6P2BEH.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return f({success:d.success,channelName:n.channelName})}),A("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:v.string(),value:v.unknown()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>kt){let l=`Artifact JSON exceeds ${kt} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,sizeBytes:d,outcome:"denied",errorReason:l}),f({error:l})}let u=yt();return Ie({id:u,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"json",value:n.value,sizeBytes:d,createdAt:Date.now()}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,artifactId:u,sizeBytes:d,outcome:"success"}),f({success:!0,artifactId:u,sizeBytes:d})}catch(c){let d=c instanceof Error?c.message:String(c);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"error",errorReason:d}),f({error:d})}}),A("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:v.string(),key:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"denied",errorReason:l}),f({error:l})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"success"}),f({value:u.value,sizeBytes:u.sizeBytes})}),A("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:v.string(),sourcePath:v.string(),mime:v.string().optional(),cleanup:v.boolean().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});if(n.mime&&!lo.test(n.mime)){let l=`Invalid MIME type: ${n.mime}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:l}),f({error:l})}try{fe(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let c=yt(),d=null,u=!1;try{let l=Ye({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,Ie({id:c,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"file",blobPath:d,mime:n.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),u=!0,n.cleanup===!0&&Ge(n.sourcePath),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{It(c)}catch{}if(d)try{Ze(d)}catch{}let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,outcome:"error",errorReason:g}),f({error:g})}}),A("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:v.string(),key:v.string(),destPath:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});try{fe(n.destPath,o.roleWorkspacePath,!1)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="file"||!u.blobPath){let l="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"denied",errorReason:l}),f({error:l})}try{let l=Xe({blobPath:u.blobPath,destPath:n.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"error",errorReason:g}),f({error:g})}}),A("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:v.string().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=n.stepId?we(n.stepId):null;if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:a}),f({error:a});let c=ke(o.executionId,n.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:c.length,outcome:"success"}),f({artifacts:c.map(d=>({id:d.id,stepId:d.stepId,key:d.key,kind:d.kind,sizeBytes:d.sizeBytes,mime:d.mime,createdAt:d.createdAt}))})})];return so({name:"execution-tools",version:"1.0.0",tools:s})}Ft();Ne();import{realpathSync as mo}from"fs";var w=b("execution"),bt=new Set;async function fo(e,t){if(t&&bt.has(t))return w.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=_t(),i={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return pe({id:r,taskId:e,plan:i,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:i}),w.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(s=>{let o=setTimeout(()=>{c(),me(r,"denied"),w.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),s(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(w.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&bt.add(t),s(!0)):(w.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),s(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let i=Date.now(),s,n,o;O(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),w.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.config.executionProfile;if(!a){let m=t.roleId?R(t.roleId):void 0;if(m){w.info({taskId:t.id,roleId:t.roleId},"Lazy-backfilled executionProfile from live Role"),a=m;let h=B(t.id);h&&O(t.id,{config:{...h.config,executionProfile:m}})}}let c=le;a&&(We(a),c=G(a.name));let d={taskId:t.id,prompt:t.prompt,roleName:a?.name,roleCagPrompt:a?.cagPrompt,allowedTools:a?.allowedTools,cwd:c,workflowStep:t.parentId&&t.stepId?{executionId:t.parentId,stepId:t.stepId}:void 0},u=ut(d),l=ft({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),g=t.config.approvalTimeout??300,E=async(m,h,k,D)=>{let x=_t(),Ce=He(D??t.roleId,t.prompt,"medium");if(Ce)return w.info({operationId:x,ruleId:Ce.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ae={steps:[{index:0,description:`${m}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[m],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return pe({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ae,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ae}),w.info({taskId:t.id,operationId:x,toolName:m,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(ce=>{let zt=setTimeout(()=>{Me(),me(x,"denied"),w.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),ce({behavior:"deny",message:`Operation timed out after ${g}s. Auto-denied. Try a safer alternative that does not require approval.`})},g*1e3),De=M=>{if(M.planId===x)if(Me(),M.decision==="allow")w.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),ce({behavior:"allow",updatedInput:h});else{let Vt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";w.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),ce({behavior:"deny",message:Vt})}},Me=()=>{clearTimeout(zt),y.off("plan_approval_decision",De)};y.on("plan_approval_decision",De)})},C=(Ue("defaults.deniedReadPaths")??[]).map(m=>{let h=Y(m);try{return mo(h)}catch{return h}}),p=a,K=p?.additionalDirectories??[],se=p?je(p):[],ve=[...K.map(m=>m.path)].filter((m,h,k)=>k.indexOf(m)===h),Dt=mt(m=>({disallowedTools:p?.disallowedTools,approvalRequired:p?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:p?.allowedBashPatterns,deniedBashPatterns:p?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...ve]}),Mt=Be({roleEnvVars:p?.envVars,taskEnv:t.config.env}),Bt=t.config.maxBudgetUsd??z().defaults.maxBudgetUsd,Ot=t.config.maxTurns??100,Lt=wt(t.roleId??"",t.id),$t=p?.mcpServers??{},Nt=t.config.mcpServers??{},Ut={...$t,...Nt,"execution-tools":Lt},ae=[{path:c,mode:"rw"}];t.roleId===Ve&&ae.push({path:le,mode:"ro"});for(let m of K)ae.push({path:m.path,mode:m.mode??"rw"});let Se=N();if(Se.platform==="none"&&!await fo(t.id,a?.name))return O(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Te=p?.permissionMode??"default",Wt=po({prompt:t.prompt,options:{cwd:c,additionalDirectories:ve,systemPrompt:u,maxTurns:Ot,maxBudgetUsd:Bt,allowedTools:p?.allowedTools,model:p?.model,mcpServers:Ut,settingSources:p?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:Dt,env:Mt,plugins:se.map(m=>({type:"local",path:m})),permissionMode:Te,...Te==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:m=>{let h=Se.spawn({command:m.command,args:m.args,cwd:m.cwd,env:m.env,signal:m.signal,visiblePaths:ae,deniedReadPaths:C,osCapabilities:p?.osCapabilities}),k=h;k.pid&&(xt(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>Rt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(w.error({taskId:t.id,roleId:t.roleId,exitCode:x,stderr:D.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:t.roleId??"unknown",taskId:t.id,path:c,operation:`sandbox_init_failure:exit_${x}`,timestamp:Date.now()}))}),h},stderr:m=>{m.trim()&&w.debug({stderr:m.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),H="",Ee=0,Pe=()=>{w.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Pe);try{for await(let m of Wt){let h=m;if(w.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(H=h.result),h.type==="result"){Ee++,typeof h.total_cost_usd=="number"&&(n=h.total_cost_usd);let k=h.usage;k?.input_tokens!==void 0&&k?.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}if(h.token_usage){let k=h.token_usage;k.input_tokens!==void 0&&k.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Pe)}o=Ee;let de=Date.now()-i;return O(t.id,{status:"completed",result:H,completedAt:Date.now(),costUsd:n,tokenUsage:s,numTurns:o,totalDurationMs:de}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:H}),se.length>0&>(t.id,se,t.roleId),w.info({taskId:t.id,durationMs:de,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:H,costUsd:n,tokenUsage:s,numTurns:o,durationMs:de}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-i;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&w.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),O(t.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:d}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:t.id,error:c}),w.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=b("execution-pool"),be=new Map;function xt(e,t,r){be.set(e,{roleId:t,taskId:r})}function Rt(e){be.delete(e)}function _e(e){return be.get(e)}var vt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(i,s)=>({index:s,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",i=>{this.onTaskCreated(i.taskId)}),y.on("task_status_change",i=>{i.newStatus==="pending"&&this.pickupPendingTasks()});let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),S.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let t of this.slots)t.abortController&&(t.abortController.abort(),t.taskId=null,t.abortController=null);S.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(t){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let t=this.slots.find(a=>a.taskId===null);if(!t){S.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let s=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=s.id,t.abortController=new AbortController;let n=t.index,o=s.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let i=this.slots[r];if(!i)return;let s="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,i.abortController?.signal);s=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{i.taskId=null,i.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:s}),this.emitSlotChange(),this.runPostCompletion(t.id,t.roleId).catch(n=>{S.error({taskId:t.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let t=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let i=qe();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Oe(i)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:i}=await import("./memory-extractor-DIYJFBCI.js"),s=await i(t,r);s>0&&S.debug({taskId:t,roleId:r,memoriesStored:s},"Post-completion: memories extracted")}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: memory extraction failed")}try{let{processTaskReview:i}=await import("./learner-IJN6B7KV.js");await i(t)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:i}=await import("./audit-manager-YCJT2WP5.js");i(t,r)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(i=>i.taskId!==null).length,r=J("pending");return{active:t,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(t){let r=this.slots.find(i=>i.taskId===t);r&&(S.warn({taskId:t,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};P();var T=b("audit"),go="sandbox_violation",V=new Map,xe=1440*60*1e3,ne=[],ho=100;function Re(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let i=Date.now()-xe;if(r.timestamps=r.timestamps.filter(s=>s>=i),V.set(t,r),r.count%100===0)for(let[s,n]of V.entries()){let o=Date.now()-xe;n.timestamps.filter(a=>a>=o).length===0&&V.delete(s)}ne.push(e),ne.length>ho&&ne.shift();try{Fe({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:e.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:go,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(s){T.error({error:s},"Failed to record violation to delivery_log")}try{let s=R(e.roleId);U({timestamp:e.timestamp,oldRules:"sandbox_violation",newRules:`${e.operation} on ${e.path}`,diff:`Sandbox violation: ${e.operation} on ${e.path} (taskId=${e.taskId??"unknown"})`,roleId:e.roleId,source:"audit"})}catch(s){T.error({error:s},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp})}async function Pt(){let e=N();if(e.platform==="none")return T.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await e.isAvailable())return T.warn({platform:e.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return e.platform==="sandbox-exec"?r=Io():e.platform==="landlock"&&(r=await yo()),()=>{if(r){let i=r;r=null,i.kill("SIGTERM");let s=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},2e3);i.on("exit",()=>clearTimeout(s))}T.info("Violation watcher stopped")}}function Io(){let e=Et("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return e.stdout?.on("data",t=>{let r=t.toString().split(`
|
|
98
|
-
`).filter(Boolean);for(let i of r)try{let s=JSON.parse(i),n=s.eventMessage??s.message??"";if(n.includes("deny")&&(n.includes("file-read")||n.includes("file-write"))){let o=ko(s,n);o&&Re(o)}}catch{}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString()},"log stream stderr")}),e.on("error",t=>{T.warn({error:t},"macOS violation watcher failed to start")}),T.info("macOS sandbox violation watcher started (log stream)"),e}async function yo(){let e=await St("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(e)return Tt(e),T.info("Linux violation watcher started (journalctl -kf)"),e;let t=await St("dmesg",["-w","-t"]);return t?(Tt(t),T.info("Linux violation watcher started (dmesg -w)"),t):(T.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function St(e,t){return new Promise(r=>{let i=Et(e,t,{stdio:["ignore","pipe","pipe"]}),s=setTimeout(()=>r(i),500);i.on("error",()=>{clearTimeout(s),r(null)}),i.on("exit",n=>{n!==0&&(clearTimeout(s),r(null))})})}function Tt(e){e.stdout?.on("data",t=>{let r=t.toString().split(`
|
|
99
|
-
`).filter(Boolean);for(let i of r)if(i.includes("landlock")&&i.includes("denied")){let s=wo(i);s&&Re(s)}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString().trim()},"Linux watcher stderr")})}function ko(e,t){let r=t.match(/(?:path|file)=["']([^"']+)["']/),i=t.match(/deny\s+(file-read|file-write|file-[^\s]+)/),s=r?.[1],n=i?.[1]??"unknown";if(!s)return null;let o=typeof e.processID=="number"?e.processID:void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function wo(e){let t=e.match(/path="([^"]+)"/)??e.match(/\/[\w\-\.\/\+ ]+/g),r=e.match(/deny\s+(\w+)/),i=e.match(/pid=(\d+)/),s=Array.isArray(t)?t[t.length-1]:t?.[1],n=r?.[1]??"unknown";if(!s)return null;let o=i?parseInt(i[1],10):void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function re(e){Re({roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp,count:1})}function Ct(e){let t=V.get(e);if(!t)return 0;let r=Date.now()-xe;return t.timestamps.filter(i=>i>=r).length}function At(){return[...ne]}$();P();var j=b("audit"),bo=.4,_o=1440*60*1e3,F=null,ie=null;function pn(e,t,r=bo){let i=R(t);if(!i||i.status==="retired"||i.status==="inactive"||i.status==="dead")return;let s=st(t,e);L(t,{performanceScore:s}),lt(t,s,r)?j.info({roleId:t,emaScore:s},"Probation role graduated"):s<r&&dt(t,s,r)&&ct(t)}async function mn(){F===null&&(F=setInterval(()=>{j.info("Running daily diagnostic reports");let e=ue(void 0,1e3);for(let t of e)if(!(t.status==="retired"||t.status==="inactive"))try{Q(t.id)}catch(r){j.error({roleId:t.id,error:r},"Daily diagnostic failed")}},_o),ie=await Pt(),j.info("AuditManager started"))}function fn(){F!==null&&(clearInterval(F),F=null),ie!==null&&(ie(),ie=null),j.info("AuditManager stopped")}function gn(e){re(e)}async function hn(){let e=N(),t=ue(void 0,1e3),i=Date.now()-1440*60*1e3,s=At(),n=s.filter(c=>c.timestamp>=i).length,o=t.map(c=>{let d=s.filter(l=>l.roleId===c.id),u=d[d.length-1];return{roleId:c.id,roleName:c.name,sandboxed:e.platform!=="none",violationCount:Ct(c.id),lastViolation:u?.timestamp}}),a=await et();return{platform:e.platform,available:a,violationCount24h:n,rolePostures:o}}export{X as a,rt as b,mt as c,ft as d,Xo as e,Zo as f,ke as g,tr as h,or as i,pn as j,mn as k,fn as l,gn as m,hn as n,vt as o};
|
package/dist/chunk-S3BAIZ4Q.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{b as s,d as l}from"./chunk-JAS3TUZX.js";l();function o(e){let n={type:e.trigger_type,cron:e.trigger_type==="once"?void 0:e.trigger_cron??void 0,event:e.trigger_event??void 0,runAt:e.trigger_type==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:n,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0}}function u(e){s().prepare(`
|
|
2
|
-
INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
|
|
3
|
-
trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
|
|
4
|
-
source_session_id, deliver_to, report_to, goal_ids)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(e.id,e.name,e.description??null,e.trigger.type,e.trigger.type==="once"?e.trigger.runAt??null:e.trigger.cron??null,e.trigger.event??null,JSON.stringify(e.steps),e.rolePreference??null,e.config?JSON.stringify(e.config):null,e.tags?JSON.stringify(e.tags):null,e.enabled?1:0,e.createdAt??Date.now(),e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.goalIds?JSON.stringify(e.goalIds):null)}function p(e){let t=s().prepare("SELECT * FROM task_templates WHERE id = ?").get(e);return t?o(t):void 0}function f(e,n){let t=s(),i=[],r=[];"name"in n&&(i.push("name = ?"),r.push(n.name)),"description"in n&&(i.push("description = ?"),r.push(n.description??null)),"trigger"in n&&n.trigger&&(i.push("trigger_type = ?"),r.push(n.trigger.type),i.push("trigger_cron = ?"),r.push(n.trigger.type==="once"?n.trigger.runAt??null:n.trigger.cron??null),i.push("trigger_event = ?"),r.push(n.trigger.event??null)),"steps"in n&&(i.push("steps = ?"),r.push(JSON.stringify(n.steps))),"rolePreference"in n&&(i.push("role_preference = ?"),r.push(n.rolePreference??null)),"config"in n&&(i.push("config = ?"),r.push(n.config?JSON.stringify(n.config):null)),"tags"in n&&(i.push("tags = ?"),r.push(n.tags?JSON.stringify(n.tags):null)),"enabled"in n&&(i.push("enabled = ?"),r.push(n.enabled?1:0)),"sourceSessionId"in n&&(i.push("source_session_id = ?"),r.push(n.sourceSessionId??null)),"deliverTo"in n&&(i.push("deliver_to = ?"),r.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(i.push("report_to = ?"),r.push(n.reportTo?JSON.stringify(n.reportTo):null)),"goalIds"in n&&(i.push("goal_ids = ?"),r.push(n.goalIds?JSON.stringify(n.goalIds):null)),i.length!==0&&(i.push("updated_at = ?"),r.push(Date.now()),r.push(e),t.prepare(`UPDATE task_templates SET ${i.join(", ")} WHERE id = ?`).run(...r))}function c(e=!1,n,t=0){let i=s(),r="SELECT * FROM task_templates",g=[];return e&&(r+=" WHERE enabled = 1"),r+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof n=="number"&&(r+=" LIMIT ? OFFSET ?",g.push(n,t)),i.prepare(r).all(...g).map(o)}function T(e){s().prepare("UPDATE task_templates SET enabled = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}function _(e){s().prepare("UPDATE task_templates SET enabled = 0, updated_at = ? WHERE id = ?").run(Date.now(),e)}function h(e){s().prepare("DELETE FROM task_templates WHERE id = ?").run(e)}export{u as a,p as b,f as c,c as d,T as e,_ as f,h as g};
|
package/dist/chunk-VRP4LTHY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as w,h as S}from"./chunk-WBAPIPST.js";import{c as g,h as P}from"./chunk-INNDBLZE.js";P();S();import{readFileSync as v,existsSync as E}from"fs";import{join as p}from"path";import{homedir as R}from"os";var T=g("ws"),x=p(R(),".adam"),f=p(x,"adam.port"),b=p(w,"adam.key");function d(){let n=process.env.ADAM_API_KEY;if(n)return n;if(E(b))return v(b,"utf-8").trim()||void 0}function m(){if(!E(f))return null;let n=parseInt(v(f,"utf-8").trim(),10);return isNaN(n)?null:n}function C(){let n=m();if(!n)throw new Error("Server not running. Run: adam server start");return`http://localhost:${n}`}var u=class extends Error{constructor(e,s){super(s);this.status=e;this.name="ApiError"}};async function A(n,t={}){let s=`${C()}${n}`,r=d(),o=await fetch(s,{method:t.method||"GET",headers:{"Content-Type":"application/json",...r?{"x-api-key":r}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0});if(!o.ok){let a=await o.text().catch(()=>"Unknown error");throw new u(o.status,a)}return o.headers.get("content-type")?.includes("application/json")?o.json():o.text()}function D(){return A("/healthz")}var k=class{ws=null;callbacks=new Map;reconnectAttempts=0;reconnectTimer=null;url;constructor(t="/events"){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}${t}`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{this.reconnectAttempts=0,t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(l=>l(c??a))}catch(r){T.error({error:r},"Failed to parse WebSocket message")}},this.ws.onclose=()=>{this.scheduleReconnect()},this.ws.onerror=s=>{e(s)}}catch(s){e(s)}})}scheduleReconnect(){let t=[1e3,2e3,4e3,8e3,15e3],e=t[Math.min(this.reconnectAttempts,t.length-1)];this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect().catch(()=>{})},e)}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}},y=class{ws=null;callbacks=new Map;url;constructor(t){let e=m();if(!e)throw new Error("Server not running. Run: adam server start");let s=d(),r=new URL(`ws://localhost:${e}/tasks/${t}/stream`);s&&r.searchParams.set("api_key",s),this.url=r.toString()}connect(){return new Promise((t,e)=>{try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>{t()},this.ws.onmessage=s=>{try{let r=JSON.parse(s.data),{type:o,data:c,...a}=r,i=this.callbacks.get(o);i&&i.forEach(h=>h(c??a));let l=this.callbacks.get("*");l&&l.forEach(h=>h(r))}catch(r){T.error({error:r},"Failed to parse task stream message")}},this.ws.onerror=s=>{e(s)},this.ws.onclose=()=>{}}catch(s){e(s)}})}on(t,e){this.callbacks.has(t)||this.callbacks.set(t,new Set),this.callbacks.get(t).add(e)}off(t,e){this.callbacks.get(t)?.delete(e)}close(){this.ws?.close()}isConnected(){return this.ws?.readyState===WebSocket.OPEN}};export{d as a,A as b,D as c,k as d,y as e};
|
package/dist/config-XMQS2NPT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as b,b as c,d,e}from"./chunk-7K4AQBDD.js";import{a}from"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,e as getChatConfig,d as getDefaults,b as loadConfig,c as loadDefaultConfig};
|
package/dist/db-YUYXVV3A.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-JAS3TUZX.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-QVKI7H7W.js";import"./chunk-JAS3TUZX.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as TTL_MS,g as cleanupExpired,b as createDeliveryLog,i as getDeliveryLogByRule,h as getDeliveryLogByTask,f as getFailedDeliveries,e as getPendingDeliveries,d as markDelivered,c as updateDeliveryLogStatus};
|
package/dist/engine-BM5BMPIC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d}from"./chunk-H7VDC6FY.js";import"./chunk-BR2JY5X2.js";import"./chunk-YVS565QY.js";import"./chunk-ISZJV72D.js";import"./chunk-XL46AGRZ.js";import"./chunk-23VZKIB6.js";import"./chunk-2DLVAKH7.js";import"./chunk-HDP7A4XY.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{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-R4GIIQ7G.js";import"./chunk-2CMR5AG7.js";import"./chunk-C6BOQJJF.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 getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c}from"./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{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b}from"./chunk-DZEVMYPB.js";import"./chunk-QWCRZDZS.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 CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
|
package/dist/roles-L34L5MK3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{j as a,k as b,l as c,m as d,n as e,o as f,p as g,r as h}from"./chunk-GBTG5B5R.js";import"./chunk-7L2WQM7N.js";import"./chunk-JAS3TUZX.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";h();export{b as createRole,g as deleteRole,c as getRole,d as getRoleByName,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-Z4D3L2HR.js";import"./chunk-2DLVAKH7.js";import"./chunk-HDP7A4XY.js";import"./chunk-L7JP7DUO.js";import"./chunk-2CMR5AG7.js";import"./chunk-C6BOQJJF.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{p as _resetForTest,e as archiveSession,b as createSession,g as deleteSession,c as getActiveSession,d as getSession,m as getTimeoutPollerInterval,i as incrementMessageCount,n as initSessionManager,j as listSessions,f as restoreSession,o as shutdownSessionManager,k as startTimeoutPoller,l as stopTimeoutPoller,h as touchSession,a as warmCache};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-S3BAIZ4Q.js";import"./chunk-JAS3TUZX.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createTaskTemplate,g as deleteTaskTemplate,f as disableTaskTemplate,e as enableTaskTemplate,b as getTaskTemplate,d as listTaskTemplates,c as updateTaskTemplate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a}from"./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-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 WorkflowExecutor};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,L as n,Q as r,W as i,b as a,h as o,j as s,l as c,o as l,st as u,t as ee,tt as te,v as ne,x as re}from"./vendor-icons-BlMaTTx3.js";import{t as d}from"./vendor-react-7e01TWy7.js";import{n as f}from"./dist-Bdqp1ixJ.js";import{t as p}from"./Button-BjXgrQ95.js";import{i as m,t as h}from"./index-pF--tN9F.js";import{t as g}from"./Card-C153tGfJ.js";import{t as ie}from"./PageHeader-BMvN0xiB.js";import{t as ae}from"./SectionHeader-CiCj3Is0.js";import{a as oe}from"./format-CHfBBLog.js";import{t as se}from"./EmptyState-CXwJFCDQ.js";import{t as _}from"./ui-B_uMx2Fy.js";import{t as ce}from"./useIsMobileLayout-Bwrm84kJ.js";import{a as v,i as y,n as b,o as x,r as S,t as C}from"./Table-CaFJieh_.js";var w=e(u(),1),T=d();function E({manifest:e}){if(!e)return null;let t=[];return e.skills.length>0&&t.push({label:`Skill(${e.skills.length})`,variant:`info`}),e.agents.length>0&&t.push({label:`Agent(${e.agents.length})`,variant:`success`}),e.mcpServers.length>0&&t.push({label:`MCP(${e.mcpServers.length})`,variant:`warning`}),e.hooks.length>0&&t.push({label:`Hook(${e.hooks.length})`,variant:`default`}),e.lspServers.length>0&&t.push({label:`LSP(${e.lspServers.length})`,variant:`default`}),(0,T.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:t.map(e=>(0,T.jsx)(h,{variant:e.variant,children:e.label},e.label))})}function D({label:e,value:t}){return(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 px-3 py-2`,children:[(0,T.jsx)(`p`,{className:`text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:e}),(0,T.jsx)(`p`,{className:`mt-1 text-sm font-medium text-[var(--app-text)]`,children:t})]})}function O({plugin:e,roles:t,operatingId:n,onInstallToRole:r}){return e.manifest?(0,T.jsxs)(`div`,{className:`space-y-4 text-xs`,children:[e.manifest.description?(0,T.jsx)(`p`,{className:`text-[var(--app-text-muted)]`,children:e.manifest.description}):null,(0,T.jsxs)(`div`,{className:`grid gap-2 md:grid-cols-4`,children:[(0,T.jsx)(D,{label:`Version`,value:e.version?`v${e.version}`:`—`}),(0,T.jsx)(D,{label:`Scope`,value:e.scope}),(0,T.jsx)(D,{label:`Capability Count`,value:e.manifest.skills.length+e.manifest.agents.length+e.manifest.mcpServers.length+e.manifest.hooks.length+e.manifest.lspServers.length}),(0,T.jsx)(D,{label:`Activation`,value:e.globalEnabled?`User On`:`User Off`})]}),(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 px-3 py-2`,children:[(0,T.jsx)(`p`,{className:`text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:`Install Path`}),(0,T.jsx)(`p`,{className:`mt-1 truncate font-mono text-[11px] text-[var(--app-text-muted)]`,title:e.installPath,children:e.installPath})]}),(0,T.jsxs)(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[e.manifest.skills.length>0&&(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`div`,{className:`mb-2 font-semibold text-[var(--app-text)]`,children:`Skills`}),e.manifest.skills.map(e=>(0,T.jsxs)(`div`,{className:`inline-flex items-baseline gap-1 text-[var(--app-text-muted)]`,children:[(0,T.jsx)(`span`,{className:`text-[var(--app-text)]`,children:e.name}),e.description?(0,T.jsxs)(`span`,{className:`text-[var(--app-text-subtle)]`,children:[`; `,e.description]}):null]},e.name))]}),e.manifest.agents.length>0&&(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`div`,{className:`mb-2 font-semibold text-[var(--app-text)]`,children:`Agents`}),e.manifest.agents.map(e=>(0,T.jsxs)(`div`,{className:`inline-flex items-baseline gap-1 text-[var(--app-text-muted)]`,children:[(0,T.jsx)(`span`,{className:`text-[var(--app-text)]`,children:e.name}),e.description?(0,T.jsxs)(`span`,{className:`text-[var(--app-text-subtle)]`,children:[`; `,e.description]}):null]},e.name))]}),e.manifest.mcpServers.length>0&&(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`div`,{className:`mb-2 font-semibold text-[var(--app-text)]`,children:`MCP Servers`}),e.manifest.mcpServers.map(e=>(0,T.jsx)(`div`,{className:`text-[var(--app-text-muted)]`,children:e},e))]}),e.manifest.hooks.length>0&&(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`div`,{className:`mb-2 font-semibold text-[var(--app-text)]`,children:`Hooks`}),e.manifest.hooks.map(e=>(0,T.jsx)(`div`,{className:`text-[var(--app-text-muted)]`,children:e},e))]}),e.manifest.lspServers.length>0&&(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`div`,{className:`mb-2 font-semibold text-[var(--app-text)]`,children:`LSP Servers`}),e.manifest.lspServers.map(e=>(0,T.jsx)(`div`,{className:`text-[var(--app-text-muted)]`,children:e},e))]})]}),t.length>0&&e.scope===`user`?(0,T.jsxs)(`div`,{className:`rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:[(0,T.jsx)(`p`,{className:`mb-2 text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:`Install to Role`}),(0,T.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px]`,disabled:n===e.id,onClick:()=>void r(e.id,t.id,t.workspacePath),children:t.name},t.id))})]}):null]}):(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-text-subtle)]`,children:`Loading manifest...`})}function k(){let[e,u]=(0,w.useState)([]),[d,D]=(0,w.useState)([]),[k,le]=(0,w.useState)([]),[ue,de]=(0,w.useState)(new Set),[fe,A]=(0,w.useState)(!0),[j,M]=(0,w.useState)(!1),[N,P]=(0,w.useState)(null),[F,pe]=(0,w.useState)(!1),[I,me]=(0,w.useState)(``),[L,R]=(0,w.useState)(null),[z,B]=(0,w.useState)(!1),[V,H]=(0,w.useState)(``),[U,he]=(0,w.useState)([]),[W,ge]=(0,w.useState)(!1),[G,_e]=(0,w.useState)(new Set),[K,q]=(0,w.useState)(`all`),[J,ve]=(0,w.useState)([]),ye=ce(),Y=(0,w.useCallback)(async()=>{A(!0);try{u((await f(`/plugins`)).plugins)}catch(e){m.error(e instanceof Error?e.message:`Failed to load plugins`)}finally{A(!1)}},[]),X=(0,w.useCallback)(async()=>{M(!0),P(null);try{let[e,t]=await Promise.all([f(`/plugins/marketplace`).catch(()=>({available:[],installed:[]})),f(`/plugins/marketplaces`)]);le(e.available),de(new Set(e.installed.map(e=>e.id))),D(t.sources)}catch(e){P(e instanceof Error?e.message:`Failed to load marketplace`)}finally{M(!1)}},[]),be=(0,w.useCallback)(async()=>{try{he((await f(`/plugins/stats?limit=20`)).stats)}catch{}},[]),Z=(0,w.useCallback)(async()=>{try{ve((await f(`/roles`)).roles)}catch{}},[]);(0,w.useEffect)(()=>{Y(),X(),Z()},[Y,X,Z]);let xe=async(e,t)=>{R(e);try{await f(`/plugins/${encodeURIComponent(e)}/${t?`enable`:`disable`}`,{method:`POST`}),m.success(`${e} ${t?`enabled`:`disabled`} globally`),u(n=>n.map(n=>n.id===e?{...n,globalEnabled:t}:n))}catch(e){m.error(e instanceof Error?e.message:`Failed to ${t?`enable`:`disable`} plugin`)}finally{R(null)}},Se=async e=>{R(e);try{await f(`/plugins/uninstall/${encodeURIComponent(e)}`,{method:`POST`}),m.success(`Plugin uninstalled`),await Promise.all([Y(),X()])}catch(e){m.error(e instanceof Error?e.message:`Uninstall failed`)}finally{R(null)}},Ce=async(e,t,n)=>{R(e);try{await f(`/plugins/install/${encodeURIComponent(e)}`,{method:`POST`,body:JSON.stringify({scope:`project`,cwd:n})});let r=J.find(e=>e.id===t)?.name??t;m.success(`Installed ${e.split(`@`)[0]} for ${r}`),await Y()}catch(e){m.error(e instanceof Error?e.message:`Install to role failed`)}finally{R(null)}},we=async()=>{if(V.trim())try{await f(`/plugins/install/${encodeURIComponent(V.trim())}`,{method:`POST`,body:JSON.stringify({})}),m.success(`Source added`),H(``),B(!1),await X()}catch(e){m.error(e instanceof Error?e.message:`Failed to add source`)}},Q=async(e,t=`user`,n)=>{R(e);try{await f(`/plugins/install/${encodeURIComponent(e)}`,{method:`POST`,body:JSON.stringify({scope:t,cwd:n})});let r=t===`project`&&n?`${e.split(`@`)[0]} for ${n.split(`/`).pop()}`:e.split(`@`)[0];m.success(`Installed ${r}`),await Promise.all([Y(),X()])}catch(e){m.error(e instanceof Error?e.message:`Install failed`)}finally{R(null)}},Te=e=>{_e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},$=K===`all`?e:e.filter(e=>e.scope===K),Ee=I?k.filter(e=>e.name.toLowerCase().includes(I.toLowerCase())||e.description.toLowerCase().includes(I.toLowerCase())):k;return(0,T.jsxs)(`div`,{className:`space-y-5`,children:[(0,T.jsx)(ie,{eyebrow:`Capabilities`,title:`Plugins`,compact:!0,description:`Installed capabilities, scope, and activation.`,metrics:[{label:`Total`,value:e.length},{label:`Project Scope`,value:e.filter(e=>e.scope===`project`).length},{label:`Catalog`,value:k.length}],actions:(0,T.jsx)(p,{variant:`ghost`,size:`sm`,onClick:()=>void Y(),children:(0,T.jsx)(ne,{size:14})})}),(0,T.jsx)(ae,{title:`Installed Plugins`,compact:!0,description:`Filter by scope, inspect manifests, and keep every activation path reachable from one place.`}),(0,T.jsxs)(g,{children:[(0,T.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,T.jsx)(n,{size:14,className:`text-[var(--app-text-muted)] flex-shrink-0`}),(0,T.jsx)(`button`,{className:`rounded-full px-2 py-0.5 text-xs transition-colors ${K===`all`?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-muted)] hover:bg-[var(--app-panel-muted)]`}`,onClick:()=>q(`all`),children:`All`}),(0,T.jsx)(`button`,{className:`rounded-full px-2 py-0.5 text-xs transition-colors ${K===`user`?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-muted)] hover:bg-[var(--app-panel-muted)]`}`,onClick:()=>q(`user`),children:`User`}),(0,T.jsx)(`button`,{className:`rounded-full px-2 py-0.5 text-xs transition-colors ${K===`project`?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-muted)] hover:bg-[var(--app-panel-muted)]`}`,onClick:()=>q(`project`),children:`Project`}),(0,T.jsx)(`span`,{className:`h-4 w-px bg-[var(--app-panel-muted)] mx-1`}),d.map(e=>(0,T.jsx)(h,{variant:`muted`,className:`text-xs`,children:e.name},e.name)),(0,T.jsxs)(`span`,{className:`ml-auto flex items-center gap-2`,children:[j&&(0,T.jsx)(s,{size:12,className:`animate-spin text-[var(--app-text-subtle)]`}),j?null:(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-2 text-xs`,onClick:()=>B(!z),children:z?(0,T.jsx)(ee,{size:12}):(0,T.jsx)(re,{size:12})})]})]}),z&&(0,T.jsxs)(`div`,{className:`mt-2 flex gap-2`,children:[(0,T.jsx)(`input`,{className:`flex-1 rounded border border-[var(--app-border)] bg-[var(--app-panel)] px-2 py-1.5 text-sm text-[var(--app-text)] focus:border-[var(--app-accent)] focus:outline-none`,value:V,onChange:e=>H(e.target.value),placeholder:`https://github.com/org/marketplace-repo`,onKeyDown:e=>{e.key===`Enter`&&we()}}),(0,T.jsx)(p,{size:`sm`,onClick:()=>void we(),disabled:!V.trim(),children:`Add`})]})]}),fe?(0,T.jsx)(g,{children:(0,T.jsx)(`div`,{className:`py-8 text-center text-sm text-[var(--app-text-subtle)]`,children:`Loading...`})}):$.length===0?(0,T.jsx)(g,{children:(0,T.jsx)(se,{icon:(0,T.jsx)(a,{size:32}),title:`No plugins`,description:K===`all`?`No plugins installed. Browse the marketplace or install from a URL.`:`No ${K}-scope plugins installed.`,className:`py-8`})}):ye?(0,T.jsx)(`div`,{className:`space-y-3`,children:$.map((e,n)=>{let i=G.has(e.id),a=e.id.split(`@`)[0],o=L===e.id,c=e.projectPath?`${e.id}:${e.projectPath}`:`${e.id}:${n}`;return(0,T.jsxs)(g,{children:[(0,T.jsx)(`div`,{className:`flex items-start justify-between gap-3`,children:(0,T.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-2`,children:[(0,T.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,T.jsx)(`button`,{onClick:()=>Te(e.id),className:`text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`,children:i?(0,T.jsx)(t,{size:14}):(0,T.jsx)(r,{size:14})}),(0,T.jsxs)(`div`,{className:`min-w-0`,children:[(0,T.jsx)(`p`,{className:`truncate text-sm font-medium text-[var(--app-text)]`,children:a}),(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-text-muted)]`,children:e.version?`v${e.version}`:`—`})]})]}),(0,T.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,T.jsx)(h,{variant:e.scope===`user`?`info`:`warning`,children:e.scope}),(0,T.jsx)(h,{variant:e.globalEnabled?`success`:`destructive`,children:e.globalEnabled?`User On`:`User Off`})]}),e.scope===`project`&&e.projectPath?(0,T.jsx)(`p`,{className:`truncate text-[11px] text-[var(--app-text-subtle)]`,title:e.projectPath,children:e.projectPath}):null,(0,T.jsx)(E,{manifest:e.manifest})]})}),(0,T.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center gap-2`,children:[(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs`,disabled:o,onClick:()=>void xe(e.id,!e.globalEnabled),children:o?(0,T.jsx)(s,{size:_.xs,className:`animate-spin`}):e.globalEnabled?`Disable`:`Enable`}),(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-7 px-2 text-xs text-[var(--app-danger)]`,disabled:o,onClick:()=>void Se(e.id),children:(0,T.jsx)(l,{size:_.xs})})]}),i?(0,T.jsx)(`div`,{className:`mt-4 rounded-xl border border-[var(--app-border)] bg-black/10 p-3`,children:(0,T.jsx)(O,{plugin:e,roles:J,operatingId:L,onInstallToRole:Ce})}):null]},c)})}):(0,T.jsx)(g,{padding:!1,children:(0,T.jsxs)(C,{children:[(0,T.jsx)(v,{children:(0,T.jsxs)(x,{children:[(0,T.jsx)(y,{className:`w-8`}),(0,T.jsx)(y,{children:`Name`}),(0,T.jsx)(y,{children:`Version`}),(0,T.jsx)(y,{children:`Scope`}),(0,T.jsx)(y,{children:`Type`}),(0,T.jsx)(y,{children:`Activation`}),(0,T.jsx)(y,{children:`Actions`})]})}),(0,T.jsx)(b,{children:$.map((e,n)=>{let i=G.has(e.id),a=e.id.split(`@`)[0],o=L===e.id,c=e.projectPath?`${e.id}:${e.projectPath}`:`${e.id}:${n}`;return(0,T.jsxs)(w.Fragment,{children:[(0,T.jsxs)(x,{className:`group`,children:[(0,T.jsx)(S,{children:(0,T.jsx)(`button`,{onClick:()=>Te(e.id),className:`text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`,children:i?(0,T.jsx)(t,{size:_.xs}):(0,T.jsx)(r,{size:_.xs})})}),(0,T.jsx)(S,{className:`font-medium text-[var(--app-text)]`,children:a}),(0,T.jsx)(S,{className:`text-xs text-[var(--app-text-muted)]`,children:e.version?`v${e.version}`:`—`}),(0,T.jsxs)(S,{children:[(0,T.jsx)(h,{variant:e.scope===`user`?`info`:`warning`,children:e.scope}),e.scope===`project`&&e.projectPath&&(0,T.jsx)(`div`,{className:`text-[10px] text-[var(--app-text-subtle)] truncate max-w-[120px]`,title:e.projectPath,children:e.projectPath.split(`/`).pop()})]}),(0,T.jsx)(S,{children:(0,T.jsx)(E,{manifest:e.manifest})}),(0,T.jsx)(S,{children:(0,T.jsx)(h,{variant:e.globalEnabled?`success`:`destructive`,children:e.globalEnabled?`User On`:`User Off`})}),(0,T.jsx)(S,{children:(0,T.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-1.5 text-xs`,disabled:o,onClick:()=>void xe(e.id,!e.globalEnabled),children:o?(0,T.jsx)(s,{size:_.xs,className:`animate-spin`}):e.globalEnabled?`Disable`:`Enable`}),(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-1.5 text-xs text-[var(--app-danger)]`,disabled:o,onClick:()=>void Se(e.id),children:(0,T.jsx)(l,{size:_.xs})})]})})]}),i&&(0,T.jsx)(x,{className:`bg-[var(--app-panel)]/50`,children:(0,T.jsx)(S,{colSpan:7,className:`px-6 py-3`,children:(0,T.jsx)(O,{plugin:e,roles:J,operatingId:L,onInstallToRole:Ce})})},`${e.id}-detail`)]},c)})})]})}),(0,T.jsxs)(g,{children:[(0,T.jsxs)(`button`,{className:`flex w-full items-center gap-2 text-sm font-semibold text-[var(--app-text)]`,onClick:()=>pe(!F),children:[(0,T.jsx)(c,{size:_.sm,className:`text-[var(--app-text-muted)]`}),`Marketplace (`,k.length,`)`,F?(0,T.jsx)(t,{size:_.xs,className:`ml-auto`}):(0,T.jsx)(r,{size:_.xs,className:`ml-auto`})]}),F&&(0,T.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,T.jsxs)(`div`,{className:`relative`,children:[(0,T.jsx)(o,{size:_.sm,className:`absolute left-2.5 top-2 text-[var(--app-text-subtle)]`}),(0,T.jsx)(`input`,{className:`w-full rounded border border-[var(--app-border)] bg-[var(--app-panel)] pl-8 pr-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,value:I,onChange:e=>me(e.target.value),placeholder:`Search available plugins...`})]}),j?(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-text-subtle)] text-center py-2`,children:`Loading marketplace...`}):N?(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-danger)] text-center py-2`,children:N}):Ee.length===0?(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-text-subtle)] text-center py-2`,children:I?`No plugins match your search`:`No marketplace plugins available`}):(0,T.jsxs)(C,{children:[(0,T.jsx)(v,{children:(0,T.jsxs)(x,{children:[(0,T.jsx)(y,{children:`Name`}),(0,T.jsx)(y,{children:`Description`}),(0,T.jsx)(y,{children:`Source`}),(0,T.jsx)(y,{children:`Action`})]})}),(0,T.jsx)(b,{children:Ee.map(e=>{let n=ue.has(e.pluginId),r=L===e.pluginId;return(0,T.jsxs)(x,{children:[(0,T.jsx)(S,{className:`font-medium text-[var(--app-text)] text-xs`,children:e.name}),(0,T.jsx)(S,{className:`text-xs text-[var(--app-text-muted)] max-w-[300px] truncate`,title:e.description,children:e.description}),(0,T.jsx)(S,{children:(0,T.jsx)(h,{variant:`muted`,className:`text-[10px]`,children:e.marketplaceName})}),(0,T.jsx)(S,{children:n?(0,T.jsx)(h,{variant:`success`,className:`text-[10px]`,children:`Installed`}):(0,T.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-2 text-xs`,disabled:r,onClick:()=>void Q(e.pluginId),children:r?(0,T.jsx)(s,{size:_.xs,className:`animate-spin`}):(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(i,{size:_.xs}),` Install`]})}),J.length>0&&(0,T.jsxs)(`div`,{className:`relative group/install`,children:[(0,T.jsx)(p,{variant:`ghost`,size:`sm`,className:`h-6 px-1 text-xs text-[var(--app-text-subtle)]`,children:(0,T.jsx)(t,{size:_.xs})}),(0,T.jsx)(`div`,{className:`absolute right-0 top-full mt-1 z-10 hidden group-hover/install:block bg-[var(--app-panel-elevated)] border border-[var(--app-border)] rounded shadow-lg py-1 min-w-[140px]`,children:J.map(t=>(0,T.jsx)(`button`,{className:`block w-full text-left px-3 py-1 text-xs text-[var(--app-text)] hover:bg-[var(--app-panel-muted)]`,disabled:r,onClick:()=>void Q(e.pluginId,`project`,t.workspacePath),children:t.name},t.id))})]})]})})]},e.pluginId)})})]})]})]}),(0,T.jsxs)(g,{children:[(0,T.jsxs)(`button`,{className:`flex w-full items-center gap-2 text-sm font-semibold text-[var(--app-text)]`,onClick:()=>{!W&&U.length===0&&be(),ge(!W)},children:[(0,T.jsx)(te,{size:14,className:`text-[var(--app-text-muted)]`}),`Usage Stats`,W?(0,T.jsx)(t,{size:12,className:`ml-auto`}):(0,T.jsx)(r,{size:12,className:`ml-auto`})]}),W&&(0,T.jsx)(`div`,{className:`mt-3`,children:U.length===0?(0,T.jsx)(`p`,{className:`text-xs text-[var(--app-text-subtle)] text-center py-2`,children:`No usage data yet`}):(0,T.jsxs)(C,{children:[(0,T.jsx)(v,{children:(0,T.jsxs)(x,{children:[(0,T.jsx)(y,{children:`Plugin`}),(0,T.jsx)(y,{children:`Usage Count`}),(0,T.jsx)(y,{children:`Last Used`})]})}),(0,T.jsx)(b,{children:U.map(e=>(0,T.jsxs)(x,{children:[(0,T.jsx)(S,{className:`font-medium text-[var(--app-text)] text-xs`,children:e.pluginName}),(0,T.jsx)(S,{className:`font-mono text-xs text-[var(--app-text-muted)]`,children:e.usageCount}),(0,T.jsx)(S,{className:`text-xs text-[var(--app-text-muted)]`,children:e.lastUsed?oe(e.lastUsed):`—`})]},e.pluginPath))})]})})]})]})}export{k as Plugins};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,B as n,M as r,Q as i,T as a,et as o,o as s,rt as c,st as l,v as u,w as d,x as f}from"./vendor-icons-BlMaTTx3.js";import{r as p,t as m}from"./vendor-react-7e01TWy7.js";import{i as h,n as g}from"./dist-Bdqp1ixJ.js";import{_,a as v,b as y,c as b,d as x,g as ee,i as S,n as C,o as w,p as T,r as E,s as te,t as ne,u as re,v as D,x as O}from"./AlertDialog-r3y6IhpW.js";import{i as k,t as A}from"./Button-BjXgrQ95.js";import{t as j}from"./vendor-state-Bj70wnRm.js";import{i as M,n as ie,r as N,t as P}from"./index-pF--tN9F.js";import{t as F}from"./Card-C153tGfJ.js";import{t as ae}from"./PageHeader-BMvN0xiB.js";import{t as oe}from"./SectionHeader-CiCj3Is0.js";import{a as se,o as ce,t as le}from"./format-CHfBBLog.js";import{t as ue}from"./EmptyState-CXwJFCDQ.js";import{t as de}from"./ui-B_uMx2Fy.js";import{t as fe}from"./useIsMobileLayout-Bwrm84kJ.js";import{Goals as pe,t as me}from"./Goals-Dz3qqp_l.js";import{a as he,i as I,n as ge,o as L,r as R,t as _e}from"./Table-CaFJieh_.js";import{t as ve}from"./Switch-CoUUy5jr.js";var z=e(l(),1),B=m();function ye(e){let t=e+`CollectionProvider`,[n,r]=y(t),[i,a]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=e=>{let{scope:t,children:n}=e,r=z.useRef(null),a=z.useRef(new Map).current;return(0,B.jsx)(i,{scope:t,itemMap:a,collectionRef:r,children:n})};o.displayName=t;let s=e+`CollectionSlot`,c=D(s),l=z.forwardRef((e,t)=>{let{scope:n,children:r}=e;return(0,B.jsx)(c,{ref:k(t,a(s,n).collectionRef),children:r})});l.displayName=s;let u=e+`CollectionItemSlot`,d=`data-radix-collection-item`,f=D(u),p=z.forwardRef((e,t)=>{let{scope:n,children:r,...i}=e,o=z.useRef(null),s=k(t,o),c=a(u,n);return z.useEffect(()=>(c.itemMap.set(o,{ref:o,...i}),()=>void c.itemMap.delete(o))),(0,B.jsx)(f,{[d]:``,ref:s,children:r})});p.displayName=u;function m(t){let n=a(e+`CollectionConsumer`,t);return z.useCallback(()=>{let e=n.collectionRef.current;if(!e)return[];let t=Array.from(e.querySelectorAll(`[${d}]`));return Array.from(n.itemMap.values()).sort((e,n)=>t.indexOf(e.ref.current)-t.indexOf(n.ref.current))},[n.collectionRef,n.itemMap])}return[{Provider:o,Slot:l,ItemSlot:p},m,r]}var V=z.createContext(void 0);function H(e){let t=z.useContext(V);return e||t||`ltr`}var U=`rovingFocusGroup.onEntryFocus`,be={bubbles:!1,cancelable:!0},W=`RovingFocusGroup`,[G,K,xe]=ye(W),[Se,Ce]=y(W,[xe]),[we,Te]=Se(W),q=z.forwardRef((e,t)=>(0,B.jsx)(G.Provider,{scope:e.__scopeRovingFocusGroup,children:(0,B.jsx)(G.Slot,{scope:e.__scopeRovingFocusGroup,children:(0,B.jsx)(J,{...e,ref:t})})}));q.displayName=W;var J=z.forwardRef((e,t)=>{let{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:a,currentTabStopId:o,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:c,onEntryFocus:l,preventScrollOnEntryFocus:u=!1,...d}=e,f=z.useRef(null),p=k(t,f),m=H(a),[h,g]=re({prop:o,defaultProp:s??null,onChange:c,caller:W}),[v,y]=z.useState(!1),b=ee(l),x=K(n),S=z.useRef(!1),[C,w]=z.useState(0);return z.useEffect(()=>{let e=f.current;if(e)return e.addEventListener(U,b),()=>e.removeEventListener(U,b)},[b]),(0,B.jsx)(we,{scope:n,orientation:r,dir:m,loop:i,currentTabStopId:h,onItemFocus:z.useCallback(e=>g(e),[g]),onItemShiftTab:z.useCallback(()=>y(!0),[]),onFocusableItemAdd:z.useCallback(()=>w(e=>e+1),[]),onFocusableItemRemove:z.useCallback(()=>w(e=>e-1),[]),children:(0,B.jsx)(_.div,{tabIndex:v||C===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:`none`,...e.style},onMouseDown:O(e.onMouseDown,()=>{S.current=!0}),onFocus:O(e.onFocus,e=>{let t=!S.current;if(e.target===e.currentTarget&&t&&!v){let t=new CustomEvent(U,be);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){let e=x().filter(e=>e.focusable);Ae([e.find(e=>e.active),e.find(e=>e.id===h),...e].filter(Boolean).map(e=>e.ref.current),u)}}S.current=!1}),onBlur:O(e.onBlur,()=>y(!1))})})}),Ee=`RovingFocusGroupItem`,De=z.forwardRef((e,t)=>{let{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:a,children:o,...s}=e,c=T(),l=a||c,u=Te(Ee,n),d=u.currentTabStopId===l,f=K(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u;return z.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),(0,B.jsx)(G.ItemSlot,{scope:n,id:l,focusable:r,active:i,children:(0,B.jsx)(_.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...s,ref:t,onMouseDown:O(e.onMouseDown,e=>{r?u.onItemFocus(l):e.preventDefault()}),onFocus:O(e.onFocus,()=>u.onItemFocus(l)),onKeyDown:O(e.onKeyDown,e=>{if(e.key===`Tab`&&e.shiftKey){u.onItemShiftTab();return}if(e.target!==e.currentTarget)return;let t=Y(e,u.orientation,u.dir);if(t!==void 0){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let n=f().filter(e=>e.focusable).map(e=>e.ref.current);if(t===`last`)n.reverse();else if(t===`prev`||t===`next`){t===`prev`&&n.reverse();let r=n.indexOf(e.currentTarget);n=u.loop?X(n,r+1):n.slice(r+1)}setTimeout(()=>Ae(n))}}),children:typeof o==`function`?o({isCurrentTabStop:d,hasTabStop:h!=null}):o})})});De.displayName=Ee;var Oe={ArrowLeft:`prev`,ArrowUp:`prev`,ArrowRight:`next`,ArrowDown:`next`,PageUp:`first`,Home:`first`,PageDown:`last`,End:`last`};function ke(e,t){return t===`rtl`?e===`ArrowLeft`?`ArrowRight`:e===`ArrowRight`?`ArrowLeft`:e:e}function Y(e,t,n){let r=ke(e.key,n);if(!(t===`vertical`&&[`ArrowLeft`,`ArrowRight`].includes(r))&&!(t===`horizontal`&&[`ArrowUp`,`ArrowDown`].includes(r)))return Oe[r]}function Ae(e,t=!1){let n=document.activeElement;for(let r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function X(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var je=q,Me=De,Z=`Tabs`,[Ne,Pe]=y(Z,[Ce]),Q=Ce(),[Fe,Ie]=Ne(Z),Le=z.forwardRef((e,t)=>{let{__scopeTabs:n,value:r,onValueChange:i,defaultValue:a,orientation:o=`horizontal`,dir:s,activationMode:c=`automatic`,...l}=e,u=H(s),[d,f]=re({prop:r,onChange:i,defaultProp:a??``,caller:Z});return(0,B.jsx)(Fe,{scope:n,baseId:T(),value:d,onValueChange:f,orientation:o,dir:u,activationMode:c,children:(0,B.jsx)(_.div,{dir:u,"data-orientation":o,...l,ref:t})})});Le.displayName=Z;var Re=`TabsList`,ze=z.forwardRef((e,t)=>{let{__scopeTabs:n,loop:r=!0,...i}=e,a=Ie(Re,n),o=Q(n);return(0,B.jsx)(je,{asChild:!0,...o,orientation:a.orientation,dir:a.dir,loop:r,children:(0,B.jsx)(_.div,{role:`tablist`,"aria-orientation":a.orientation,...i,ref:t})})});ze.displayName=Re;var Be=`TabsTrigger`,Ve=z.forwardRef((e,t)=>{let{__scopeTabs:n,value:r,disabled:i=!1,...a}=e,o=Ie(Be,n),s=Q(n),c=We(o.baseId,r),l=Ge(o.baseId,r),u=r===o.value;return(0,B.jsx)(Me,{asChild:!0,...s,focusable:!i,active:u,children:(0,B.jsx)(_.button,{type:`button`,role:`tab`,"aria-selected":u,"aria-controls":l,"data-state":u?`active`:`inactive`,"data-disabled":i?``:void 0,disabled:i,id:c,...a,ref:t,onMouseDown:O(e.onMouseDown,e=>{!i&&e.button===0&&e.ctrlKey===!1?o.onValueChange(r):e.preventDefault()}),onKeyDown:O(e.onKeyDown,e=>{[` `,`Enter`].includes(e.key)&&o.onValueChange(r)}),onFocus:O(e.onFocus,()=>{let e=o.activationMode!==`manual`;!u&&!i&&e&&o.onValueChange(r)})})})});Ve.displayName=Be;var He=`TabsContent`,Ue=z.forwardRef((e,t)=>{let{__scopeTabs:n,value:r,forceMount:i,children:a,...o}=e,s=Ie(He,n),c=We(s.baseId,r),l=Ge(s.baseId,r),u=r===s.value,d=z.useRef(u);return z.useEffect(()=>{let e=requestAnimationFrame(()=>d.current=!1);return()=>cancelAnimationFrame(e)},[]),(0,B.jsx)(x,{present:i||u,children:({present:n})=>(0,B.jsx)(_.div,{"data-state":u?`active`:`inactive`,"data-orientation":s.orientation,role:`tabpanel`,"aria-labelledby":c,hidden:!n,id:l,tabIndex:0,...o,ref:t,style:{...e.style,animationDuration:d.current?`0s`:void 0},children:n&&a})})});Ue.displayName=He;function We(e,t){return`${e}-trigger-${t}`}function Ge(e,t){return`${e}-content-${t}`}var Ke=Le,qe=ze,Je=Ve,Ye=Ue,Xe=Ke,Ze=z.forwardRef(({className:e,...t},n)=>(0,B.jsx)(qe,{ref:n,className:h(`surface-panel-muted inline-flex min-h-11 items-center justify-center gap-1 rounded-full p-1 text-[var(--app-text-muted)]`,e),...t}));Ze.displayName=qe.displayName;var Qe=z.forwardRef(({className:e,...t},n)=>(0,B.jsx)(Je,{ref:n,className:h(`inline-flex items-center justify-center whitespace-nowrap rounded-full px-4 py-2 text-sm font-medium ring-offset-[var(--app-canvas)] transition-[background-color,color,box-shadow] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:surface-panel data-[state=active]:text-[var(--app-text)] data-[state=active]:shadow-[var(--app-shadow-sm)]`,e),...t}));Qe.displayName=Je.displayName;var $e=z.forwardRef(({className:e,...t},n)=>(0,B.jsx)(Ye,{ref:n,className:h(`mt-4 ring-offset-[var(--app-canvas)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2`,e),...t}));$e.displayName=Ye.displayName;var et=[{label:`All`,value:`all`},{label:`Running`,value:`running`},{label:`Pending`,value:`pending`},{label:`Completed`,value:`completed`},{label:`Failed`,value:`failed`},{label:`Cancelled`,value:`cancelled`}],$=new Set([`pending`,`queued`,`running`,`paused`]);function tt(){let e=N(e=>e.tasks),t=N(e=>e.fetchTasks),[n,i]=(0,z.useState)(`all`),[a,s]=(0,z.useState)(!1),[l,d]=(0,z.useState)(``),[m,h]=(0,z.useState)(!1),[_,v]=(0,z.useState)(new Set),[y,b]=(0,z.useState)(!1),x=fe();(0,z.useEffect)(()=>{let e=n===`all`?void 0:n;t(e);let r=setInterval(()=>void t(e),5e3);return()=>clearInterval(r)},[t,n]),(0,z.useEffect)(()=>{v(new Set)},[n]);let ee=async()=>{if(l.trim()){h(!0);try{await g(`/tasks`,{method:`POST`,body:JSON.stringify({prompt:l.trim()})}),d(``),s(!1),t(n===`all`?void 0:n)}finally{h(!1)}}},S=e=>{v(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},C=()=>{let e=T.filter(e=>$.has(e.status)).map(e=>e.id);v(new Set(e))},w=async()=>{if(_.size!==0){b(!0);try{await g(`/tasks/batch-cancel`,{method:`POST`,body:JSON.stringify({taskIds:Array.from(_)})}),v(new Set),t(n===`all`?void 0:n)}finally{b(!1)}}},T=[...e].sort((e,t)=>t.createdAt-e.createdAt),E=Array.from(_).filter(t=>{let n=e.find(e=>e.id===t);return n&&$.has(n.status)});return(0,B.jsxs)(`div`,{className:`space-y-4`,children:[(0,B.jsx)(oe,{title:`Tasks`,description:`Review active execution, cancel work, or create the next task.`,compact:!0,action:(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[_.size>0&&(0,B.jsxs)(A,{variant:`destructive`,size:`sm`,onClick:()=>void w(),disabled:y||E.length===0,children:[(0,B.jsx)(c,{size:de.sm}),y?`Cancelling...`:`Cancel ${E.length} task${E.length===1?``:`s`}`]}),(0,B.jsx)(A,{variant:`ghost`,size:`sm`,onClick:()=>void t(n===`all`?void 0:n),children:(0,B.jsx)(u,{size:de.sm})}),(0,B.jsxs)(A,{size:`sm`,onClick:()=>s(!a),children:[(0,B.jsx)(f,{size:de.sm}),`New Task`]})]})}),a&&(0,B.jsxs)(F,{className:`flex gap-2`,children:[(0,B.jsx)(`input`,{className:`flex-1 rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Enter task prompt...`,value:l,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&ee()}}),(0,B.jsx)(A,{onClick:()=>void ee(),disabled:m||!l.trim(),children:m?`Creating...`:`Create`}),(0,B.jsx)(A,{variant:`ghost`,onClick:()=>s(!1),children:`Cancel`})]}),(0,B.jsxs)(`div`,{className:`flex flex-col gap-2 md:flex-row md:items-center md:justify-between`,children:[(0,B.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:et.map(e=>(0,B.jsx)(`button`,{onClick:()=>i(e.value),className:`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${n===e.value?`bg-[var(--app-panel-elevated)] text-[var(--app-text)]`:`text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`}`,children:e.label},e.value))}),(0,B.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[T.some(e=>$.has(e.status))&&(0,B.jsx)(`button`,{onClick:C,className:`text-xs text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`,children:`Select all cancellable`}),_.size>0&&(0,B.jsxs)(`button`,{onClick:()=>v(new Set),className:`text-xs text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`,children:[`Clear selection (`,_.size,`)`]})]})]}),T.length===0?(0,B.jsx)(F,{padding:!1,children:(0,B.jsx)(ue,{icon:(0,B.jsx)(r,{size:32}),title:`No tasks found`,description:n===`all`?`Create a task to get started`:`No tasks with status "${n}"`})}):x?(0,B.jsx)(`div`,{className:`space-y-3`,children:T.map(e=>(0,B.jsx)(F,{className:_.has(e.id)?`border-[var(--app-accent)]/40 bg-[var(--app-accent)]/8`:``,children:(0,B.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,B.jsx)(`div`,{className:`pt-1`,children:$.has(e.status)?(0,B.jsx)(`button`,{onClick:()=>S(e.id),className:`flex h-4 w-4 items-center justify-center rounded border transition-colors ${_.has(e.id)?`border-[var(--app-accent-strong)] bg-[var(--app-accent)] text-white`:`border-[var(--app-border-strong)] bg-transparent hover:border-[var(--app-text-muted)]`}`,children:_.has(e.id)&&(0,B.jsx)(o,{size:12})}):(0,B.jsx)(`span`,{className:`inline-block h-4 w-4`})}),(0,B.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[(0,B.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[(0,B.jsxs)(`div`,{className:`min-w-0 space-y-1`,children:[(0,B.jsx)(p,{to:`/tasks/${e.id}`,className:`break-all font-mono text-xs text-[var(--app-accent)] hover:text-[var(--app-accent)]`,children:e.id.slice(0,8)}),(0,B.jsx)(`p`,{className:`break-words text-sm font-medium leading-6 text-[var(--app-text)]`,children:ce(e.prompt,140)})]}),(0,B.jsx)(P,{variant:ie(e.status),children:e.status})]}),(0,B.jsxs)(`div`,{className:`grid gap-2 text-xs text-[var(--app-text-subtle)] sm:grid-cols-3`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:`Role`}),(0,B.jsx)(`div`,{className:`mt-1 font-mono text-[var(--app-text)]`,children:e.roleId?e.roleId.slice(0,12):`—`})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:`Cost`}),(0,B.jsx)(`div`,{className:`mt-1 font-mono text-[var(--app-text)]`,children:e.costUsd==null?`—`:le(e.costUsd)})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`span`,{className:`text-[10px] uppercase tracking-[0.14em] text-[var(--app-text-subtle)]`,children:`Created`}),(0,B.jsx)(`div`,{className:`mt-1 text-[var(--app-text)]`,children:se(e.createdAt)})]})]})]})]})},e.id))}):(0,B.jsx)(F,{padding:!1,children:(0,B.jsxs)(_e,{children:[(0,B.jsx)(he,{children:(0,B.jsxs)(L,{children:[(0,B.jsx)(I,{className:`w-8`,children:(0,B.jsx)(`button`,{onClick:()=>{_.size>0&&_.size===T.filter(e=>$.has(e.status)).length?v(new Set):C()},className:`flex h-4 w-4 items-center justify-center rounded border transition-colors ${_.size>0&&_.size===T.filter(e=>$.has(e.status)).length?`border-[var(--app-accent-strong)] bg-[var(--app-accent)] text-white`:`border-[var(--app-border-strong)] bg-transparent hover:border-[var(--app-text-muted)]`}`,children:_.size>0&&_.size===T.filter(e=>$.has(e.status)).length&&(0,B.jsx)(o,{size:12})})}),(0,B.jsx)(I,{children:`ID`}),(0,B.jsx)(I,{children:`Prompt`}),(0,B.jsx)(I,{children:`Status`}),(0,B.jsx)(I,{children:`Role`}),(0,B.jsx)(I,{children:`Cost`}),(0,B.jsx)(I,{children:`Created`})]})}),(0,B.jsx)(ge,{children:T.map(e=>(0,B.jsxs)(L,{className:_.has(e.id)?`bg-[var(--app-panel-elevated)]/50`:``,children:[(0,B.jsx)(R,{children:$.has(e.status)?(0,B.jsx)(`button`,{onClick:()=>S(e.id),className:`flex h-4 w-4 items-center justify-center rounded border transition-colors ${_.has(e.id)?`border-[var(--app-accent-strong)] bg-[var(--app-accent)] text-white`:`border-[var(--app-border-strong)] bg-transparent hover:border-[var(--app-text-muted)]`}`,children:_.has(e.id)&&(0,B.jsx)(o,{size:12})}):(0,B.jsx)(`span`,{className:`inline-block w-4`})}),(0,B.jsx)(R,{children:(0,B.jsx)(p,{to:`/tasks/${e.id}`,className:`font-mono text-xs text-[var(--app-accent)] hover:text-[var(--app-accent)]`,children:e.id.slice(0,8)})}),(0,B.jsx)(R,{children:(0,B.jsxs)(`div`,{className:`space-y-1`,children:[(0,B.jsx)(`div`,{className:`break-words font-medium text-[var(--app-text)]`,children:ce(e.prompt,120)}),(0,B.jsxs)(`div`,{className:`text-xs text-[var(--app-text-subtle)]`,children:[e.totalDurationMs?le(e.costUsd??0):`Awaiting completion`,` · `,se(e.createdAt)]})]})}),(0,B.jsx)(R,{children:(0,B.jsx)(P,{variant:ie(e.status),children:e.status})}),(0,B.jsx)(R,{children:(0,B.jsx)(`span`,{className:`font-mono text-xs text-[var(--app-text-subtle)]`,children:e.roleId?e.roleId.slice(0,12):`—`})}),(0,B.jsx)(R,{className:`font-mono text-xs`,children:e.costUsd==null?`—`:le(e.costUsd)}),(0,B.jsx)(R,{className:`text-xs text-[var(--app-text-subtle)]`,children:se(e.createdAt)})]},e.id))})]})})]})}function nt(e){return`step-${e+1}`}function rt(){let e=N(e=>e.templates),r=N(e=>e.fetchTemplates),o=N(e=>e.goals),c=N(e=>e.fetchGoals),l=N(e=>e.roles),p=N(e=>e.fetchRoles),[m,h]=(0,z.useState)(!1),[_,y]=(0,z.useState)(``),[x,ee]=(0,z.useState)(`manual`),[T,re]=(0,z.useState)(``),[D,O]=(0,z.useState)(``),[k,j]=(0,z.useState)([{id:`step-1`,prompt:``}]),[ie,ae]=(0,z.useState)(!1),[ce,le]=(0,z.useState)(!1),[de,fe]=(0,z.useState)(null),[pe,ye]=(0,z.useState)(null),[V,H]=(0,z.useState)(null),[U,be]=(0,z.useState)(null),[W,G]=(0,z.useState)(``),[K,xe]=(0,z.useState)(`manual`),[Se,Ce]=(0,z.useState)(``),[we,Te]=(0,z.useState)(``),[q,J]=(0,z.useState)([]),[Ee,De]=(0,z.useState)(!1),[Oe,ke]=(0,z.useState)(!1),[Y,Ae]=(0,z.useState)(`prompt`),[X,je]=(0,z.useState)([]),[Me,Z]=(0,z.useState)([]),[Ne,Pe]=(0,z.useState)([]),[Q,Fe]=(0,z.useState)(null),[Ie,Le]=(0,z.useState)([]),[Re,ze]=(0,z.useState)(!1),Be=(0,z.useCallback)(async e=>{ze(!0);try{let t=await g(`/workflow-executions?templateId=${e}&limit=5`);Le(await Promise.all(t.executions.map(async e=>{try{let t=await g(`/workflow-executions/${e.id}`);return{...t.execution,stepTasks:t.stepTasks}}catch{return{...e,stepTasks:[]}}})))}catch{Le([])}finally{ze(!1)}},[]),Ve=(0,z.useCallback)(e=>{Q===e?(Fe(null),Le([])):(Fe(e),Be(e))},[Q,Be]);(0,z.useEffect)(()=>{r(),c(),p()},[r,c,p]);let He=async()=>{if(_.trim()&&!(Y===`prompt`&&k.every(e=>!e.prompt.trim()))&&!(Y===`goal`&&X.length===0)){le(!0);try{let e={name:_.trim(),trigger:{type:x,...x===`cron`&&T?{cron:T}:{},...x===`once`&&D?{runAt:new Date(D).toISOString()}:{}},enabled:!0,...Me.length>0?{deliverTo:Me}:{},...ie?{config:{continueOnError:!0}}:{}};Y===`prompt`?e.steps=k.filter(e=>e.prompt.trim()).map((e,t)=>({id:e.id||nt(t),prompt:e.prompt.trim(),...e.roleId?{roleId:e.roleId}:{},...e.dependsOn&&e.dependsOn.length>0?{dependsOn:e.dependsOn}:{},...e.config&&(e.config.timeout!==void 0||e.config.maxTurns!==void 0)?{config:e.config}:{}})):(e.goalIds=X,e.steps=[]),await g(`/task-templates`,{method:`POST`,body:JSON.stringify(e)}),y(``),j([{id:`step-1`,prompt:``}]),re(``),O(``),je([]),Z([]),h(!1),r()}finally{le(!1)}}},Ue=async t=>{let n=e.find(e=>e.id===t);fe(t);try{await g(`/task-templates/${t}/run`,{method:`POST`}),M.success(`Triggered: ${n?.name??t}`)}catch(e){let t=e instanceof Error?e.message:`Failed to trigger template`;M.error(`Trigger failed: ${t}`)}finally{fe(null)}},We=async t=>{let n=e.find(e=>e.id===t);try{await g(`/task-templates/${t}`,{method:`DELETE`}),M.success(`Deleted: ${n?.name??t}`),r()}catch(e){let t=e instanceof Error?e.message:`Failed to delete template`;M.error(`Delete failed: ${t}`)}},Ge=async t=>{let n=e.find(e=>e.id===t);if(!n)return;if(n.trigger.type!==`cron`&&n.trigger.type!==`event`&&n.trigger.type!==`once`){M.error(`Toggle not applicable for manual triggers`);return}let i=!n.enabled;try{await g(`/task-templates/${t}`,{method:`PATCH`,body:JSON.stringify({enabled:i})}),M.success(`${n.name} ${i?`enabled`:`disabled`}`),r()}catch(e){let t=e instanceof Error?e.message:`Failed to toggle template`;M.error(`Toggle failed: ${t}`)}},Ke=e=>{be(e.id),G(e.name),xe(e.trigger.type),Ce(e.trigger.cron??``),Te(e.trigger.runAt?new Date(e.trigger.runAt).toISOString().slice(0,16):``),J(e.steps.map(e=>({id:e.id,prompt:e.prompt,roleId:e.roleId,dependsOn:e.dependsOn,config:e.config}))),De(e.config?.continueOnError??!1),Pe(e.deliverTo??[])},qe=async()=>{if(!(!U||!W.trim()||q.every(e=>!e.prompt.trim()))){ke(!0);try{await g(`/task-templates/${U}`,{method:`PATCH`,body:JSON.stringify({name:W.trim(),trigger:{type:K,...K===`cron`&&Se?{cron:Se}:{},...K===`once`&&we?{runAt:new Date(we).toISOString()}:{}},steps:q.filter(e=>e.prompt.trim()).map((e,t)=>({id:e.id||nt(t),prompt:e.prompt.trim(),...e.roleId?{roleId:e.roleId}:{},...e.dependsOn&&e.dependsOn.length>0?{dependsOn:e.dependsOn}:{},...e.config&&(e.config.timeout!==void 0||e.config.maxTurns!==void 0)?{config:e.config}:{}})),enabled:e.find(e=>e.id===U)?.enabled??!0,...Ee?{config:{continueOnError:!0}}:{config:{}},deliverTo:Ne.length>0?Ne:void 0})}),be(null),r(),M.success(`Template updated`)}catch(e){let t=e instanceof Error?e.message:`Failed to update template`;M.error(t)}finally{ke(!1)}}},Je=e.find(e=>e.id===pe),Ye=e.find(e=>e.id===V);return(0,B.jsxs)(`div`,{className:`space-y-4`,children:[(0,B.jsx)(oe,{title:`Automations`,description:`Reusable workflows, manual triggers, and recent workflow runs.`,compact:!0,action:(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsx)(A,{variant:`ghost`,size:`sm`,onClick:()=>void r(),children:(0,B.jsx)(u,{size:14})}),(0,B.jsxs)(A,{size:`sm`,onClick:()=>h(!m),children:[(0,B.jsx)(f,{size:14}),`New Automation`]})]})}),m&&(0,B.jsxs)(F,{className:`space-y-3`,children:[(0,B.jsx)(`input`,{className:`w-full rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Template name`,value:_,onChange:e=>y(e.target.value)}),(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsxs)(`select`,{className:`rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] focus:border-[var(--app-accent)] focus:outline-none`,value:x,onChange:e=>ee(e.target.value),children:[(0,B.jsx)(`option`,{value:`manual`,children:`Manual`}),(0,B.jsx)(`option`,{value:`cron`,children:`Cron`}),(0,B.jsx)(`option`,{value:`event`,children:`Event`}),(0,B.jsx)(`option`,{value:`once`,children:`Once`})]}),x===`cron`&&(0,B.jsx)(`input`,{className:`flex-1 rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Cron expression (e.g. */5 * * * *)`,value:T,onChange:e=>re(e.target.value)}),x===`once`&&(0,B.jsx)(`input`,{type:`datetime-local`,className:`flex-1 rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] focus:border-[var(--app-accent)] focus:outline-none`,value:D,onChange:e=>O(e.target.value)})]}),(0,B.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,B.jsx)(`span`,{className:`text-xs text-[var(--app-text-muted)]`,children:`Action type:`}),(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:()=>Ae(`prompt`),className:`rounded px-2 py-1 text-xs ${Y===`prompt`?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-muted)] hover:text-[var(--app-text)]`}`,children:`Custom Prompt`}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>Ae(`goal`),className:`rounded px-2 py-1 text-xs ${Y===`goal`?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-muted)] hover:text-[var(--app-text)]`}`,children:`Goal Reference`})]})]}),Y===`prompt`?(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,B.jsx)(`span`,{className:`text-xs text-[var(--app-text-muted)]`,children:`Steps`}),(0,B.jsxs)(A,{variant:`ghost`,size:`sm`,onClick:()=>j([...k,{id:nt(k.length),prompt:``}]),children:[(0,B.jsx)(f,{size:12}),` Add Step`]})]}),k.map((e,t)=>(0,B.jsxs)(`div`,{className:`rounded-md border border-[var(--app-border)] p-2 space-y-1.5`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(`span`,{className:`text-[10px] font-mono text-[var(--app-text-subtle)]`,children:e.id}),(0,B.jsxs)(`select`,{className:`flex-1 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-2 py-1 text-xs text-[var(--app-text)]`,value:e.roleId??``,onChange:n=>{let r=[...k];r[t]={...e,roleId:n.target.value||void 0},j(r)},children:[(0,B.jsx)(`option`,{value:``,children:`Role (template default)`}),l.filter(e=>e.source!==`system`).map(e=>(0,B.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),k.length>1&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>j(k.filter((e,n)=>n!==t)),className:`text-[var(--app-danger)] hover:text-[var(--app-danger-soft-text)]`,children:(0,B.jsx)(s,{size:12})})]}),(0,B.jsx)(`textarea`,{className:`w-full rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-2 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Step ${t+1} prompt${t>0?` (use {{`+k[t-1].id+`.result}} for prev output)`:``}`,rows:2,value:e.prompt,onChange:n=>{let r=[...k];r[t]={...e,prompt:n.target.value},j(r)}}),t>0&&(0,B.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,B.jsx)(`span`,{className:`text-[10px] text-[var(--app-text-subtle)]`,children:`depends on:`}),k.slice(0,t).map(n=>(0,B.jsx)(`button`,{type:`button`,onClick:()=>{let r=e.dependsOn??[],i=[...k];i[t]={...e,dependsOn:r.includes(n.id)?r.filter(e=>e!==n.id):[...r,n.id]},j(i)},className:`rounded px-1.5 py-0.5 text-[10px] ${(e.dependsOn??[]).includes(n.id)?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`}`,children:n.id},n.id))]}),(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsxs)(`label`,{className:`flex items-center gap-1 text-[10px] text-[var(--app-text-subtle)]`,children:[`timeout(s):`,(0,B.jsx)(`input`,{type:`number`,min:0,placeholder:`default`,className:`w-20 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-1.5 py-0.5 text-xs text-[var(--app-text)]`,value:e.config?.timeout??``,onChange:n=>{let r=[...k],i=n.target.value===``?void 0:Number(n.target.value);r[t]={...e,config:{...e.config,timeout:i}},j(r)}})]}),(0,B.jsxs)(`label`,{className:`flex items-center gap-1 text-[10px] text-[var(--app-text-subtle)]`,children:[`max turns:`,(0,B.jsx)(`input`,{type:`number`,min:0,placeholder:`default`,className:`w-20 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-1.5 py-0.5 text-xs text-[var(--app-text)]`,value:e.config?.maxTurns??``,onChange:n=>{let r=[...k],i=n.target.value===``?void 0:Number(n.target.value);r[t]={...e,config:{...e.config,maxTurns:i}},j(r)}})]})]})]},e.id))]}):(0,B.jsx)(`div`,{className:`space-y-1`,children:o.length===0?(0,B.jsx)(`p`,{className:`text-xs text-[var(--app-text-subtle)]`,children:`No goals available`}):o.map(e=>(0,B.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-[var(--app-text)] hover:text-[var(--app-text)] cursor-pointer`,children:[(0,B.jsx)(`input`,{type:`checkbox`,checked:X.includes(e.id),onChange:t=>{t.target.checked?je([...X,e.id]):je(X.filter(t=>t!==e.id))},className:`rounded border-[var(--app-border-strong)] bg-[var(--app-panel-elevated)]`}),(0,B.jsx)(`span`,{className:`truncate`,children:e.name}),(0,B.jsx)(P,{variant:`muted`,className:`text-[10px]`,children:e.status})]},e.id))}),k.length>1&&(0,B.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-[var(--app-text)] cursor-pointer`,children:[(0,B.jsx)(`input`,{type:`checkbox`,checked:ie,onChange:e=>ae(e.target.checked),className:`rounded border-[var(--app-border-strong)] bg-[var(--app-panel-elevated)]`}),`Continue on error (skip failed step dependents, run independent steps)`]}),(0,B.jsx)(me,{value:Me,onChange:Z}),(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsx)(A,{onClick:()=>void He(),disabled:ce||!_.trim()||Y===`prompt`&&k.every(e=>!e.prompt.trim())||Y===`goal`&&X.length===0,children:ce?`Creating...`:`Create`}),(0,B.jsx)(A,{variant:`ghost`,onClick:()=>h(!1),children:`Cancel`})]})]}),U!==null&&(0,B.jsxs)(F,{className:`space-y-3`,children:[(0,B.jsx)(`span`,{className:`text-sm font-medium text-[var(--app-text)]`,children:`Edit Automation`}),(0,B.jsx)(`input`,{className:`w-full rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Template name`,value:W,onChange:e=>G(e.target.value)}),(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsxs)(`select`,{className:`rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] focus:border-[var(--app-accent)] focus:outline-none`,value:K,onChange:e=>xe(e.target.value),children:[(0,B.jsx)(`option`,{value:`manual`,children:`Manual`}),(0,B.jsx)(`option`,{value:`cron`,children:`Cron`}),(0,B.jsx)(`option`,{value:`event`,children:`Event`}),(0,B.jsx)(`option`,{value:`once`,children:`Once`})]}),K===`cron`&&(0,B.jsx)(`input`,{className:`flex-1 rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Cron expression`,value:Se,onChange:e=>Ce(e.target.value)}),K===`once`&&(0,B.jsx)(`input`,{type:`datetime-local`,className:`flex-1 rounded-md border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-3 py-1.5 text-sm text-[var(--app-text)] focus:border-[var(--app-accent)] focus:outline-none`,value:we,onChange:e=>Te(e.target.value)})]}),(0,B.jsxs)(`div`,{className:`space-y-2`,children:[(0,B.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,B.jsx)(`span`,{className:`text-xs text-[var(--app-text-muted)]`,children:`Steps`}),(0,B.jsxs)(A,{variant:`ghost`,size:`sm`,onClick:()=>J([...q,{id:nt(q.length),prompt:``}]),children:[(0,B.jsx)(f,{size:12}),` Add Step`]})]}),q.map((e,t)=>(0,B.jsxs)(`div`,{className:`rounded-md border border-[var(--app-border)] p-2 space-y-1.5`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(`span`,{className:`text-[10px] font-mono text-[var(--app-text-subtle)]`,children:e.id}),(0,B.jsxs)(`select`,{className:`flex-1 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-2 py-1 text-xs text-[var(--app-text)]`,value:e.roleId??``,onChange:n=>{let r=[...q];r[t]={...e,roleId:n.target.value||void 0},J(r)},children:[(0,B.jsx)(`option`,{value:``,children:`Role (template default)`}),l.filter(e=>e.source!==`system`).map(e=>(0,B.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),q.length>1&&(0,B.jsx)(`button`,{type:`button`,onClick:()=>J(q.filter((e,n)=>n!==t)),className:`text-[var(--app-danger)] hover:text-[var(--app-danger-soft-text)]`,children:(0,B.jsx)(s,{size:12})})]}),(0,B.jsx)(`textarea`,{className:`w-full rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-2 py-1.5 text-sm text-[var(--app-text)] placeholder:text-[var(--app-text-subtle)] focus:border-[var(--app-accent)] focus:outline-none`,placeholder:`Step ${t+1} prompt`,rows:2,value:e.prompt,onChange:n=>{let r=[...q];r[t]={...e,prompt:n.target.value},J(r)}}),t>0&&(0,B.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,B.jsx)(`span`,{className:`text-[10px] text-[var(--app-text-subtle)]`,children:`depends on:`}),q.slice(0,t).map(n=>(0,B.jsx)(`button`,{type:`button`,onClick:()=>{let r=e.dependsOn??[],i=[...q];i[t]={...e,dependsOn:r.includes(n.id)?r.filter(e=>e!==n.id):[...r,n.id]},J(i)},className:`rounded px-1.5 py-0.5 text-[10px] ${(e.dependsOn??[]).includes(n.id)?`bg-[var(--app-accent)] text-white`:`bg-[var(--app-panel-elevated)] text-[var(--app-text-subtle)] hover:text-[var(--app-text)]`}`,children:n.id},n.id))]}),(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsxs)(`label`,{className:`flex items-center gap-1 text-[10px] text-[var(--app-text-subtle)]`,children:[`timeout(s):`,(0,B.jsx)(`input`,{type:`number`,min:0,placeholder:`default`,className:`w-20 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-1.5 py-0.5 text-xs text-[var(--app-text)]`,value:e.config?.timeout??``,onChange:n=>{let r=[...q],i=n.target.value===``?void 0:Number(n.target.value);r[t]={...e,config:{...e.config,timeout:i}},J(r)}})]}),(0,B.jsxs)(`label`,{className:`flex items-center gap-1 text-[10px] text-[var(--app-text-subtle)]`,children:[`max turns:`,(0,B.jsx)(`input`,{type:`number`,min:0,placeholder:`default`,className:`w-20 rounded border border-[var(--app-border)] bg-[var(--app-panel-elevated)] px-1.5 py-0.5 text-xs text-[var(--app-text)]`,value:e.config?.maxTurns??``,onChange:n=>{let r=[...q],i=n.target.value===``?void 0:Number(n.target.value);r[t]={...e,config:{...e.config,maxTurns:i}},J(r)}})]})]})]},e.id))]}),q.length>1&&(0,B.jsxs)(`label`,{className:`flex items-center gap-2 text-xs text-[var(--app-text)] cursor-pointer`,children:[(0,B.jsx)(`input`,{type:`checkbox`,checked:Ee,onChange:e=>De(e.target.checked),className:`rounded border-[var(--app-border-strong)] bg-[var(--app-panel-elevated)]`}),`Continue on error`]}),(0,B.jsx)(me,{value:Ne,onChange:Pe}),(0,B.jsxs)(`div`,{className:`flex gap-2`,children:[(0,B.jsx)(A,{onClick:()=>void qe(),disabled:Oe||!W.trim()||q.every(e=>!e.prompt.trim()),children:Oe?`Saving...`:`Save`}),(0,B.jsx)(A,{variant:`ghost`,onClick:()=>be(null),children:`Cancel`})]})]}),(0,B.jsx)(F,{padding:!1,children:e.length===0?(0,B.jsx)(ue,{icon:(0,B.jsx)(n,{size:32}),title:`No automations`,description:`Create an automation to run recurring tasks`}):(0,B.jsxs)(_e,{children:[(0,B.jsx)(he,{children:(0,B.jsxs)(L,{children:[(0,B.jsx)(I,{children:`Name`}),(0,B.jsx)(I,{children:`Trigger`}),(0,B.jsx)(I,{children:`Schedule`}),(0,B.jsx)(I,{children:`Steps`}),(0,B.jsx)(I,{children:`Enabled`}),(0,B.jsx)(I,{children:`Created`}),(0,B.jsx)(I,{children:`Webhook URL`}),(0,B.jsx)(I,{children:`Actions`})]})}),(0,B.jsx)(ge,{children:e.map(e=>(0,B.jsxs)(z.Fragment,{children:[(0,B.jsxs)(L,{children:[(0,B.jsx)(R,{className:`font-medium text-[var(--app-text)]`,children:(0,B.jsxs)(`button`,{type:`button`,onClick:()=>Ve(e.id),className:`flex items-center gap-1 hover:text-[var(--app-accent)] transition-colors`,children:[Q===e.id?(0,B.jsx)(t,{size:12}):(0,B.jsx)(i,{size:12}),e.name]})}),(0,B.jsx)(R,{children:(0,B.jsx)(P,{variant:e.trigger.type===`cron`?`info`:e.trigger.type===`event`?`warning`:(e.trigger.type,`muted`),children:e.trigger.type})}),(0,B.jsx)(R,{className:`font-mono text-xs`,children:e.trigger.type===`once`&&e.trigger.runAt?new Date(e.trigger.runAt).toLocaleString():e.trigger.cron??`—`}),(0,B.jsx)(R,{className:`font-mono text-xs`,children:e.goalIds&&e.goalIds.length>0?`Goals: ${e.goalIds.length}`:(()=>{let t=new Set(e.steps.filter(e=>e.roleId).map(e=>e.roleId));return t.size>0?`${e.steps.length} steps / ${t.size} roles`:String(e.steps.length)})()}),(0,B.jsx)(R,{children:e.trigger.type!==`cron`&&e.trigger.type!==`event`&&e.trigger.type!==`once`?(0,B.jsx)(`span`,{className:`text-xs text-[var(--app-text-subtle)]`,children:`—`}):(0,B.jsx)(ve,{checked:e.enabled,onCheckedChange:()=>void Ge(e.id),"aria-label":`Toggle ${e.name}`})}),(0,B.jsx)(R,{className:`text-xs text-[var(--app-text-subtle)]`,children:e.createdAt?se(e.createdAt):`—`}),(0,B.jsx)(R,{className:`font-mono text-xs text-[var(--app-text-muted)]`,children:e.enabled?`POST /webhooks/${e.id}`:`—`}),(0,B.jsx)(R,{children:(0,B.jsxs)(`div`,{className:`flex gap-1`,children:[(0,B.jsx)(A,{variant:`ghost`,size:`sm`,onClick:()=>Ke(e),title:`Edit`,children:(0,B.jsx)(a,{size:12})}),(0,B.jsx)(A,{variant:`ghost`,size:`sm`,onClick:()=>ye(e.id),disabled:de===e.id,title:`Run now`,children:(0,B.jsx)(d,{size:12})}),(0,B.jsx)(A,{variant:`ghost`,size:`sm`,className:`text-[var(--app-danger)] hover:text-[var(--app-danger-soft-text)]`,onClick:()=>H(e.id),title:`Delete`,children:(0,B.jsx)(s,{size:12})})]})})]}),Q===e.id&&(0,B.jsx)(L,{children:(0,B.jsxs)(R,{colSpan:8,className:`bg-[var(--app-panel)]/50 p-3`,children:[(0,B.jsx)(`div`,{className:`text-xs text-[var(--app-text-muted)] mb-2 font-medium`,children:`Recent Executions`}),Re?(0,B.jsx)(`div`,{className:`text-xs text-[var(--app-text-subtle)]`,children:`Loading...`}):Ie.length===0?(0,B.jsx)(`div`,{className:`text-xs text-[var(--app-text-subtle)]`,children:`No executions yet`}):(0,B.jsx)(`div`,{className:`space-y-1.5`,children:Ie.map(t=>{let n=Object.entries(t.stepStatuses),r=n.filter(([,e])=>e.status===`completed`).length,i=n.filter(([,e])=>e.status===`failed`).length,a=n.filter(([,e])=>e.status===`skipped`).length,o=n.filter(([,e])=>e.status===`cancelled`).length,s=n.length,c=new Map(t.stepTasks.filter(e=>e.stepId).map(e=>[e.stepId,e])),u=[...e.steps.map(e=>e.id),...Object.keys(t.stepStatuses).filter(t=>!e.steps.some(e=>e.id===t))];return(0,B.jsxs)(`div`,{className:`rounded border border-[var(--app-border)] bg-[var(--app-canvas)]/50 p-2.5 space-y-2`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-3 text-xs`,children:[(0,B.jsx)(P,{variant:t.status===`completed`?`success`:t.status===`failed`?`destructive`:t.status===`partial`?`warning`:t.status===`cancelled`?`secondary`:`muted`,children:t.status}),(0,B.jsx)(`span`,{className:`text-[var(--app-text-subtle)]`,children:new Date(t.startedAt).toLocaleString()}),s>0&&(0,B.jsxs)(`span`,{className:`text-[var(--app-text-muted)]`,children:[r,`/`,s,` steps`,(0,B.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[i>0&&(0,B.jsxs)(`span`,{className:`text-[var(--app-danger)]`,children:[i,` failed`]}),a>0&&(0,B.jsxs)(`span`,{className:`text-[var(--app-warning)]`,children:[a,` skipped`]}),o>0&&(0,B.jsxs)(`span`,{className:`text-[var(--app-text)]`,children:[o,` cancelled`]})]})]}),t.completedAt&&(0,B.jsxs)(`span`,{className:`text-[var(--app-text-subtle)]`,children:[Math.round((t.completedAt-t.startedAt)/1e3),`s`]}),(0,B.jsx)(`span`,{className:`font-mono text-[var(--app-text-subtle)] truncate max-w-[120px]`,children:t.id.slice(0,8)})]}),(0,B.jsx)(`div`,{className:`space-y-1.5`,children:u.map(n=>{let r=t.stepStatuses[n];if(!r)return null;let i=e.steps.find(e=>e.id===n),a=c.get(n),o=a?.roleId??r.roleId??i?.roleId,s=l.find(e=>e.id===o)?.name??o,u=a?.error??r.error??a?.result??r.result;return(0,B.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_auto_auto] gap-2 rounded bg-[var(--app-panel)]/60 px-2 py-1.5 text-xs`,children:[(0,B.jsxs)(`div`,{className:`min-w-0`,children:[(0,B.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,B.jsx)(`span`,{className:`font-mono text-[var(--app-text)]`,children:n}),s&&(0,B.jsxs)(`span`,{className:`text-[var(--app-warning-soft-text)]`,children:[`@`,s]}),i?.dependsOn&&i.dependsOn.length>0&&(0,B.jsxs)(`span`,{className:`text-[var(--app-text-subtle)]`,children:[`after `,i.dependsOn.join(`, `)]})]}),u&&(0,B.jsx)(`div`,{className:`mt-1 truncate ${r.status===`failed`?`text-[var(--app-danger-soft-text)]`:r.status===`skipped`?`text-[var(--app-warning-soft-text)]`:r.status===`cancelled`?`text-[var(--app-text)]`:`text-[var(--app-text-muted)]`}`,children:u})]}),(0,B.jsx)(P,{variant:r.status===`completed`?`success`:r.status===`failed`?`destructive`:r.status===`skipped`?`warning`:r.status===`cancelled`?`secondary`:`muted`,children:r.status}),(0,B.jsxs)(`div`,{className:`text-right text-[var(--app-text-subtle)]`,children:[a?.completedAt&&(0,B.jsxs)(`div`,{children:[Math.max(0,Math.round((a.completedAt-a.createdAt)/1e3)),`s`]}),a?.id&&(0,B.jsx)(`div`,{className:`font-mono`,children:a.id.slice(0,8)})]})]},`${t.id}-${n}`)})})]},t.id)})})]})})]},e.id))})]})}),(0,B.jsx)(ne,{open:pe!==null,onOpenChange:e=>{e||ye(null)},children:(0,B.jsxs)(S,{children:[(0,B.jsxs)(te,{children:[(0,B.jsx)(b,{children:`Run Template`}),(0,B.jsxs)(v,{children:[`Run “`,Je?.name,`” now? This will execute the template immediately.`]})]}),(0,B.jsxs)(w,{children:[(0,B.jsx)(E,{children:`Cancel`}),(0,B.jsx)(C,{onClick:()=>{pe&&Ue(pe),ye(null)},children:`Run Now`})]})]})}),(0,B.jsx)(ne,{open:V!==null,onOpenChange:e=>{e||H(null)},children:(0,B.jsxs)(S,{children:[(0,B.jsxs)(te,{children:[(0,B.jsx)(b,{children:`Delete Template`}),(0,B.jsxs)(v,{children:[`Delete “`,Ye?.name,`”? This action cannot be undone.`]})]}),(0,B.jsxs)(w,{children:[(0,B.jsx)(E,{children:`Cancel`}),(0,B.jsx)(C,{className:`bg-[var(--app-danger)] hover:bg-[var(--app-danger)]`,onClick:()=>{V&&We(V),H(null)},children:`Delete`})]})]})})]})}function it(){let{tasks:e,templates:t,goals:n}=N(j(e=>({tasks:e.tasks,templates:e.templates,goals:e.goals}))),r=N(e=>e.fetchTasks),i=N(e=>e.fetchTemplates),a=N(e=>e.fetchGoals);return(0,z.useEffect)(()=>{r(),i(),a()},[r,i,a]),(0,B.jsxs)(`div`,{className:`space-y-4`,children:[(0,B.jsx)(ae,{eyebrow:`Operations`,title:`Work`,description:`Tasks, automations, and goals in one place.`,metrics:[{label:`Running`,value:e.filter(e=>e.status===`running`).length},{label:`Automations`,value:t.length},{label:`Goals`,value:n.length}],compact:!0}),(0,B.jsxs)(Xe,{defaultValue:`tasks`,children:[(0,B.jsxs)(Ze,{children:[(0,B.jsx)(Qe,{value:`tasks`,children:`Tasks`}),(0,B.jsx)(Qe,{value:`automations`,children:`Automations`}),(0,B.jsx)(Qe,{value:`goals`,children:`Goals`})]}),(0,B.jsx)($e,{value:`tasks`,children:(0,B.jsx)(tt,{})}),(0,B.jsx)($e,{value:`automations`,children:(0,B.jsx)(rt,{})}),(0,B.jsx)($e,{value:`goals`,children:(0,B.jsx)(pe,{})})]})]})}export{it as Work};
|