adam-agent-server 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/App-WJMHK5EO.js +13 -0
  2. package/dist/adam-automator-skills-UFW5TXCC.js +18 -0
  3. package/dist/adam-tools-IAZSLWYB.js +1 -0
  4. package/dist/approval-handler-HQO62WK2.js +1 -0
  5. package/dist/audit-manager-LC5EQXCI.js +1 -0
  6. package/dist/bree-engine-M5CZ6A62.js +1 -0
  7. package/dist/channels-5TFYQN5Z.js +1 -0
  8. package/dist/{channels-PUOPR5Y2.js → channels-J4STJ4X2.js} +1 -1
  9. package/dist/{chunk-L4Y3GR6W.js → chunk-2H7UOW4P.js} +1 -1
  10. package/dist/chunk-3LY6PD6A.js +1 -0
  11. package/dist/{chunk-RUY23IJK.js → chunk-4C5ITATX.js} +1 -1
  12. package/dist/{chunk-NZEDILAK.js → chunk-52PR7XTN.js} +1 -1
  13. package/dist/chunk-5OQZPUBV.js +79 -0
  14. package/dist/{chunk-6THDALGC.js → chunk-7446ZS6D.js} +1 -1
  15. package/dist/{chunk-J3NIPZ73.js → chunk-7ZGSJCX5.js} +2 -2
  16. package/dist/{chunk-24GTCFEV.js → chunk-DBP7GPWG.js} +2 -2
  17. package/dist/chunk-DWRYIN5N.js +12 -0
  18. package/dist/chunk-FIN36WAP.js +99 -0
  19. package/dist/{chunk-GYHOPV4Q.js → chunk-FXQAUQTI.js} +1 -1
  20. package/dist/{chunk-KOWFPY2J.js → chunk-FZCNYKNT.js} +1 -1
  21. package/dist/{chunk-QQWRV23T.js → chunk-G5ESQEXN.js} +1 -1
  22. package/dist/chunk-GGIHDFRW.js +6 -0
  23. package/dist/{chunk-I5IUTZA3.js → chunk-GMMWA5EG.js} +1 -1
  24. package/dist/chunk-HWLSHTVX.js +27 -0
  25. package/dist/{chunk-XAMLLKKA.js → chunk-I7ZZKPHE.js} +1 -1
  26. package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
  27. package/dist/chunk-MDBVKBC7.js +47 -0
  28. package/dist/chunk-MJSSCKMB.js +23 -0
  29. package/dist/{chunk-INNDBLZE.js → chunk-MRTJFYPR.js} +1 -1
  30. package/dist/{chunk-YHVFZB6Q.js → chunk-N4ES7TCL.js} +1 -1
  31. package/dist/{chunk-4VHBKJD5.js → chunk-NCFVJCNQ.js} +26 -7
  32. package/dist/{chunk-3567PCEJ.js → chunk-P5ZXNBNV.js} +2 -2
  33. package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
  34. package/dist/{chunk-EZGMA3VV.js → chunk-RLJYEEQC.js} +1 -1
  35. package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
  36. package/dist/{chunk-YHH3QMLL.js → chunk-TNL2LZB7.js} +1 -1
  37. package/dist/{chunk-HYDCXE5K.js → chunk-TSPQ44HT.js} +1 -1
  38. package/dist/{chunk-JKPSEMUZ.js → chunk-V32YF3J5.js} +1 -1
  39. package/dist/{chunk-CKIVKM5T.js → chunk-VVSZZK5T.js} +2 -2
  40. package/dist/{chunk-XF4IERYF.js → chunk-WAG3MNMC.js} +5 -5
  41. package/dist/{chunk-VRP4LTHY.js → chunk-YDVTWPNA.js} +1 -1
  42. package/dist/{chunk-7BSWC62F.js → chunk-YHVYX3F4.js} +1 -1
  43. package/dist/{chunk-KO5AFX5U.js → chunk-YXYIA24D.js} +1 -1
  44. package/dist/chunk-ZL5JXLAX.js +49 -0
  45. package/dist/cli.js +2 -2
  46. package/dist/{config-CBNOT66B.js → config-KFPS7IEH.js} +1 -1
  47. package/dist/config-ZBNGRASI.js +1 -0
  48. package/dist/db-PZ2V7UCK.js +1 -0
  49. package/dist/delivery-log-ACNJ66RD.js +1 -0
  50. package/dist/engine-5DHYHDAP.js +1 -0
  51. package/dist/{evolution-audit-JZ2U7J4C.js → evolution-audit-OQDGPKYI.js} +1 -1
  52. package/dist/{external-api-7XV2PXPC.js → external-api-V74YTLBY.js} +1 -1
  53. package/dist/index.js +24 -15
  54. package/dist/learner-QCD6BH2J.js +1 -0
  55. package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
  56. package/dist/{memories-EKREXLT6.js → memories-QGMRSBJJ.js} +1 -1
  57. package/dist/{memory-extractor-JO7OHBZP.js → memory-extractor-3MRK43A2.js} +2 -2
  58. package/dist/memory-service-M5ADGITG.js +1 -0
  59. package/dist/outbound-gateway-QRL36F7K.js +1 -0
  60. package/dist/role-presets-DLO3XS54.js +1 -0
  61. package/dist/role-workspace-URSOBCDH.js +1 -0
  62. package/dist/roles-KYXNMO5H.js +1 -0
  63. package/dist/session-manager-LZ77OT7A.js +1 -0
  64. package/dist/task-templates-YPNWJOVV.js +1 -0
  65. package/dist/workflow-executor-3WMS2WV3.js +1 -0
  66. package/package.json +1 -1
  67. package/web/dist/assets/{AlertDialog-r3y6IhpW.js → AlertDialog-CfeiyMrc.js} +1 -1
  68. package/web/dist/assets/{Button-BjXgrQ95.js → Button-DuQctNms.js} +1 -1
  69. package/web/dist/assets/{Card-C153tGfJ.js → Card-rKfViPS2.js} +1 -1
  70. package/web/dist/assets/{ChannelDetail-C2uAZv1u.js → ChannelDetail-DHT8fW0C.js} +1 -1
  71. package/web/dist/assets/{Channels-C62Qrg-n.js → Channels-YHGNXcRu.js} +2 -2
  72. package/web/dist/assets/{Chat-kH2owmB_.js → Chat-Dv_Izjx3.js} +1 -1
  73. package/web/dist/assets/{Dashboard-BhD8SpFb.js → Dashboard-DsHC5W4C.js} +1 -1
  74. package/web/dist/assets/{EmptyState-CXwJFCDQ.js → EmptyState-CIdIlMbn.js} +1 -1
  75. package/web/dist/assets/{EnvVarEditor-GSapLD96.js → EnvVarEditor-Dxy1Kz1Z.js} +1 -1
  76. package/web/dist/assets/EventDefDetail-CwprP2ch.js +1 -0
  77. package/web/dist/assets/Events-B19a8cEG.js +1 -0
  78. package/web/dist/assets/{Evolution-BO5hysLD.js → Evolution-DT6iZvil.js} +1 -1
  79. package/web/dist/assets/{GoalDetail-cxa8OvEi.js → GoalDetail-BALsnPQl.js} +1 -1
  80. package/web/dist/assets/{Goals-Dz3qqp_l.js → Goals-BJIsKgfH.js} +1 -1
  81. package/web/dist/assets/{Logs-Ckp3-hYV.js → Logs-Cv15aV3l.js} +1 -1
  82. package/web/dist/assets/{Memories-DEuSRoP3.js → Memories-CKAXhAso.js} +1 -1
  83. package/web/dist/assets/{NotFound-Bvn39vSk.js → NotFound-DitXhq_y.js} +1 -1
  84. package/web/dist/assets/{PageHeader-BMvN0xiB.js → PageHeader-CHSgtxPw.js} +1 -1
  85. package/web/dist/assets/Plugins-NO0S2spH.js +1 -0
  86. package/web/dist/assets/{RoleDetail-BWMjP9aZ.js → RoleDetail-1FNyCD4u.js} +2 -2
  87. package/web/dist/assets/{Roles-DD7NBDku.js → Roles-grfjw2zy.js} +1 -1
  88. package/web/dist/assets/{SectionHeader-CiCj3Is0.js → SectionHeader-C2WpiwJ5.js} +1 -1
  89. package/web/dist/assets/{Settings-BlU19KuR.js → Settings-9LRLfa_4.js} +1 -1
  90. package/web/dist/assets/{Strategies-CJ_q94-v.js → Strategies-BMyd_7_5.js} +1 -1
  91. package/web/dist/assets/{Switch-CoUUy5jr.js → Switch-CULsD-kC.js} +1 -1
  92. package/web/dist/assets/{Table-CaFJieh_.js → Table-DuOLbyJQ.js} +1 -1
  93. package/web/dist/assets/{TaskDetail-DVrjU-E6.js → TaskDetail-C2yXy8gE.js} +2 -2
  94. package/web/dist/assets/Work-dftf35Me.js +1 -0
  95. package/web/dist/assets/index-D4IubNPI.css +2 -0
  96. package/web/dist/assets/index-qYKJGoIB.js +2 -0
  97. package/web/dist/assets/{useIsMobileLayout-Bwrm84kJ.js → useIsMobileLayout-C6KIQjuh.js} +1 -1
  98. package/web/dist/assets/{vendor-icons-BlMaTTx3.js → vendor-icons-Dk0hMuJz.js} +1 -1
  99. package/web/dist/assets/{vendor-react-7e01TWy7.js → vendor-react-C6faO6LO.js} +1 -1
  100. package/web/dist/assets/{vendor-state-Bj70wnRm.js → vendor-state-DahK0J-G.js} +1 -1
  101. package/web/dist/index.html +7 -7
  102. package/dist/App-JGH6G5US.js +0 -13
  103. package/dist/adam-tools-KTLBI4PA.js +0 -1
  104. package/dist/approval-handler-JZSXM4AD.js +0 -1
  105. package/dist/audit-manager-BPJEAX22.js +0 -1
  106. package/dist/bree-engine-CRK73AI4.js +0 -1
  107. package/dist/channels-WMTZJAO4.js +0 -1
  108. package/dist/chunk-DBI36EGR.js +0 -83
  109. package/dist/chunk-DMZM7RU6.js +0 -19
  110. package/dist/chunk-HQ66TFYI.js +0 -12
  111. package/dist/chunk-I67UMGJM.js +0 -10
  112. package/dist/chunk-NOUSHXGX.js +0 -6
  113. package/dist/chunk-T7GEINGZ.js +0 -6
  114. package/dist/chunk-WRETNOC3.js +0 -99
  115. package/dist/chunk-ZRUVORAJ.js +0 -49
  116. package/dist/config-XMQS2NPT.js +0 -1
  117. package/dist/db-XQUI4IBL.js +0 -1
  118. package/dist/delivery-log-T56ZYDWO.js +0 -1
  119. package/dist/engine-7DFJOADQ.js +0 -1
  120. package/dist/learner-4EO7ZKK4.js +0 -1
  121. package/dist/memory-service-Y3HVQYHM.js +0 -1
  122. package/dist/outbound-gateway-U5LP54JG.js +0 -1
  123. package/dist/role-presets-HWZHXBBA.js +0 -1
  124. package/dist/roles-3AEHVOEW.js +0 -1
  125. package/dist/session-manager-PWJLU6KZ.js +0 -1
  126. package/dist/task-templates-ED2UCUPE.js +0 -1
  127. package/dist/workflow-executor-XFTTJQNE.js +0 -1
  128. package/web/dist/assets/Plugins-CRym22JF.js +0 -1
  129. package/web/dist/assets/Work-BMl61RRi.js +0 -1
  130. package/web/dist/assets/index-DcXMQByM.css +0 -2
  131. package/web/dist/assets/index-pF--tN9F.js +0 -2
@@ -1,12 +0,0 @@
1
- import{e as Q,j as Ae}from"./chunk-24GTCFEV.js";import{a as re}from"./chunk-NZEDILAK.js";import{a as Z}from"./chunk-2CMR5AG7.js";import{a as ee,b as $,c as te,j as ne}from"./chunk-7BSWC62F.js";import{c as X,d as Y,g as L,h as z}from"./chunk-J3NIPZ73.js";import{b as T,d as _e}from"./chunk-4VHBKJD5.js";import{c as V,h as Re}from"./chunk-INNDBLZE.js";import{c as xe,e as ke}from"./chunk-FCV2DPZQ.js";var Oe={};ke(Oe,{getGlobalEnabledState:()=>J,getInstalledPlugin:()=>De,getPluginManifest:()=>F,listInstalledPlugins:()=>B,listMarketplaceSources:()=>Ie,resolvePluginPaths:()=>K,scanDirectoryConfig:()=>U});import{existsSync as b,readFileSync as x,readdirSync as oe}from"fs";import{join as m}from"path";import se from"os";function S(t){try{if(!b(t))return null;let e=x(t,"utf-8");return JSON.parse(e)}catch{return null}}function J(){return S(Me())?.enabledPlugins??{}}function F(t){let e=t;function r(n,o){let s={};try{if(!b(n))return s;let a=x(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let f of o){let l=new RegExp(`^${f}:\\s*(.+)$`,"m"),d=a.match(l);d&&(s[f]=d[1].trim())}}catch{}return s}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=m(e,".claude-plugin","plugin.json");if(b(o))try{let l=JSON.parse(x(o,"utf-8"));n.name=l.name??"",n.version=l.version,n.description=l.description,Array.isArray(l.lspServers)&&(n.lspServers=l.lspServers),Array.isArray(l.mcpServers)&&(n.mcpServers=l.mcpServers),Array.isArray(l.hooks)&&(n.hooks=l.hooks)}catch{}let s=m(e,"skills");if(b(s)){let l=oe(s,{withFileTypes:!0});for(let d of l){if(!d.isDirectory()&&!d.isSymbolicLink())continue;let p=m(s,d.name,"SKILL.md"),c=r(p,["name","description"]);c.name&&n.skills.push({name:c.name,description:c.description??""})}}let i=m(e,"agents");if(b(i)){let l=oe(i,{withFileTypes:!0});for(let d of l){if(!d.isFile()||!d.name.endsWith(".md"))continue;let p=r(m(i,d.name),["name","description"]);p.name&&n.agents.push({name:p.name,description:p.description??""})}}let a=m(e,".mcp.json");if(b(a))try{let l=JSON.parse(x(a,"utf-8"));l.mcpServers&&typeof l.mcpServers=="object"&&(n.mcpServers=Object.keys(l.mcpServers))}catch{}let f=m(e,"hooks","hooks.json");if(b(f))try{let l=JSON.parse(x(f,"utf-8"));Array.isArray(l)&&(n.hooks=l.map(d=>typeof d=="object"&&d!==null&&"event"in d?String(d.event):String(d)))}catch{}return n}catch{return null}}function B(t){let e=S(N());if(!e?.plugins)return[];let r=J(),n=[];for(let[o,s]of Object.entries(e.plugins))if(!(!Array.isArray(s)||s.length===0))for(let i of s){let a=i.scope??"user";t?.scope&&a!==t.scope||t?.projectPath&&i.projectPath!==t.projectPath||n.push({id:o,name:o.split("@")[0],version:i.version??"",scope:a,projectPath:i.projectPath,installPath:i.installPath??m(k(),o),enabled:r[o]??i.enabled??!0,installedAt:i.installedAt??"",lastUpdated:i.lastUpdated??""})}return n}function De(t){let e=S(N());if(!e?.plugins?.[t])return null;let r=e.plugins[t];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=J();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??m(k(),t),enabled:o[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function K(t){let e=S(N()),r=new Map;for(let n of t){let o=e?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??m(k(),n))}return r}function Ie(){return S(Ee())?.marketplaces??[]}function U(t){let e=m(t,".claude","settings.json"),r=S(e);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var k,N,Ee,Me,ie=xe(()=>{"use strict";k=()=>m(se.homedir(),".claude","plugins"),N=()=>m(k(),"installed_plugins.json"),Ee=()=>m(k(),"known_marketplaces.json"),Me=()=>m(se.homedir(),".claude","settings.json")});import{tool as P}from"@anthropic-ai/claude-agent-sdk";import{z as u}from"zod";import{v4 as je}from"uuid";function y(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Ce={query:u.string().describe("Search query for memory retrieval"),roleId:u.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:u.number().optional().describe("Max results to return (default 5)")},Te={query:u.string().describe("Search query for memory retrieval"),topK:u.number().optional().describe("Max results to return (default 5)")},Le={id:u.string().optional().describe("Memory ID to update. Omit to create new."),roleId:u.string().describe("Role ID to save memory under"),content:u.string().describe("Memory content text"),type:u.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:u.array(u.string()).optional().describe("Keywords for BM25 search"),importance:u.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:u.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},$e={id:u.string().optional().describe("Memory ID to update. Omit to create new."),content:u.string().describe("Memory content text"),type:u.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:u.array(u.string()).optional().describe("Keywords for BM25 search"),importance:u.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:u.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ae={id:u.string().describe("Memory ID to delete")};async function le(t,e){let r=t??e.roleId,n=e.topK??5,o=await re(r,e.query,{topK:n});return y({results:o.map(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.score}))})}async function ce(t,e){let r=t??e.roleId;if(!r)return y({error:"roleId is required"});let n,o=!0;try{n=await Z(e.content)}catch{o=!1}if(e.id){if(!$(e.id))return y({error:`Memory ${e.id} not found`});let f=te(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return y({id:e.id,action:"updated",success:f,embeddingUpdated:o})}let s=`mem-${je().slice(0,8)}`,i=Date.now();return ee({id:s,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:i,lastAccessed:i,retrievedCount:0,tier:e.tier??"episodic"}),y({id:s,action:"created",success:!0,embeddingUpdated:o})}async function de(t,e){if(t){let r=$(e.id);if(!r)return y({error:`Memory ${e.id} not found`});if(r.roleId!==t)return y({error:`Memory ${e.id} does not belong to this role`})}return ne(e.id),y({id:e.id,deleted:!0})}function bt(t){return t?[P("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Te,async e=>le(t,e)),P("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",$e,async e=>ce(t,e)),P("delete_memory","Delete a memory by ID.",ae,async e=>de(t,e))]:[P("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Ce,async e=>le(void 0,e)),P("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",Le,async e=>ce(void 0,e)),P("delete_memory","Delete a memory by ID.",ae,async e=>de(void 0,e))]}ie();Ae();z();var Ne={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function xt(t,e){let r=t.allowedTools??[],n=t.osCapabilities??[];if(r.length===0&&n.length===0&&Object.keys(t.mcpServers??{}).length===0&&(t.additionalDirectories?.length??0)===0&&(!e||e.plugins.length===0))return"No tool permissions";let o=new Map,s=[];for(let p of r){let c=Ne[p];if(c){let g=o.get(c.category)??[];g.push(c.label),o.set(c.category,g)}else s.push(p)}let i=[];for(let[p,c]of o)i.push(`${p} (${c.join(", ")})`);s.length>0&&i.push(s.join(", "));let a=i.join(" \xB7 "),f=p=>{a=a?`${a} \xB7 ${p}`:p},l=Object.keys(t.mcpServers??{});l.length>0&&f(`MCP: ${l.join(", ")}`);let d=t.additionalDirectories??[];if(d.length>0&&f(`Dirs: ${d.map(p=>p.path).join(", ")}`),n.length>0){let p=n.map(c=>{let g=Y(c.id);return c.id==="automation"&&c.targets?.length?`${g.label} (${c.targets.join(", ")})`:g.label});f(`OS: ${p.join(", ")}`)}if(e&&e.plugins.length>0){let p=e.plugins.map(c=>{let g=[];return c.skills.length>0&&g.push(`skills: ${c.skills.map(w=>w.name).join(", ")}`),c.agents.length>0&&g.push(`agents: ${c.agents.map(w=>w.name).join(", ")}`),g.length>0?`${c.name} (${g.join("; ")})`:c.name});f(`Plugins: ${p.join(", ")}`)}return a}function Je(t){let e=[],r=t.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=U(n.path),s=Object.entries(o.enabledPlugins).filter(([,a])=>a).map(([a])=>a),i=K(s);for(let[,a]of i)e.includes(a)||e.push(a)}try{let n=Q(t.name),o=B({scope:"project",projectPath:n});for(let s of o)s.installPath&&!e.includes(s.installPath)&&e.push(s.installPath)}catch{}return e}function kt(t){let e=Je(t),r=[];for(let n of e){let o=F(n);o&&r.push({name:o.name||n.split("/").pop()||"unknown",description:o.description,skills:o.skills,agents:o.agents,mcpServers:o.mcpServers,hooks:o.hooks})}return{plugins:r}}import{accessSync as ue,constants as me}from"fs";import{accessSync as Fe,constants as Be,existsSync as pe,realpathSync as Ke}from"fs";import{join as G}from"path";import{spawn as Ue}from"child_process";import{execFileSync as Ge}from"child_process";var R=null;function _(){if(R)return R;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=G(t,"landlock-exec","landlock-exec");if(pe(e))return R=e,e;let r=process.env.PATH?.split(":").find(n=>pe(G(n,"landlock-exec")));return r?(R=G(r,"landlock-exec"),R):e}var A=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{Fe(_(),Be.X_OK)}catch{return!1}try{return Ge(_(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],o=[];for(let s of e.visiblePaths??[]){let i=s.mode==="rw"?"--rw":"--ro",a;try{a=Ke(s.path)}catch{a=s.path}o.push(i,a),a!==s.path&&o.push(i,s.path)}return o.push("--",r,...n),Ue(_(),o,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function fe(){if(process.platform==="linux")try{return ue(_(),me.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return ue("/usr/bin/sandbox-exec",me.X_OK),"sandbox-exec"}catch{return"none"}return"none"}Re();import{spawn as Ye}from"child_process";import{readFileSync as be,writeFileSync as ze,mkdtempSync as Qe,realpathSync as H,rmSync as Ze}from"fs";import{join as h}from"path";import{tmpdir as et}from"os";z();var He=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],We=["com.apple.coreservices.appleevents"];function qe(t){if(!X.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function ge(t,e){return L(t)?.find(r=>r.id===e)}function Ve(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...We.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)qe(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
2
- `)}function Xe(t){return t?["","; ===== Role OS capability: Accessibility =====","(allow signal)","(allow mach-priv-host-port)","(allow mach-task-name)",'(allow mach-lookup (local-name "com.apple.axserver"))',"(allow user-preference-read",...He.map(r=>` (preference-domain "${r}")`),")"].join(`
3
- `):""}function ye(t){let e=L(t);return e?.length?[Ve(ge(e,"automation")),Xe(ge(e,"accessibility"))].filter(Boolean).join(`
4
- `):""}var Se=V("sandbox-macos"),he="/usr/bin/sandbox-exec";function tt(){let t=[h(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),h(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),h(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return be(e,"utf-8"),e}catch{}return t[t.length-1]}var nt=tt();function E(t){if(!t.startsWith("/"))throw new Error(`Sandbox path must be absolute: ${t}`);if(t.includes('"')||t.includes(")")||t.includes("(")||t.includes("$"))throw new Error(`Sandbox path contains invalid characters for SBPL: ${t}`)}function rt(t){let e=[`
5
- ; ===== Per-Role writable paths =====`];for(let r of t){if(r.mode!=="rw")continue;let n;try{n=H(r.path)}catch{n=r.path}E(n),e.push(`(allow file-write* (subpath "${n}"))`),n!==r.path&&(E(r.path),e.push(`(allow file-write* (subpath "${r.path}"))`))}return e.join(`
6
- `)}function ot(t){if(!t.length)return"";let e=[`
7
- ; ===== Global read blacklist (deniedReadPaths) =====`];for(let r of t){let n;try{n=H(r)}catch{n=r}try{E(n),e.push(`(deny file-read-data (subpath "${n}"))`),e.push(`(deny file-read-metadata (subpath "${n}"))`),n!==r&&(E(r),e.push(`(deny file-read-data (subpath "${r}"))`),e.push(`(deny file-read-metadata (subpath "${r}"))`))}catch(o){Se.warn({path:r,error:o.message},"Skipping deniedReadPath: invalid for SBPL")}}return e.join(`
8
- `)}var M=class{platform="sandbox-exec";async isAvailable(){try{let{existsSync:e}=await import("fs");return e(he)}catch{return!1}}spawn(e){let{command:r,args:n,cwd:o,env:s,signal:i,visiblePaths:a,deniedReadPaths:f,osCapabilities:l}=e,d=be(nt,"utf-8"),p=rt(a),c=ot(f??[]),g=ye(l),w=d+p+c+g+`
9
- `,I=H(Qe(h(et(),"adam-sandbox-"))),O=h(I,"role.sb");ze(O,w,"utf-8");let j=I,C=s?.HOME??process.env.HOME??"/tmp",we={...s,TMPDIR:j,CLAUDE_CODE_TMPDIR:j,CLAUDE_CONFIG_DIR:h(C,".claude")};Se.debug({command:r,visiblePaths:a.length,profilePath:O},"Spawning sandboxed process");let q=Ye(he,["-f",O,"-D",`TMPDIR=${j}`,"-D",`CLAUDE_CONFIG=${h(C,".claude")}`,"-D",`HOME_CACHE=${h(C,"Library","Caches")}`,r,...n],{cwd:o,env:we,stdio:"pipe",signal:i});return q.on("exit",()=>{try{Ze(I,{recursive:!0,force:!0})}catch{}}),q}};import{spawn as st}from"child_process";var v=null,Pe=null,D=null;function it(){if(v)return v;let t=Pe??fe();return Pe=t,t==="sandbox-exec"?v=new M:t==="landlock"?v=new A:v=new W(t),v}async function qt(){return D!==null||(D=await it().isAvailable()),D}var W=class{platform;constructor(e){this.platform=e}async isAvailable(){return!1}spawn(e){let r=e.command??"node",n=e.args??[];return st(r,n,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};_e();function at(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var ve={low:1,medium:2,high:3};function Yt(t){T().prepare(`
10
- INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
11
- VALUES (?, ?, ?, ?, ?, ?)
12
- `).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function zt(t,e,r){let o=T().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==t)&&!(ve[r]>ve[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(e))return at(s)}catch{}}export{Yt as a,zt as b,J as c,F as d,B as e,De as f,Ie as g,U as h,Oe as i,ie as j,bt as k,xt as l,Je as m,kt as n,it as o,qt as p};
@@ -1,10 +0,0 @@
1
- import{a as D}from"./chunk-YHVFZB6Q.js";import{a as x,b as y}from"./chunk-XAMLLKKA.js";import{b as _}from"./chunk-CKIVKM5T.js";import{b}from"./chunk-KO5AFX5U.js";import{a as g}from"./chunk-L7JP7DUO.js";import{d as v}from"./chunk-7K4AQBDD.js";import{k as C,q as z}from"./chunk-J3NIPZ73.js";import{b as h,d as $}from"./chunk-4VHBKJD5.js";import{c as E,h as A}from"./chunk-INNDBLZE.js";A();z();$();function M(u){return{id:u.id,templateId:u.template_id,status:u.status,stepStatuses:JSON.parse(u.step_statuses),startedAt:u.started_at,completedAt:u.completed_at??void 0,error:u.error??void 0}}function P(u,e){h().prepare(`
2
- INSERT INTO workflow_executions (id, template_id, status, step_statuses, started_at)
3
- VALUES (?, ?, 'running', '{}', ?)
4
- `).run(u,e,Date.now())}function I(u){let t=h().prepare("SELECT * FROM workflow_executions WHERE id = ?").get(u);return t?M(t):void 0}function R(u,e){let t=h(),s=[],r=[];e.status!==void 0&&(s.push("status = ?"),r.push(e.status)),e.stepStatuses!==void 0&&(s.push("step_statuses = ?"),r.push(JSON.stringify(e.stepStatuses))),e.completedAt!==void 0&&(s.push("completed_at = ?"),r.push(e.completedAt)),e.error!==void 0&&(s.push("error = ?"),r.push(e.error)),s.length!==0&&(r.push(u),t.prepare(`UPDATE workflow_executions SET ${s.join(", ")} WHERE id = ?`).run(...r))}function F(u,e=50,t=0){let s=h(),r="SELECT * FROM workflow_executions",o=[];return u&&(r+=" WHERE template_id = ?",o.push(u)),r+=" ORDER BY started_at DESC LIMIT ? OFFSET ?",o.push(e,t),s.prepare(r).all(...o).map(M)}import{v4 as N}from"uuid";var m=E("scheduler"),O=class{maxRetries;baseDelayMs;constructor(e){this.maxRetries=e?.maxRetries??3,this.baseDelayMs=e?.baseDelayMs??1e3}async execute(e,t){let s=v(),r={timeout:e.config?.timeout??s.timeout,approvalRequired:s.approvalRequired,approvalTimeout:s.approvalTimeout,plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??s.model,maxTurns:e.config?.maxTurns??s.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??s.maxBudgetUsd,env:{...s.env,...e.config?.env},claudeCodePath:s.claudeCodePath},o={templateId:e.id,executionId:t,stepResults:new Map,stepStatuses:{},config:r,continueOnError:e.config?.continueOnError??!1,failedStepIds:new Set,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo};P(t,e.id),D(t),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:"running"});let i=this.groupIntoLayers(e.steps);for(let f of i){if(this.syncExternalState(o)==="cancelled")return this.finalizeCancelledWorkflow(e,o);let k=f.filter(d=>!this.shouldSkip(d,o)),W=f.filter(d=>this.shouldSkip(d,o));for(let d of W){let p={stepId:d.id,taskId:"",status:"skipped",error:"Skipped: dependency failed"};o.stepResults.set(d.id,p),o.stepStatuses[d.id]={taskId:"",status:"skipped",error:"Skipped: dependency failed"},m.info({stepId:d.id,executionId:t},"Step skipped due to failed dependency")}if(k.length===0)continue;let T=await Promise.allSettled(k.map(d=>this.executeStep(d,o)));if(this.syncExternalState(o)==="cancelled")return this.finalizeCancelledWorkflow(e,o);for(let d=0;d<k.length;d++){let p=k[d],c=T[d];if(c.status==="rejected"){m.error({stepId:p.id,error:c.reason},"Workflow step threw");let S={stepId:p.id,taskId:"",status:"failed",error:String(c.reason)};o.stepResults.set(p.id,S),o.failedStepIds.add(p.id),o.stepStatuses[p.id]={taskId:"",status:"failed",error:String(c.reason)}}let w=o.stepResults.get(p.id);if(w?.status==="failed"&&(o.failedStepIds.add(p.id),!o.continueOnError)){if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);let S="failed";return R(t,{status:S,stepStatuses:o.stepStatuses,completedAt:Date.now(),error:w.error}),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:S}),m.warn({stepId:p.id,executionId:t},"Workflow step failed, workflow aborted"),{executionId:t,status:S,stepResults:o.stepResults}}}if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);R(t,{stepStatuses:o.stepStatuses})}if(this.isWorkflowCancelled(o.executionId))return this.finalizeCancelledWorkflow(e,o);let a=o.failedStepIds.size>0,l=[...o.stepResults.values()].some(f=>f.status==="skipped"||f.status==="cancelled"),n=a||l?"partial":"completed";return R(t,{status:n,stepStatuses:o.stepStatuses,completedAt:Date.now()}),g.emit({type:"workflow_status_change",executionId:t,templateId:e.id,status:n}),m.info({executionId:t,status:n,completedSteps:o.stepResults.size,totalSteps:e.steps.length,failedSteps:o.failedStepIds.size},"Workflow completed"),await this.deliverWorkflowResult(o,n),{executionId:t,status:n,stepResults:o.stepResults}}groupIntoLayers(e){let t=new Map(e.map(a=>[a.id,a])),s=new Map,r=new Map;for(let a of e)s.set(a.id,0),r.set(a.id,[]);for(let a of e)if(a.dependsOn)for(let l of a.dependsOn)t.has(l)&&(s.set(a.id,(s.get(a.id)??0)+1),r.get(l)?.push(a.id));let o=[],i=new Set(e.map(a=>a.id));for(;i.size>0;){let a=[];for(let l of i)if((s.get(l)??0)===0){let n=t.get(l);n&&a.push(n)}if(a.length===0){m.warn({remaining:[...i]},"Cycle detected in step dependencies");for(let l of i){let n=t.get(l);n&&o.push([n])}break}o.push(a);for(let l of a){i.delete(l.id);for(let n of r.get(l.id)??[])s.set(n,(s.get(n)??0)-1)}}return o}syncExternalState(e){let t=I(e.executionId);if(t){for(let[s,r]of Object.entries(t.stepStatuses))(r.status==="skipped"||r.status==="failed"||r.status==="cancelled")&&!e.stepResults.has(s)&&!e.failedStepIds.has(s)&&(r.status==="skipped"?e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"skipped",error:r.error??"Manually skipped via API"}):r.status==="cancelled"?e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"cancelled",error:r.error??"Cancelled"}):(e.failedStepIds.add(s),e.stepResults.set(s,{stepId:s,taskId:r.taskId,status:"failed",error:r.error})),e.stepStatuses[s]=r,m.info({stepId:s,status:r.status,executionId:e.executionId},"Synced external step status from DB"));return t.status==="cancelled"?"cancelled":void 0}}shouldSkip(e,t){return e.dependsOn?e.dependsOn.some(s=>t.failedStepIds.has(s)?!0:t.stepResults.get(s)?.status==="skipped"):!1}async executeStep(e,t){let s=this.resolveVariables(e.prompt,t.stepResults),r=e.roleId??t.rolePreference,o=r?C(r):void 0,i={...t.config,...e.config?.timeout!==void 0?{timeout:e.config.timeout}:{},...e.config?.maxTurns!==void 0?{maxTurns:e.config.maxTurns}:{}},a=(i.timeout??600)*1e3,l="",n="failed";for(let p=1;p<=this.maxRetries;p++){let c=N();if(l=c,x({id:c,status:"pending",prompt:s,config:i,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId,roleId:r,stepId:e.id}),t.stepStatuses[e.id]={taskId:c,status:"running",roleId:r},m.debug({stepId:e.id,taskId:c,roleId:r,attempt:p},"Created workflow step as task"),g.emit({type:"task_created",taskId:c}),n=await this.waitForTaskCompletion(c,a),n==="completed"||n==="cancelled")break;if(p<this.maxRetries){let w=this.baseDelayMs*Math.pow(2,p-1);m.info({stepId:e.id,attempt:p,maxRetries:this.maxRetries,delayMs:w},"Workflow step failed, retrying with new task"),await this.sleep(w)}}let f=y(l),k=I(t.executionId),W=k?.stepStatuses[e.id],T=n==="completed"?"completed":W?.status==="skipped"?"skipped":W?.status==="cancelled"||k?.status==="cancelled"?"cancelled":"failed",d={stepId:e.id,taskId:l,status:T,roleId:r,roleName:o?.name,result:f?.result,error:f?.error};t.stepResults.set(e.id,d),t.stepStatuses[e.id]={taskId:l,status:d.status,roleId:r,result:f?.result,error:f?.error}}async deliverWorkflowResult(e,t){let s=_();if(e.deliverTo&&e.deliverTo.length>0){let r=this.assembleWorkflowSummary(e);for(let o of e.deliverTo)if(o.type==="channel"){let i=b(o.channelId);try{await s.send({taskId:e.executionId,channelId:o.channelId,chatId:o.chatId,platform:i?.platform,content:r,messageType:"deliver"})}catch(a){m.error({executionId:e.executionId,channelId:o.channelId,error:a},"Workflow delivery failed")}}}if(e.reportTo&&e.reportTo.length>0){let r=[...e.stepResults.values()].filter(n=>n.status==="completed").length,o=e.failedStepIds.size,i=[...e.stepResults.values()].filter(n=>n.status==="skipped").length,a=e.stepResults.size,l=`Workflow ${t}: ${r}/${a} steps completed${o>0?`, ${o} failed`:""}${i>0?`, ${i} skipped`:""}`;for(let n of e.reportTo)if(n.type==="channel"){let f=b(n.channelId);try{await s.send({taskId:e.executionId,channelId:n.channelId,chatId:n.chatId,platform:f?.platform,content:l,messageType:"report"})}catch(k){m.error({executionId:e.executionId,channelId:n.channelId,error:k},"Workflow report delivery failed")}}}}assembleWorkflowSummary(e){let t=[];for(let[s,r]of e.stepResults){let o=r.status==="completed"?"OK":r.status==="skipped"?"SKIP":"FAIL",i=r.roleName?` (${r.roleName})`:"",a=r.result??r.error??"No output";t.push(`## [${o}] Step: ${s}${i}
5
-
6
- ${a}`)}return t.join(`
7
-
8
- ---
9
-
10
- `)}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(s,r)=>t.get(r)?.result??`[no result from ${r}]`)}waitForTaskCompletion(e,t=6e5){return new Promise(s=>{let r=!1,o=Date.now(),i=()=>{r=!0,g.off("task_status_change",a)},a=n=>{r||n.taskId!==e||(n.newStatus==="completed"?(i(),s("completed")):n.newStatus==="failed"?(i(),s("failed")):n.newStatus==="cancelled"&&(i(),s("cancelled")))};g.on("task_status_change",a);let l=()=>{if(r)return;if(Date.now()-o>t){i(),s("failed");return}let n=y(e);if(!n){i(),s("failed");return}if(n.status==="completed"){i(),s("completed");return}if(n.status==="failed"){i(),s("failed");return}if(n.status==="cancelled"){i(),s("cancelled");return}setTimeout(l,5e3)};setTimeout(l,100)})}sleep(e){return new Promise(t=>setTimeout(t,e))}isWorkflowCancelled(e){return I(e)?.status==="cancelled"}finalizeCancelledWorkflow(e,t){let s=I(t.executionId);return R(t.executionId,{status:"cancelled",stepStatuses:s?.stepStatuses??t.stepStatuses,completedAt:s?.completedAt??Date.now(),error:s?.error}),m.info({executionId:t.executionId,templateId:e.id},"Workflow cancelled"),{executionId:t.executionId,status:"cancelled",stepResults:t.stepResults}}};export{I as a,R as b,F as c,O as d};
@@ -1,6 +0,0 @@
1
- import{b as i,d as l}from"./chunk-4VHBKJD5.js";l();function o(e){return{id:e.id,name:e.name,description:e.description??void 0,roleId:e.role,metricType:e.metric_type,targetValue:e.target_value,currentValue:e.current_value,deadline:e.deadline,budgetUsd:e.budget_usd,status:e.status,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}}function c(e){i().prepare(`
2
- INSERT INTO goals (id, name, description, role, metric_type, target_value,
3
- current_value, deadline, budget_usd, status, created_at, updated_at,
4
- source_session_id, deliver_to, report_to)
5
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6
- `).run(e.id,e.name,e.description??null,e.roleId,e.metricType,e.targetValue,e.currentValue,e.deadline,e.budgetUsd,e.status,e.createdAt,e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null)}function _(e){let s=i().prepare("SELECT * FROM goals WHERE id = ?").get(e);return s?o(s):void 0}function g(e,t){let s=i(),n=[],r=[],d={name:"name",description:"description",roleId:"role",metricType:"metric_type",targetValue:"target_value",currentValue:"current_value",deadline:"deadline",budgetUsd:"budget_usd",status:"status",updatedAt:"updated_at",sourceSessionId:"source_session_id"};for(let[u,a]of Object.entries(d))u in t&&(n.push(`${a} = ?`),r.push(t[u]??null));"deliverTo"in t&&(n.push("deliver_to = ?"),r.push(JSON.stringify(t.deliverTo))),"reportTo"in t&&(n.push("report_to = ?"),r.push(JSON.stringify(t.reportTo))),n.length!==0&&(r.push(e),s.prepare(`UPDATE goals SET ${n.join(", ")} WHERE id = ?`).run(...r))}function f(e,t=100,s=0){let n=i(),r="SELECT * FROM goals",d=[];return e&&(r+=" WHERE status = ?",d.push(e)),r+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(t,s),n.prepare(r).all(...d).map(o)}function m(e){i().prepare("DELETE FROM goals WHERE id = ?").run(e)}export{c as a,_ as b,g as c,f as d,m as e};
@@ -1,6 +0,0 @@
1
- import{b as s,d as l}from"./chunk-4VHBKJD5.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};
@@ -1,99 +0,0 @@
1
- import{b as Fe,k as Xe,m as Ze,o as L,p as Qe}from"./chunk-HQ66TFYI.js";import{a as ue,d as je,e as pe}from"./chunk-YHH3QMLL.js";import{a as Oe,b as Le}from"./chunk-6THDALGC.js";import{b as me,c as qe,d as Je,e as Ye,f as Ge}from"./chunk-YHVFZB6Q.js";import{b as q,c as z,d as J,f as Be}from"./chunk-XAMLLKKA.js";import{a as $,e as et}from"./chunk-HYDCXE5K.js";import{a as ze}from"./chunk-DMZM7RU6.js";import{e as G,f as Ue,j as We}from"./chunk-24GTCFEV.js";import{b as Ve}from"./chunk-EZGMA3VV.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as He}from"./chunk-NZEDILAK.js";import{b as Ke}from"./chunk-T33BLZV2.js";import{d as W,i as Me}from"./chunk-GSMC3VUM.js";import{a as Y,b as $e,k as R,m as B,n as le,q as O}from"./chunk-J3NIPZ73.js";import{a as Ne,g as jt}from"./chunk-QQWRV23T.js";import{b,d as H}from"./chunk-4VHBKJD5.js";import{d as ce,h as Vt}from"./chunk-WBAPIPST.js";import{c as w,h as P}from"./chunk-INNDBLZE.js";H();function Ft(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 tt(e){b().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 b().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(Ft)}function ot(e){return b().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(e)?.ema_score}function rt(e){let r=b().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 s=r.map(i=>{let n=JSON.parse(i.token_usage);return(n.input??0)+(n.output??0)}).sort((i,n)=>i-n);return s[Math.floor(s.length/2)]}P();import{v4 as Kt}from"uuid";var Ht=w("audit"),Z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},nt=.3;function qt(e,t){let r=q(e),s=r?.status==="completed"?1:0,i=1,n=je(e);n?.deviationReport&&(i=n.deviationReport.overallAccuracy);let o=1,a=Le(e,1e3),c=a.filter(m=>m.type==="tool_result"||m.type==="permission_denied").length,d=a.filter(m=>m.type==="permission_denied").length;c>0&&(o=1-d/c);let u=1;if(r?.tokenUsage){let m=r.tokenUsage.input+r.tokenUsage.output,E=t?rt(t):1e4;m>E&&(u=Math.max(0,1-(m-E)/E))}let l=s*Z.taskSuccess+i*Z.planAccuracy+o*Z.permissionCompliance+u*Z.efficiency;return{taskSuccess:s,planAccuracy:i,permissionCompliance:o,efficiency:u,weighted:l}}function st(e,t){let r=qt(t,e),s=ot(e),i=s!==void 0?nt*r.weighted+(1-nt)*s:r.weighted;return tt({id:Kt(),roleId:e,taskId:t,scores:r,emaScore:i,createdAt:Date.now()}),Ht.debug({roleId:e,taskId:t,scores:{...r,weighted:r.weighted.toFixed(3)},ema:i.toFixed(3)},"Task score recorded"),i}O();O();P();var Jt=w("audit");function Q(e,t=7){let r=R(e),s=X(e,100),i=Date.now(),n=i-t*24*60*60*1e3,o=s.filter(g=>g.createdAt>=n),a=o.map(g=>g.emaScore),c=o.length>0?o.reduce((g,U)=>g+U.scores.weighted,0)/o.length:1,d=[],u=o.filter(g=>g.scores.taskSuccess<.5);u.length>0&&d.push({category:"task_failures",count:u.length,examples:u.slice(0,3).map(g=>g.taskId)});let l=o.filter(g=>g.scores.planAccuracy<.5);l.length>0&&d.push({category:"plan_deviations",count:l.length,examples:l.slice(0,3).map(g=>g.taskId)});let m=o.filter(g=>g.scores.permissionCompliance<.8);m.length>0&&d.push({category:"permission_violations",count:m.length,examples:m.slice(0,3).map(g=>g.taskId)});let E=o.filter(g=>g.scores.efficiency<.3);E.length>0&&d.push({category:"inefficiency",count:E.length,examples:E.slice(0,3).map(g=>g.taskId)});let N=[],C=[];return u.length>o.length*.3&&(N.push("High task failure rate"),C.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),m.length>0&&(N.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&&(N.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"})),Jt.info({roleId:e,taskCount:o.length,avgScore:c.toFixed(3),failureCategories:d.map(g=>g.category)},"Diagnostic report generated"),{roleId:e,agentName:r?.name??"Unknown",period:{start:n,end:i},taskCount:o.length,avgScore:c,scoreHistory:a,failureBehaviors:d,rootCauses:N,recommendations:C}}P();var ee=w("audit"),it=.4,Yt=5;function at(e,t,r=it){if(t>=r)return;let s=R(e);if(!s||s.status==="retired"||s.status==="dead")return;ee.warn({roleId:e,emaScore:t,threshold:r},"Agent EMA below threshold, retiring");let i=Q(e),n=JSON.stringify(s.learnedRules),o=Gt(s.learnedRules,i);B(e,{status:"retired",learnedRules:o});let a=[...i.failureBehaviors.map(d=>`${d.category}: ${d.count} occurrences`),...i.rootCauses.map(d=>`Root cause: ${d}`),...i.recommendations.map(d=>`Recommendation [${d.action}]: ${d.detail}`)].join(`
9
- `),c=et(n,JSON.stringify(o));return $({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:s.learnedRules.length,newRulesCount:o.length,recommendations:i.recommendations.length},"Agent retired with targeted learnedRules modification"),i}function dt(e){let t=R(e);return!t||t.status!=="retired"?!1:(B(e,{status:"probation"}),$({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 ct(e,t,r=it,s=Yt){let i=R(e);return!i||i.status!=="probation"||X(e,s+1).length<s?!1:t>=r?(B(e,{status:"active"}),$({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 Gt(e,t){let r=[...e];for(let s of t.recommendations){let i=`[audit:${s.action}] ${s.detail}`;r.includes(i)||r.push(i)}if(t.failureBehaviors.length>0){let i=`[audit:diagnostic] Failure patterns detected: ${t.failureBehaviors.map(n=>`${n.category}(${n.count})`).join(", ")}. Review and adjust behavior accordingly.`;r.includes(i)||r.push(i)}return r}import{spawn as Tt}from"child_process";O();import{query as uo}from"@anthropic-ai/claude-agent-sdk";import{v4 as bt}from"uuid";function lt(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.`:"",s=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
- ${s}
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 Xt,relative as Zt,resolve as Qt}from"path";$e();P();var eo=new Set(["Read","Glob","Grep","LSP"]),to=new Set(["Edit","Write","NotebookEdit"]);function fe(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function ge(e){return Qt(Y(e))}function ut(e,t){return t.some(r=>{let s=ge(r),i=Zt(s,e);return i===""||!i.startsWith("..")&&!Xt(i)})}function pt(e,t,r){return async(s,i,{agentID:n,blockedPath:o})=>{if(o){let c=ge(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=ge(d);if(ut(c,[u]))return oo.warn({toolName:s,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&&ut(c,r.roleScope)?{behavior:"allow",updatedInput:i}:t?await t(s,i,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(eo.has(s))return{behavior:"allow",updatedInput:i};if(to.has(s))return{behavior:"allow",updatedInput:i};let a=e(n??"");if(s==="Bash"&&a){let c=i.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(fe(d).test(c))return{behavior:"allow",updatedInput:i}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(fe(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(s))return{behavior:"deny",message:`Tool ${s} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=s==="Bash"?i.command??"":`${s} ${JSON.stringify(i)}`;for(let d of a.approvalRequired)try{if(fe(d).test(c))return await t(s,i,d,n)}catch{}}return{behavior:"allow",updatedInput:i}}}var oo=w("manager");function mt(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,s=e.roleId==="role-chat-manager";if(!s&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:i}=await import("./memory-service-Y3HVQYHM.js"),n=e.taskPrompt||"role context and recent interactions",o=s?["semantic","working"]:["semantic","episodic"],a=await i(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 s=e.taskPrompt||"role context",i=await He(s,r,5);if(i)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:i}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:s}=await import("./memories-EKREXLT6.js"),{getDb:i}=await import("./db-XQUI4IBL.js"),n=t.transcript;if(!n||n.length<=100)return{};if(i().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)}`;s({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,s=t.tool_input,i=t.tool_response,n=typeof i=="string"?i:JSON.stringify(i??"");try{Oe({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(s??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:s,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:s}=await import("./memories-EKREXLT6.js");s({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{}}]}]}}O();We();Vt();P();H();import{randomUUID as ro}from"crypto";function ft(e,t,r){let i=b().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;i.run(ro(),e,o,a,r??null,n)}}function Go(e){return b().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 Xo(e=50){return b().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)}O();We();import{createSdkMcpServer as so,tool as A}from"@anthropic-ai/claude-agent-sdk";import{z as v}from"zod";import{v4 as It}from"uuid";H();function gt(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 he(e){b().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 Ie(e,t,r){let i=b().prepare(`
85
- SELECT * FROM workflow_artifacts
86
- WHERE execution_id = ? AND step_id = ? AND key = ?
87
- `).get(e,t,r);return i?gt(i):void 0}function ye(e,t){let r=b(),s="SELECT * FROM workflow_artifacts WHERE execution_id = ?",i=[e];return t&&(s+=" AND step_id = ?",i.push(t)),s+=" ORDER BY created_at ASC",r.prepare(s).all(...i).map(gt)}function er(e){let t=b(),r=ye(e);return t.prepare("DELETE FROM workflow_artifacts WHERE execution_id = ?").run(e),r}function ht(e){b().prepare("DELETE FROM workflow_artifacts WHERE id = ?").run(e)}function tr(e){return b().prepare(`
88
- SELECT id
89
- FROM workflow_executions
90
- WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
91
- `).all(e).map(s=>s.id)}P();H();var no=w("audit");function I(e){try{b().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){no.error({err:t,entry:e},"Failed to write artifact access log")}}var io=/^[A-Za-z0-9._-]{1,256}$/,ao=/^[A-Za-z0-9._-]{1,128}$/,yt=256*1024,co=/^[a-z]+\/[a-z0-9.+-]+$/;async function lo(e){let{listChannels:t}=await import("./channels-PUOPR5Y2.js"),r=t(),{listSessions:s}=await import("./session-manager-PWJLU6KZ.js"),i=[...s("active"),...s("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=i.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 p(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return io.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ke(e){return ao.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function kt(e,t){let r=e?R(e):void 0,s=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=q(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}`}},i=[...Xe(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-PUOPR5Y2.js"),o=n();return p({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 p({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return p({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await lo(n.channelName);if(!o)return p({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-U5LP54JG.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return p({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 s();if("error"in o)return p({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}),p({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>yt){let l=`Artifact JSON exceeds ${yt} 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}),p({error:l})}let u=It();return he({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"}),p({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}),p({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 s();if("error"in o)return p({error:o.error});let a=ke(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}),p({error:d});let u=Ie(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}),p({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}),p({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"}),p({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 s();if("error"in o)return p({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}),p({error:a});if(n.mime&&!co.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}),p({error:l})}try{me(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let m=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:m}),p({error:m})}let c=It(),d=null,u=!1;try{let l=qe({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,he({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&&Je(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"}),p({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{ht(c)}catch{}if(d)try{Ge(d)}catch{}let m=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:m}),p({error:m})}}),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 s();if("error"in o)return p({error:o.error});let a=ke(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}),p({error:d});try{me(n.destPath,o.roleWorkspacePath,!1)}catch(l){let m=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:m}),p({error:m})}let u=Ie(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}),p({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}),p({error:l})}try{let l=Ye({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"}),p({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let m=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:m}),p({error:m})}}),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 s();if("error"in o)return p({error:o.error});let a=n.stepId?ke(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}),p({error:a});let c=ye(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"}),p({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:i})}jt();$e();import{realpathSync as po}from"fs";var _=w("execution"),wt=new Set;async function mo(e,t){if(t&&wt.has(t))return _.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=bt(),s={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 ue({id:r,taskId:e,plan:s,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:s}),_.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(i=>{let o=setTimeout(()=>{c(),pe(r,"denied"),_.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),i(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(_.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&wt.add(t),i(!0)):(_.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),i(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let s=Date.now(),i,n,o;z(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),_.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.roleId?R(t.roleId):void 0,c=ce;a&&(Ue(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=lt(d),l=mt({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),m=t.config.approvalTimeout??300,E=async(f,h,k,D)=>{let x=bt(),Pe=Fe(D??t.roleId,t.prompt,"medium");if(Pe)return _.info({operationId:x,ruleId:Pe.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ce={steps:[{index:0,description:`${f}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[f],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return ue({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ce,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ce}),_.info({taskId:t.id,operationId:x,toolName:f,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(de=>{let Wt=setTimeout(()=>{De(),pe(x,"denied"),_.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),de({behavior:"deny",message:`Operation timed out after ${m}s. Auto-denied. Try a safer alternative that does not require approval.`})},m*1e3),Ae=M=>{if(M.planId===x)if(De(),M.decision==="allow")_.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),de({behavior:"allow",updatedInput:h});else{let zt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";_.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),de({behavior:"deny",message:zt})}},De=()=>{clearTimeout(Wt),y.off("plan_approval_decision",Ae)};y.on("plan_approval_decision",Ae)})},C=(Ne("defaults.deniedReadPaths")??[]).map(f=>{let h=Y(f);try{return po(h)}catch{return h}}),g=a?.additionalDirectories??[],U=a?Ze(a):[],Re=[...g.map(f=>f.path)].filter((f,h,k)=>k.indexOf(f)===h),At=pt(f=>({disallowedTools:a?.disallowedTools,approvalRequired:a?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:a?.allowedBashPatterns,deniedBashPatterns:a?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...Re]}),Dt=Me({roleEnvVars:a?.envVars,taskEnv:t.config.env}),Mt=t.config.maxBudgetUsd??W().defaults.maxBudgetUsd,Bt=t.config.maxTurns??100,Ot=kt(t.roleId??"",t.id),Lt=a?.mcpServers??{},$t=t.config.mcpServers??{},Nt={...Lt,...$t,"execution-tools":Ot},ie=[{path:c,mode:"rw"}];t.roleId===ze&&ie.push({path:ce,mode:"ro"});for(let f of g)ie.push({path:f.path,mode:f.mode??"rw"});let ve=L();if(ve.platform==="none"&&!await mo(t.id,a?.name))return z(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Se=a?.permissionMode??"default",Ut=uo({prompt:t.prompt,options:{cwd:c,additionalDirectories:Re,systemPrompt:u,maxTurns:Bt,maxBudgetUsd:Mt,allowedTools:a?.allowedTools,model:a?.model,mcpServers:Nt,settingSources:a?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:At,env:Dt,plugins:U.map(f=>({type:"local",path:f})),permissionMode:Se,...Se==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:f=>{let h=ve.spawn({command:f.command,args:f.args,cwd:f.cwd,env:f.env,signal:f.signal,visiblePaths:ie,deniedReadPaths:C,osCapabilities:a?.osCapabilities}),k=h;k.pid&&(_t(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>xt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(_.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:f=>{f.trim()&&_.debug({stderr:f.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),K="",Te=0,Ee=()=>{_.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Ee);try{for await(let f of Ut){let h=f;if(_.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(K=h.result),h.type==="result"){Te++,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&&(i={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&&(i={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Ee)}o=Te;let ae=Date.now()-s;return z(t.id,{status:"completed",result:K,completedAt:Date.now(),costUsd:n,tokenUsage:i,numTurns:o,totalDurationMs:ae}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:K}),U.length>0&&ft(t.id,U,t.roleId),_.info({taskId:t.id,durationMs:ae,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:K,costUsd:n,tokenUsage:i,numTurns:o,durationMs:ae}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-s;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&_.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),z(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}),_.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=w("execution-pool"),we=new Map;function _t(e,t,r){we.set(e,{roleId:t,taskId:r})}function xt(e){we.delete(e)}function be(e){return we.get(e)}var Rt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(s,i)=>({index:i,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",s=>{this.onTaskCreated(s.taskId)}),y.on("task_status_change",s=>{s.newStatus==="pending"&&this.pickupPendingTasks()});let r=W().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=W().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 i=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=i.id,t.abortController=new AbortController;let n=t.index,o=i.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(i,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let s=this.slots[r];if(!s)return;let i="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,s.abortController?.signal);i=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{s.taskId=null,s.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:i}),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(i=>i.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let s=Ke();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Be(s)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:s}=await import("./memory-extractor-JO7OHBZP.js"),i=await s(t,r);i>0&&S.debug({taskId:t,roleId:r,memoriesStored:i},"Post-completion: memories extracted")}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: memory extraction failed")}try{let{processTaskReview:s}=await import("./learner-4EO7ZKK4.js");await s(t)}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:s}=await import("./audit-manager-BPJEAX22.js");s(t,r)}catch(s){S.error({taskId:t,roleId:r,error:s},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(s=>s.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(s=>s.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=w("audit"),fo="sandbox_violation",V=new Map,_e=1440*60*1e3,ne=[],go=100;function xe(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let s=Date.now()-_e;if(r.timestamps=r.timestamps.filter(i=>i>=s),V.set(t,r),r.count%100===0)for(let[i,n]of V.entries()){let o=Date.now()-_e;n.timestamps.filter(a=>a>=o).length===0&&V.delete(i)}ne.push(e),ne.length>go&&ne.shift();try{Ve({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:fo,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(i){T.error({error:i},"Failed to record violation to delivery_log")}try{let i=R(e.roleId);$({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(i){T.error({error:i},"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 Et(){let e=L();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=ho():e.platform==="landlock"&&(r=await Io()),()=>{if(r){let s=r;r=null,s.kill("SIGTERM");let i=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}},2e3);s.on("exit",()=>clearTimeout(i))}T.info("Violation watcher stopped")}}function ho(){let e=Tt("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 s of r)try{let i=JSON.parse(s),n=i.eventMessage??i.message??"";if(n.includes("deny")&&(n.includes("file-read")||n.includes("file-write"))){let o=yo(i,n);o&&xe(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 Io(){let e=await vt("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(e)return St(e),T.info("Linux violation watcher started (journalctl -kf)"),e;let t=await vt("dmesg",["-w","-t"]);return t?(St(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 vt(e,t){return new Promise(r=>{let s=Tt(e,t,{stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>r(s),500);s.on("error",()=>{clearTimeout(i),r(null)}),s.on("exit",n=>{n!==0&&(clearTimeout(i),r(null))})})}function St(e){e.stdout?.on("data",t=>{let r=t.toString().split(`
99
- `).filter(Boolean);for(let s of r)if(s.includes("landlock")&&s.includes("denied")){let i=ko(s);i&&xe(i)}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString().trim()},"Linux watcher stderr")})}function yo(e,t){let r=t.match(/(?:path|file)=["']([^"']+)["']/),s=t.match(/deny\s+(file-read|file-write|file-[^\s]+)/),i=r?.[1],n=s?.[1]??"unknown";if(!i)return null;let o=typeof e.processID=="number"?e.processID:void 0,a=o?be(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:i,operation:n,timestamp:Date.now(),count:1}}function ko(e){let t=e.match(/path="([^"]+)"/)??e.match(/\/[\w\-\.\/\+ ]+/g),r=e.match(/deny\s+(\w+)/),s=e.match(/pid=(\d+)/),i=Array.isArray(t)?t[t.length-1]:t?.[1],n=r?.[1]??"unknown";if(!i)return null;let o=s?parseInt(s[1],10):void 0,a=o?be(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:i,operation:n,timestamp:Date.now(),count:1}}function re(e){xe({roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp,count:1})}function Pt(e){let t=V.get(e);if(!t)return 0;let r=Date.now()-_e;return t.timestamps.filter(s=>s>=r).length}function Ct(){return[...ne]}O();P();var j=w("audit"),wo=.4,bo=1440*60*1e3,F=null,se=null;function un(e,t,r=wo){let s=R(t);if(!s||s.status==="retired"||s.status==="inactive"||s.status==="dead")return;let i=st(t,e);B(t,{performanceScore:i}),ct(t,i,r)?j.info({roleId:t,emaScore:i},"Probation role graduated"):i<r&&at(t,i,r)&&dt(t)}async function pn(){F===null&&(F=setInterval(()=>{j.info("Running daily diagnostic reports");let e=le(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")}},bo),se=await Et(),j.info("AuditManager started"))}function mn(){F!==null&&(clearInterval(F),F=null),se!==null&&(se(),se=null),j.info("AuditManager stopped")}function fn(e){re(e)}async function gn(){let e=L(),t=le(void 0,1e3),s=Date.now()-1440*60*1e3,i=Ct(),n=i.filter(c=>c.timestamp>=s).length,o=t.map(c=>{let d=i.filter(l=>l.roleId===c.id),u=d[d.length-1];return{roleId:c.id,roleName:c.name,sandboxed:e.platform!=="none",violationCount:Pt(c.id),lastViolation:u?.timestamp}}),a=await Qe();return{platform:e.platform,available:a,violationCount24h:n,rolePostures:o}}export{X as a,ot as b,pt as c,mt as d,Go as e,Xo as f,ye as g,er as h,tr as i,un as j,pn as k,mn as l,fn as m,gn as n,Rt as o};
@@ -1,49 +0,0 @@
1
- import{a as I,b as C}from"./chunk-NOUSHXGX.js";import{d as _}from"./chunk-I67UMGJM.js";import{a as k,b as T}from"./chunk-XAMLLKKA.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as y}from"./chunk-7BSWC62F.js";import{a as b,b as l,d,f as x}from"./chunk-T7GEINGZ.js";import{d as w}from"./chunk-7K4AQBDD.js";import{n as v,q as O}from"./chunk-J3NIPZ73.js";import{c as h,h as E}from"./chunk-INNDBLZE.js";E();O();import{v4 as c}from"uuid";import{CronExpressionParser as D}from"cron-parser";var n=h("scheduler"),m="ai-hourly-digest";function H(){if(l(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()};b(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,H();let e=d(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let i=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),i++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(o=>{n.error({taskId:r.taskId,error:o},"Event trigger check failed")})},u.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")})},u.on("workflow_status_change",this.workflowCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:i},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=v(void 0,1e3,0),t=0;for(let i of e)t+=y(i.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&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.workflowCompletionHandler&&(u.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 i;try{i=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=i.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)},s=r(),a=setTimeout(o,s);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+s).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,c()))}async scheduleJob(e){let t=l(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,i=this.cronJobs.get(t);i&&(clearTimeout(i),this.cronJobs.delete(t))}async runNow(e){let t=l(e);if(!t)throw new Error(`Template ${e} not found`);let i=c();return this.executeWorkflow(t,i).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),i}async checkEventTriggers(e){let t=T(e);if(!t)return;let i=d(!0),r=i.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,c());if(t.templateId){let o=i.filter(s=>s.trigger.type!=="event"||!s.trigger.event?!1:s.trigger.event===`template_complete:${t.templateId}`);for(let s of o)n.info({templateName:s.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(s,c())}}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=C(r);if(!o){n.warn({goalId:r,templateId:e.id},"Goal reference not found, skipping");continue}let s=c();I({id:s,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=c();k({id:a,status:"pending",prompt:`Decompose and execute goal: ${o.name}. ${o.description??""}`,parentId:s,config:w(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:a}),n.info({templateId:e.id,sourceGoalId:r,newGoalId:s,taskId:a},"Goal reference triggered, dispatched decomposition task")}return}let i=await this.workflowExecutor.execute(e,t);n.info({templateName:e.name,executionId:t,status:i.status,steps:i.stepResults.size},"Workflow execution finished")}async checkWorkflowEventTriggers(e){let i=d(!0).filter(r=>r.trigger.type!=="event"||!r.trigger.event?!1:r.trigger.event===`workflow_complete:${e}`);for(let r of i)n.info({templateName:r.name,sourceTemplateId:e},"Workflow complete trigger matched"),await this.executeWorkflow(r,c())}scheduleOnceJob(e){let t=l(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 s=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,s),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,c()),x(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},J=null;function U(){return J}function z(g){J=g}export{A as a,U as b,z as c};
@@ -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};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-4VHBKJD5.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-EZGMA3VV.js";import"./chunk-4VHBKJD5.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};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-3567PCEJ.js";import"./chunk-L4Y3GR6W.js";import"./chunk-RUY23IJK.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-GYHOPV4Q.js";import"./chunk-I5IUTZA3.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
@@ -1 +0,0 @@
1
- import{d as l,e as D,f as S,g as $}from"./chunk-YHH3QMLL.js";import{b as h}from"./chunk-6THDALGC.js";import{b as u}from"./chunk-XAMLLKKA.js";import{e as R,g as T,j as C}from"./chunk-24GTCFEV.js";import{k,m as x,q as N}from"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-NZEDILAK.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-DMZM7RU6.js";import"./chunk-24GTCFEV.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
@@ -1 +0,0 @@
1
- import{i as a,j as b,k as c,l as d,m as e,n as f,o as g,q as h}from"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.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-JKPSEMUZ.js";import"./chunk-GYHOPV4Q.js";import"./chunk-I5IUTZA3.js";import"./chunk-L7JP7DUO.js";import"./chunk-2CMR5AG7.js";import"./chunk-7BSWC62F.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{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-T7GEINGZ.js";import"./chunk-4VHBKJD5.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-I67UMGJM.js";import"./chunk-YHVFZB6Q.js";import"./chunk-XAMLLKKA.js";import"./chunk-CKIVKM5T.js";import"./chunk-KO5AFX5U.js";import"./chunk-EZGMA3VV.js";import"./chunk-L7JP7DUO.js";import"./chunk-7K4AQBDD.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-J3NIPZ73.js";import"./chunk-QQWRV23T.js";import"./chunk-4VHBKJD5.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as 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};