adam-agent-server 1.5.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 (127) 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-HYSB2EEK.js → channels-J4STJ4X2.js} +1 -1
  9. package/dist/{chunk-BR2JY5X2.js → chunk-2H7UOW4P.js} +1 -1
  10. package/dist/{chunk-VRJ7R766.js → chunk-3LY6PD6A.js} +1 -1
  11. package/dist/{chunk-YVS565QY.js → chunk-4C5ITATX.js} +1 -1
  12. package/dist/{chunk-R4GIIQ7G.js → chunk-52PR7XTN.js} +1 -1
  13. package/dist/chunk-5OQZPUBV.js +79 -0
  14. package/dist/{chunk-Y3AMO6WC.js → chunk-7446ZS6D.js} +1 -1
  15. package/dist/{chunk-GBTG5B5R.js → chunk-7ZGSJCX5.js} +1 -1
  16. package/dist/{chunk-QWCRZDZS.js → chunk-DBP7GPWG.js} +2 -2
  17. package/dist/{chunk-5XUR3M23.js → chunk-DWRYIN5N.js} +1 -1
  18. package/dist/{chunk-RAW263MQ.js → chunk-FIN36WAP.js} +4 -4
  19. package/dist/{chunk-2DLVAKH7.js → chunk-FXQAUQTI.js} +1 -1
  20. package/dist/{chunk-6FXNB7NE.js → chunk-FZCNYKNT.js} +1 -1
  21. package/dist/{chunk-7L2WQM7N.js → chunk-G5ESQEXN.js} +1 -1
  22. package/dist/chunk-GGIHDFRW.js +6 -0
  23. package/dist/{chunk-HDP7A4XY.js → chunk-GMMWA5EG.js} +1 -1
  24. package/dist/chunk-HWLSHTVX.js +27 -0
  25. package/dist/{chunk-ISZJV72D.js → chunk-I7ZZKPHE.js} +1 -1
  26. package/dist/{chunk-5V36ACKZ.js → chunk-IZNEOYRP.js} +1 -1
  27. package/dist/{chunk-6775OYXA.js → chunk-MDBVKBC7.js} +1 -1
  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-JAS3TUZX.js → chunk-NCFVJCNQ.js} +26 -7
  32. package/dist/{chunk-H7VDC6FY.js → chunk-P5ZXNBNV.js} +1 -1
  33. package/dist/{chunk-7K4AQBDD.js → chunk-PG6LMSX6.js} +1 -1
  34. package/dist/{chunk-QVKI7H7W.js → chunk-RLJYEEQC.js} +1 -1
  35. package/dist/{chunk-2CMR5AG7.js → chunk-SWP2JC54.js} +1 -1
  36. package/dist/{chunk-H54ZXA26.js → chunk-TNL2LZB7.js} +1 -1
  37. package/dist/{chunk-5S6BMWD2.js → chunk-TSPQ44HT.js} +1 -1
  38. package/dist/{chunk-Z4D3L2HR.js → chunk-V32YF3J5.js} +1 -1
  39. package/dist/{chunk-XL46AGRZ.js → chunk-VVSZZK5T.js} +2 -2
  40. package/dist/{chunk-HTPUEIFT.js → chunk-WAG3MNMC.js} +5 -5
  41. package/dist/{chunk-VRP4LTHY.js → chunk-YDVTWPNA.js} +1 -1
  42. package/dist/{chunk-C6BOQJJF.js → chunk-YHVYX3F4.js} +1 -1
  43. package/dist/{chunk-23VZKIB6.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-EMNKHR3W.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-LZSQPDHH.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 +16 -13
  54. package/dist/{learner-IJN6B7KV.js → learner-QCD6BH2J.js} +1 -1
  55. package/dist/{logger-QCJUU7GV.js → logger-WEXZORHP.js} +1 -1
  56. package/dist/{memories-ZII5QSTJ.js → memories-QGMRSBJJ.js} +1 -1
  57. package/dist/{memory-extractor-DIYJFBCI.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-W5AOIGEQ.js +0 -1
  104. package/dist/approval-handler-ORD4MUVM.js +0 -1
  105. package/dist/audit-manager-YCJT2WP5.js +0 -1
  106. package/dist/bree-engine-R5YLSDCL.js +0 -1
  107. package/dist/channels-JCMPPQED.js +0 -1
  108. package/dist/chunk-2YAP4YJV.js +0 -57
  109. package/dist/chunk-DZEVMYPB.js +0 -19
  110. package/dist/chunk-GY52JA5I.js +0 -10
  111. package/dist/chunk-MTWLLE26.js +0 -49
  112. package/dist/chunk-S3BAIZ4Q.js +0 -6
  113. package/dist/config-XMQS2NPT.js +0 -1
  114. package/dist/db-YUYXVV3A.js +0 -1
  115. package/dist/delivery-log-VKONLSVD.js +0 -1
  116. package/dist/engine-BM5BMPIC.js +0 -1
  117. package/dist/memory-service-QMYJPBAE.js +0 -1
  118. package/dist/outbound-gateway-6K6P2BEH.js +0 -1
  119. package/dist/role-presets-K2BDRZBS.js +0 -1
  120. package/dist/roles-L34L5MK3.js +0 -1
  121. package/dist/session-manager-GRJ3FV3L.js +0 -1
  122. package/dist/task-templates-23YOAF3E.js +0 -1
  123. package/dist/workflow-executor-JTUWX5DC.js +0 -1
  124. package/web/dist/assets/Plugins-CRym22JF.js +0 -1
  125. package/web/dist/assets/Work-BMl61RRi.js +0 -1
  126. package/web/dist/assets/index-DcXMQByM.css +0 -2
  127. package/web/dist/assets/index-pF--tN9F.js +0 -2
@@ -0,0 +1,79 @@
1
+ import{j as ve}from"./chunk-V32YF3J5.js";import{a as st,c as ut,d as ft,e as gt}from"./chunk-DWRYIN5N.js";import{b as ot,c as he,e as it}from"./chunk-TNL2LZB7.js";import{a as pt,c as we,e as mt}from"./chunk-2H7UOW4P.js";import{a as L,b as Je,c as He,d as Ye,e as Qe,f as Ze,h as Xe,i as re,j as q,k as oe,l as et,m as tt,n as V,o as rt,p as $,q as ge}from"./chunk-MDBVKBC7.js";import{a as nt}from"./chunk-IZNEOYRP.js";import{a as Ge,b as Ve,c as te,d as We,e as Be,f as Ke,g as Wt,h as ze,i as C,k as ne}from"./chunk-3LY6PD6A.js";import{b as Oe}from"./chunk-7446ZS6D.js";import{b as x,c as G,d as O}from"./chunk-I7ZZKPHE.js";import{d as be}from"./chunk-YXYIA24D.js";import{c as Fe}from"./chunk-MJSSCKMB.js";import{e as me,f as X,g as je,i as fe,j as ee}from"./chunk-DBP7GPWG.js";import{a as W}from"./chunk-L7JP7DUO.js";import{g as at}from"./chunk-YHVYX3F4.js";import{c as ye,d as B,e as lt,h as dt,i as ct}from"./chunk-GGIHDFRW.js";import{d as _,j as $e}from"./chunk-GSMC3VUM.js";import{f as Ue,g as ue,i as Vt,k as Le,l as I,n as U,o as A,p as qe,q as pe,r as Z}from"./chunk-7ZGSJCX5.js";import{b as D,d as Ne}from"./chunk-NCFVJCNQ.js";import{d as ce,h as Gt}from"./chunk-WBAPIPST.js";import{c as w,d as Me,h as N}from"./chunk-MRTJFYPR.js";import{f as P}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as yn,tool as u}from"@anthropic-ai/claude-agent-sdk";import{z as n}from"zod";Z();ee();import{v4 as K}from"uuid";N();var Bt=w("goal-manager");async function br(e){let t;try{let o=JSON.parse(e);t={name:o.name??"",description:o.description,metric:o.metric??"",targetValue:o.targetValue??0,currentValue:o.currentValue??0,deadline:o.deadline??0,budget:o.budget??0,roleId:o.roleId??"engineer",status:"active"}}catch{t=await Kt(e)}let r=zt(t);return{goalState:t,validationResult:r,rawInput:e}}async function Kt(e){let t=`Extract SMART goal fields from this natural language input.
2
+
3
+ Input: "${e}"
4
+
5
+ Respond ONLY with a JSON object:
6
+ {
7
+ "name": "short goal name (max 100 chars)",
8
+ "description": "detailed description of what the goal aims to achieve",
9
+ "metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
10
+ "targetValue": <number, the target to reach>,
11
+ "deadline_days": <number, days from now to complete>,
12
+ "budget": <number, estimated budget in USD>,
13
+ "role": "<best matching role: engineer | analyst | content_creator | reviewer>"
14
+ }
15
+
16
+ Rules:
17
+ - name: concise, actionable title
18
+ - metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
19
+ - targetValue: realistic target for the metric; use 1 for binary goals
20
+ - deadline_days: reasonable timeframe; default 7 if unclear
21
+ - budget: estimated cost in USD; default 5 if unclear
22
+ - role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let o=(await nt(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(o){let i=JSON.parse(o[0]),a=i.deadline_days??7;return{name:(i.name??e.slice(0,100)).slice(0,100),description:i.description??e,metric:i.metric??"completion",targetValue:i.targetValue??1,currentValue:0,deadline:Date.now()+a*24*60*60*1e3,budget:i.budget??5,roleId:i.roleId??"engineer",status:"active"}}}catch(r){Bt.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function zt(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function vr(e,t,r){let o=K(),i=Date.now(),a={id:o,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:i,deliverTo:t,reportTo:r};return re(a),a}function ht(e,t){let r=Date.now(),o=[],i={id:K(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};o.push(i),V(i);let a={id:K(),goalId:e,level:"L1",parentId:i.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};o.push(a),V(a);let l={id:K(),goalId:e,level:"L2",parentId:a.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};o.push(l),V(l);let d={id:K(),goalId:e,level:"L3",parentId:l.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return o.push(d),V(d),o}var Jt=3,Ht=2,ie=class{static async generateVariants(t,r,o=Jt,i=Ht){let a=$.getTopStrategies(t,r,o);if(a.length===0){let d=`baseline-${r}-v1`;return $.addStrategy(t,r,d,this.generateBaselinePrompt(t,r)),[d]}let l=[];for(let d=0;d<i;d++){let m=a[0].totalTrials+d+1,c=`${r}-evolved-v${m}`,h=a[0].promptTemplate,f=this.mutateTemplate(h);$.addStrategy(t,r,c,f),l.push(c)}return l}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
23
+
24
+ ## Core Focus
25
+ Complete tasks with high quality.
26
+
27
+ ## Approach
28
+ 1. Understand the task requirements thoroughly
29
+ 2. Plan your approach before executing
30
+ 3. Execute systematically, checking your work
31
+ 4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],o=r[Math.floor(Math.random()*r.length)];return`${t}
32
+
33
+ ## Evolution
34
+ ${o}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,o){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};N();ze();import{v4 as T}from"uuid";import{spawnSync as yt}from"child_process";import{createRequire as Yt}from"module";import{dirname as Qt,join as bt}from"path";import{openSync as Zt,readFileSync as Xt,unlinkSync as en}from"fs";var tn=3e4,vt=12e4;function wt(){let t=Yt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return bt(Qt(t),"cli.js")}function z(e,t){let r=wt(),o=t?.timeout??tn;if(t?.json){let a=bt("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),l=Zt(a,"w");try{let d=yt("node",[r,...e],{cwd:t.cwd,timeout:o,stdio:["ignore",l,"pipe"],encoding:"utf-8"});if(d.status!==0)throw new Error(d.stderr?.trim()||`CLI exited with status ${d.status}`);return Xt(a,"utf-8")}finally{try{en(a)}catch{}}}let i=yt("node",[r,...e],{cwd:t?.cwd,timeout:o,encoding:"utf-8"});if(i.status!==0)throw new Error(i.stderr?.trim()||`CLI exited with status ${i.status}`);return i.stdout}function It(){let e=z(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function Ie(e,t="user",r){return z(["plugin","install",e,"--scope",t],{cwd:r,timeout:vt})}function ke(e,t,r){let o=["plugin","uninstall",e];return t&&o.push("--scope",t),z(o,{cwd:r,timeout:vt})}function kt(e,t){return z(["plugin","enable",e])}function Tt(e,t){return z(["plugin","disable",e])}function Dr(){try{return!!wt()}catch{return!1}}Ne();import{v4 as rn}from"uuid";function on(e){return{id:e.id,eventDefId:e.event_def_id??void 0,occurredAt:e.occurred_at,ingestedAt:e.ingested_at,userDay:e.user_day??void 0,source:e.source,type:e.type,payload:JSON.parse(e.payload),confidence:e.confidence,dedupKey:e.dedup_key,relatedEntities:e.related_entities??void 0,trustLevel:e.trust_level}}function St(e){let t=D(),r=e.id??rn(),o=new Date().toISOString();return t.prepare(`
35
+ INSERT OR IGNORE INTO events
36
+ (id, event_def_id, occurred_at, ingested_at, user_day, source, type, payload, confidence, dedup_key, related_entities, trust_level)
37
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
38
+ `).run(r,e.eventDefId??null,e.occurredAt??o,o,e.userDay??null,e.source,e.type,JSON.stringify(e.payload),e.confidence??1,e.dedupKey,e.relatedEntities??null,e.trustLevel??"trusted").changes===0?{inserted:!1,id:t.prepare("SELECT id FROM events WHERE source = ? AND dedup_key = ?").get(e.source,e.dedupKey)?.id??r}:{inserted:!0,id:r}}function Rt(e={}){let t=D(),r="SELECT * FROM events WHERE 1=1",o=[];e.eventDefId!==void 0&&(r+=" AND event_def_id = ?",o.push(e.eventDefId)),e.typePattern!==void 0&&(r+=" AND type LIKE ?",o.push(e.typePattern)),e.since!==void 0&&(r+=" AND occurred_at >= ?",o.push(e.since)),e.until!==void 0&&(r+=" AND occurred_at <= ?",o.push(e.until)),r+=" ORDER BY occurred_at DESC";let i=Math.min(e.limit??50,500);return r+=` LIMIT ${i}`,e.offset!==void 0&&(r+=` OFFSET ${e.offset}`),t.prepare(r).all(...o).map(on)}Ne();function _t(e){return{id:e.id,name:e.name,sourceType:e.source_type,sourceConfig:JSON.parse(e.source_config),enabled:e.enabled===1,description:e.description??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}function Dt(e){let t=D(),r=Date.now();return t.prepare(`
39
+ INSERT INTO event_defs (id, name, source_type, source_config, enabled, description, created_at, updated_at)
40
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
41
+ `).run(e.id,e.name,e.sourceType,JSON.stringify(e.sourceConfig),e.enabled?1:0,e.description??null,r,r),{...e,createdAt:r,updatedAt:r}}function j(e){let r=D().prepare("SELECT * FROM event_defs WHERE id = ?").get(e);return r?_t(r):void 0}function se(e={}){let t=D(),r="SELECT * FROM event_defs WHERE 1=1",o=[];return e.sourceType!==void 0&&(r+=" AND source_type = ?",o.push(e.sourceType)),e.enabled!==void 0&&(r+=" AND enabled = ?",o.push(e.enabled?1:0)),r+=" ORDER BY created_at DESC",t.prepare(r).all(...o).map(_t)}function Te(e,t){let r=D(),o=j(e);if(!o)return;let i={...o,...t,updatedAt:Date.now()};return r.prepare(`
42
+ UPDATE event_defs
43
+ SET name = ?, source_type = ?, source_config = ?, enabled = ?, description = ?, updated_at = ?
44
+ WHERE id = ?
45
+ `).run(i.name,i.sourceType,JSON.stringify(i.sourceConfig),i.enabled?1:0,i.description??null,i.updatedAt,e),i}function Se(e){return D().prepare("DELETE FROM event_defs WHERE id = ?").run(e).changes>0}import{CronExpressionParser as sn}from"cron-parser";import{v4 as an}from"uuid";function M(e){let{emitPayload:t,...r}=e,o=St(r);return o.inserted?(e.eventDefId&&W.emit({type:"event_fired",eventDefId:e.eventDefId,eventId:o.id,payload:t??e.payload}),{inserted:!0,id:o.id}):{inserted:!1,id:o.id}}N();var Et=w("scheduler"),ae=new Map;function Ct(e,t){let r=t.next(),o=Math.max(r.getTime()-Date.now(),1e3),i=setTimeout(async()=>{try{let a=an(),l=e.sourceConfig.payload_template??{},d={triggered_at:new Date().toISOString(),...l};M({id:a,eventDefId:e.id,type:"scheduler.tick",source:"adam-internal",dedupKey:`cron-${e.id}-${Date.now()}`,payload:d,occurredAt:new Date().toISOString(),trustLevel:"trusted"})}catch(a){Et.error({defId:e.id,err:a},"cron handler failed")}ae.has(e.id)&&Ct(e,t)},o);ae.set(e.id,i)}function Pt(e){if(!e.enabled)return;let t=sn.parse(e.sourceConfig.cron);Ct(e,t),Et.info({defId:e.id,defName:e.name},"Cron source started")}function xt(e){let t=ae.get(e);t&&(clearTimeout(t),ae.delete(e))}Gt();import{watch as ln}from"fs";import{statSync as dn,realpathSync as cn}from"fs";import{homedir as un}from"os";import{join as At,extname as pn}from"path";import{createHash as mn}from"crypto";N();var J=w("scheduler"),Re=new Map;function fn(e){let t;try{t=cn(e)}catch{throw new Error(`Watch path does not exist: ${e}`)}let r=un();if(!t.startsWith(r)&&!t.startsWith(ce))throw new Error(`Watch path must be within ${r} or ${ce}: ${e}`)}function $t(e){if(!e.enabled)return;let t=e.sourceConfig;fn(t.path);let r=t.stability_delay_ms??5e3,o=t.glob,i={watcher:null,stopped:!1,stabilityTimer:null,pendingEvents:new Map},a=(l,d)=>{if(!l||i.stopped||o&&!gn(l,o))return;let m=At(t.path,l),c=0,h=Date.now();try{let f=dn(m);c=f.size,h=f.mtimeMs}catch{return}i.pendingEvents.set(l,{mtime:h,size:c}),i.stabilityTimer&&clearTimeout(i.stabilityTimer),i.stabilityTimer=setTimeout(()=>{if(!i.stopped){for(let[f,g]of i.pendingEvents)try{let b=At(t.path,f),S=mn("sha256").update(`dir-${e.id}-${b}-${g.mtime}`).digest("hex").slice(0,16);M({id:S,eventDefId:e.id,type:"filesystem.file.created",source:`dir-${e.id}`,dedupKey:`dir-${e.id}-${b}-${g.mtime}`,payload:{file_path:b,mtime:g.mtime,size:g.size},occurredAt:new Date(g.mtime).toISOString(),trustLevel:"trusted"})}catch(b){J.warn({file:f,err:b},"Failed to fire directory watch event")}i.pendingEvents.clear()}},r)};try{i.watcher=ln(t.path,{persistent:!1},(l,d)=>{a(d,l)}),i.watcher.on("error",l=>{J.warn({defId:e.id,err:l},"fs.watch error, removing watcher"),_e(e.id)}),Re.set(e.id,i),J.info({defId:e.id,defName:e.name,path:t.path},"Directory watch started")}catch(l){throw J.error({defId:e.id,err:l},"Failed to start directory watch"),l}}function _e(e){let t=Re.get(e);if(t){t.stopped=!0,t.stabilityTimer&&clearTimeout(t.stabilityTimer);try{t.watcher.close()}catch{}Re.delete(e),J.info({defId:e},"Directory watch stopped")}}function gn(e,t){if(t.startsWith("*.")){let r=t.slice(1);return pn(e)===r}return e===t}import{v4 as Mt}from"uuid";function De(e,t){if(!e.enabled)throw new Error(`Event def '${e.id}' is disabled`);let r=Mt();return M({id:r,eventDefId:e.id,type:"manual.fire",source:"manual",dedupKey:`manual-${e.id}-${Date.now()}`,payload:t??{},occurredAt:new Date().toISOString(),trustLevel:"trusted"}),{eventId:r}}function Ee(e,t){let r=Mt(),o=Date.now(),i=Math.random().toString(36).slice(2,10);return M({id:r,eventDefId:e.id,type:"manual.test.fire",source:`manual-test-${e.id}`,dedupKey:`manual-test-${e.id}-${o}-${i}`,payload:t??{},occurredAt:new Date().toISOString(),trustLevel:"trusted"}),{eventId:r}}N();var Ce=w("scheduler");function Pe(e){if(e.enabled)switch(e.sourceType){case"cron":Pt(e);break;case"directory_watch":$t(e);break;case"webhook":break;case"manual":break;default:Ce.warn({defId:e.id,sourceType:e.sourceType},"Unknown source type, skipping")}}function le(e,t){switch(t){case"cron":xt(e);break;case"directory_watch":_e(e);break;case"webhook":case"manual":break;default:Ce.warn({defId:e,sourceType:t},"Unknown source type, nothing to stop")}}async function oo(){let e=se({});for(let t of e)t.enabled&&le(t.id,t.sourceType);Ce.info("All event source handlers stopped")}import{z as k}from"zod/v4";var Nt={webhook:k.object({}).strict(),manual:k.object({}).strict(),cron:k.object({cron:k.string().min(1,"cron expression required"),payload_template:k.record(k.string(),k.unknown()).optional()}).strict(),directory_watch:k.object({path:k.string().min(1,"watch path required"),glob:k.string().optional(),stability_delay_ms:k.number().int().positive().optional()}).strict()};function H(){return Object.keys(Nt)}function hn(e){return Nt[e]}function xe(e,t){let r=hn(e);if(!r)return{ok:!1,error:`Unknown sourceType: '${e}'. Known: ${H().join(", ")}`};let o=r.safeParse(t??{});return o.success?{ok:!0,data:o.data}:{ok:!1,error:k.prettifyError(o.error)}}N();import*as Ot from"crypto";var Y=w("api"),Q=class{cancelTask(t){let r=x(t);r&&(G(t,{status:"cancelled",completedAt:Date.now()}),W.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),Y.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,o){return Y.debug({approvalId:t,action:r,reason:o},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,o,i){let a=ot(t);if(!a)return Y.warn({planId:t},"Plan not found or already resolved"),!1;let l=x(a.taskId);return l?(it(t,r==="allow"?"approved":"denied",o),r==="allow"&&o==="permanent"&&st({id:Ot.randomUUID(),roleId:a.roleId,taskPattern:l.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:a.plan.overallRisk,createdAt:Date.now(),createdByTaskId:l.id}),W.emit({type:"plan_approval_decision",taskId:l.id,planId:t,decision:r,approvalType:o,reason:i}),Y.debug({planId:t,decision:r,approvalType:o},"Plan approval resolved"),!0):(Y.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as Ut}from"fs";Vt();var F=w("manager");function s(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function bn(e){let t=e.parameters?Object.entries(e.parameters).map(([o,i])=>`- ${o}: ${i.description}`).join(`
46
+ `):"",r=t?`
47
+ ## Inputs
48
+ ${t}
49
+ `:"";return`---
50
+ description: ${e.description}
51
+ ---
52
+ # ${e.skillName}
53
+ ${r}
54
+ ## Instructions
55
+ ${e.instructions}
56
+ `}async function R(e){let{listChannels:t}=await import("./channels-J4STJ4X2.js"),r=t(),{listSessions:o}=await import("./session-manager-LZ77OT7A.js"),i=[...o("active"),...o("archived")],a=[];for(let l of e)if(l.type==="session"&&l.sessionId)a.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,m=l.chatId;if(!d&&l.channelName){let c=r.find(h=>h.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!m){let c=i.find(h=>h.source.type==="channel"&&h.source.channelId===d&&h.source.chatId);c?.source.chatId?m=c.source.chatId:m=r.find(f=>f.id===d)?.config?.userId}d&&m?a.push({type:"channel",channelId:d,chatId:m}):F.warn({channelName:l.channelName,channelId:d,chatId:m},"Could not resolve channel notify target")}return a}async function vn(e){let{listRoles:t}=await import("./roles-KYXNMO5H.js"),r=t(void 0,100,0);for(let o of r)if(o.name.toLowerCase().includes(e.toLowerCase()))return o.id}var wn={goalId:n.string()},In={goalId:n.string(),status:n.string().optional(),currentValue:n.number().optional(),budgetUsd:n.number().optional(),notes:n.string().optional()},kn={goalId:n.string(),goalDescription:n.string(),maxSubtasks:n.number().optional()},E=n.union([n.object({type:n.literal("session"),sessionId:n.string()}),n.object({type:n.literal("channel"),channelName:n.string()}),n.object({type:n.literal("channel"),channelId:n.string(),chatId:n.string().optional()})]),Tn={prompt:n.string(),roleId:n.string().optional().describe("Role ID. Call list_roles(requirements) first to find the best role for the task."),requirements:L.optional(),autoSelectRole:n.boolean().optional(),deliverTo:n.array(E).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:n.object({allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional()}).optional()},Sn={taskId:n.string(),goalId:n.string().optional(),strategyId:n.string().optional()},Rn={roleId:n.string(),taskType:n.string(),name:n.string().optional()},_n={status:n.string().optional(),limit:n.number().optional()},Dn={taskId:n.string(),roleId:n.string()},En={taskId:n.string().optional(),status:n.string().optional(),limit:n.number().optional()},Cn={roleId:n.string(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional(),allowedChannels:n.array(n.string()).optional(),inheritUserSettings:n.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Pn={roleId:n.string().describe("Role ID to update."),name:n.string().min(1).optional(),cagPrompt:n.string().optional(),learnedRules:n.array(n.string()).optional(),status:n.enum(["active","inactive","retired"]).optional(),executionMode:n.enum(["isolated","inline"]).optional(),model:n.string().optional(),maxBudgetUsd:n.number().optional(),approvalRequired:n.array(n.string()).optional(),preferences:n.object({model:n.string().optional(),effort:n.enum(["low","medium","high","max"]).optional(),maxTurns:n.number().optional()}).optional(),permissionMode:n.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:n.array(n.string()).optional(),deniedBashPatterns:n.array(n.string()).optional(),evaluationCriteria:n.record(n.string(),n.number()).optional(),envVars:n.record(n.string(),n.string()).optional()},xn={roleId:n.string().optional(),limit:n.number().optional()},An={name:n.string(),cagPrompt:n.string(),traits:n.array(n.string()).optional(),allowedTools:n.array(n.string()).optional(),disallowedTools:n.array(n.string()).optional(),osCapabilities:n.array(n.object({id:n.string().min(1),targets:n.array(n.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:n.array(n.object({path:n.string(),mode:n.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:n.boolean().optional(),inheritMcp:n.boolean().optional(),inheritPermissions:n.boolean().optional()})).optional()},$n={roleId:n.string(),reason:n.string().optional()},Mn={name:n.string(),description:n.string().optional(),roleId:n.string().optional(),metric:n.string().optional(),targetValue:n.number().optional(),deadline:n.number().optional(),budgetUsd:n.number().optional(),deliverTo:n.array(E).optional().describe("Where to deliver goal completion notifications.")},Nn={name:n.string(),description:n.string().optional(),triggerType:n.enum(["cron","template_complete","workflow_complete","event"]),triggerCron:n.string().optional(),triggerEvent:n.string().optional().describe("For triggerType=template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. For cron/event: unused."),eventDefId:n.string().uuid().optional().describe("Required when triggerType='event'. Event def to bind this template to. Use list_event_defs to find or create_event_def to create one."),prompt:n.string(),roleId:n.string().optional(),requirements:L.optional(),autoSelectRole:n.boolean().optional(),enabled:n.boolean().optional(),goalIds:n.array(n.string()).optional(),deliverTo:n.array(E).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary).")},On={status:n.enum(["active","retired","probation"]).optional(),limit:n.number().optional(),requirements:L.optional()},Un={enabled:n.boolean().optional()},Ln={},qn={},jn={prompt:n.string().describe("The task prompt to execute after the delay"),delayMinutes:n.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:n.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:n.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:n.array(E).optional().describe("Where to deliver the task output (result full text)."),reportTo:n.array(E).optional().describe("Where to send status reports (completion summary).")},Fn={roleId:n.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Gn={roleId:n.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:n.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Vn={roleId:n.string().describe("Role ID to uninstall the plugin from."),pluginId:n.string().describe("Plugin ID to uninstall.")},Wn={roleId:n.string().describe("Role ID to bind the MCP server to."),mcpName:n.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:n.record(n.string(),n.unknown()).describe("MCP server configuration object.")},Bn={roleId:n.string().describe("Role ID to unbind the MCP server from."),mcpName:n.string().describe("Name of the MCP server to remove.")},Kn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},zn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Jn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Hn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Yn={},Qn={},Zn={pluginId:n.string().describe("Plugin ID (e.g., 'github@anthropic').")},Xn={roleId:n.string().describe("Role ID to associate scanned plugins with."),path:n.string().describe("Directory path to scan for .claude/settings.json.")},er={taskId:n.string().describe("Task ID to cancel.")},tr={taskId:n.string().describe("Task ID to get logs for."),limit:n.number().optional().describe("Max log entries (default 20).")},nr={roleId:n.string().describe("Role ID to delete.")},rr={},or={updates:n.record(n.string(),n.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},ir={roleId:n.string().describe("Role ID to list memories for."),limit:n.number().optional().describe("Max results (default 20).")},sr={templateId:n.string().describe("Template ID to update."),name:n.string().optional(),enabled:n.boolean().optional(),prompt:n.string().optional(),triggerType:n.enum(["cron","template_complete","workflow_complete","event"]).optional().describe("Explicit trigger type. Required when updating trigger settings."),triggerCron:n.string().optional(),triggerEvent:n.string().optional().describe("For template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. Unused for cron/event."),eventDefId:n.string().uuid().optional().describe("Required when triggerType='event'. The event def UUID to bind this template to."),roleId:n.string().optional(),autoSelectRole:n.boolean().optional().describe("Step-level: if true, Adam picks the best-fit role at dispatch time. Write to the single-step template's step."),requirements:L.optional().describe("Step-level: required when autoSelectRole=true. Fields: tools, paths, osCapabilities, network, plugins.")},ar={templateId:n.string().describe("Template ID to delete.")},lr={templateId:n.string().describe("Template ID to run immediately.")},dr={enabled:n.boolean().optional().describe("Filter by enabled status.")},cr={eventType:n.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:n.string().describe("Channel ID to deliver to."),format:n.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:n.record(n.string(),n.unknown()).optional().describe("JSON match criteria for event fields."),enabled:n.boolean().optional().describe("Enable this rule immediately (default true).")},ur={ruleId:n.string().describe("Delivery rule ID to delete.")},pr={roleId:n.string().optional().describe("Role ID to filter strategies by.")},Lt=[u("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",wn,async e=>{let t=q(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),o=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:o,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),u("update_goal_state","Update a goal's status, current value, or budget.",In,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),oe(e.goalId,t)),s({success:!0})}),u("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",kn,async e=>{let t=_(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),l=`Decompose this goal into ${r} actionable subtasks.
57
+
58
+ Goal: ${e.goalDescription}
59
+
60
+ Respond ONLY with a JSON array. Each item:
61
+ {
62
+ "description": "...",
63
+ "prompt": "detailed task instruction",
64
+ "complexity": "low|medium|high",
65
+ "role": "engineer|analyst|content_creator|reviewer",
66
+ "requirements": {
67
+ "tools": ["Read", "Write"],
68
+ "paths": [{"path": "/abs/path", "access": "ro"}],
69
+ "osCapabilities": [{"id": "automation", "targets": ["bundle.id"]}],
70
+ "network": false
71
+ }
72
+ }
73
+
74
+ Rules:
75
+ - Each subtask must be independently executable
76
+ - Order from foundational to dependent
77
+ - Be specific about what each subtask should accomplish
78
+ - For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.
79
+ - Include tools and paths required for the subtask where known. If unknown, omit the field.`,d=a({prompt:l,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),m="";for await(let h of d){let f=h;f.type==="result"&&typeof f.result=="string"&&(m=f.result)}let c=m.match(/\[[\s\S]*\]/);if(c){let h=JSON.parse(c[0]),f=[];for(let g=0;g<Math.min(h.length,r);g++){let b=h[g],S=b.role,p=S?await vn(S):void 0,y=await ge({prompt:b.prompt,roleId:p,requirements:b.requirements,config:t.defaults});if(!y.ok){f.push({id:`admission-failed-${g}`,description:b.description,prompt:b.prompt,dependencies:g>0&&f.length>0?[f[g-1].id]:[],estimatedComplexity:b.complexity??"medium",role:S,admissionError:`${y.code}: ${y.reason}`});continue}f.push({id:y.taskId,description:b.description,prompt:b.prompt,dependencies:g>0?[f[g-1].id]:[],estimatedComplexity:b.complexity??"medium",role:S})}if(f.length>0)return s({subtasks:f})}}catch(a){F.error({error:a},"LLM decomposition failed, using fallback")}let o=await Ze({taskId:T(),roleId:void 0,autoSelectRole:!1}),i=[];return o.ok||i.push({id:"admission-blocked",description:`Decomposition fallback blocked: ${o.reason}`,prompt:e.goalDescription,dependencies:[],estimatedComplexity:"medium",admissionError:`${o.code}: ${o.reason}`}),s({subtasks:i})}),u("dispatch_task","Create and dispatch a task. Workflow: (1) call list_roles(requirements) to find candidate roles by fit; (2) call dispatch_task with requirements AND the chosen roleId. requirements is STRONGLY RECOMMENDED \u2014 when present, admission validates role fit before creation and returns structured mismatch diagnostics. If you cannot produce clear requirements from the user's message, ASK THE USER instead of dispatching. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Tn,async e=>{if(!e.roleId&&!e.autoSelectRole){let i=A("active",20,0).filter(a=>a.source!=="system").map(a=>({id:a.id,name:a.name,allowedTools:a.allowedTools??[],capabilitySummary:C(a)}));return s({error:"Must provide roleId or autoSelectRole=true with requirements.",availableRoles:i})}let t=e.deliverTo?await R(e.deliverTo):void 0,r=e.reportTo?await R(e.reportTo):void 0,o=await ge({prompt:e.prompt,roleId:e.roleId,requirements:e.requirements,autoSelectRole:e.autoSelectRole,deliverTo:t,reportTo:r,toolOverrides:e.toolOverrides});if(!o.ok){let i=(o.candidates??[]).map(l=>({id:l.roleId,name:l.name,fitScore:l.fitScore,missing:l.missing})),a=i.length>0?i:A("active",20,0).filter(l=>l.source!=="system").map(l=>({id:l.id,name:l.name,allowedTools:l.allowedTools??[],capabilitySummary:C(l)}));return s({error:o.reason,code:o.code,missing:o.missing,availableRoles:a})}return s({taskId:o.taskId,roleId:o.roleId,fitScore:o.fitScore,strategyId:o.strategyId,warnings:o.warnings})}),u("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:n.array(n.object({id:n.string().describe("Unique step identifier"),prompt:n.string().describe("Task prompt for this step"),roleId:n.string().optional().describe("Role ID for this step. Call list_roles first to find roles."),requirements:L.optional().describe("Task requirements for this step (D-012)."),autoSelectRole:n.boolean().optional().describe("Auto-select best role for this step (D-012)."),dependsOn:n.array(n.string()).optional().describe("Step IDs this step depends on"),config:n.object({timeout:n.number().optional(),maxTurns:n.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:n.string().optional().describe("Workflow name for tracking"),deliverTo:n.array(E).optional().describe("Where to deliver the aggregated workflow output"),reportTo:n.array(E).optional().describe("Where to send workflow status reports"),continueOnError:n.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let p of e.steps){if(!p.roleId&&!p.autoSelectRole){t.push(`${p.id} (needs roleId or autoSelectRole)`);continue}if(p.roleId){let y=I(p.roleId);(!y||y.status!=="active")&&t.push(`${p.id} (roleId ${p.roleId} invalid/inactive)`)}}if(t.length>0){let p=A("active",20,0).filter(y=>y.source!=="system").map(y=>({id:y.id,name:y.name,capabilitySummary:C(y)}));return s({error:`Steps missing roleId/autoSelectRole or with invalid roleIds: ${t.join("; ")}.`,availableRoles:p})}let r=new Set(e.steps.map(p=>p.id));for(let p of e.steps)if(p.dependsOn)for(let y of p.dependsOn){if(!r.has(y))return s({error:`Step "${p.id}" depends on unknown step "${y}"`});if(y===p.id)return s({error:`Step "${p.id}" cannot depend on itself`})}let o=new Set,i=new Set,a=new Map(e.steps.map(p=>[p.id,p.dependsOn??[]])),l=p=>{if(i.has(p))return!0;if(o.has(p))return!1;o.add(p),i.add(p);for(let y of a.get(p)??[])if(l(y))return!0;return i.delete(p),!1};for(let p of e.steps)if(l(p.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0,c=T(),h=_(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(p=>({id:p.id,prompt:p.prompt,roleId:p.roleId,requirements:p.requirements,autoSelectRole:p.autoSelectRole,dependsOn:p.dependsOn,config:p.config})),enabled:!0,createdAt:Date.now(),config:{...h.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:m};try{ye(f)}catch(p){let{TemplateRoleConfigError:y}=await import("./task-templates-YPNWJOVV.js");if(p instanceof y)return s({code:p.code,error:p.message,failingStepIds:p.failingStepIds,hint:"Each step must have roleId OR autoSelectRole=true (with requirements). Use list_roles to find an appropriate role."});throw p}let{WorkflowExecutor:g}=await import("./workflow-executor-3WMS2WV3.js");new g().execute(f,c).catch(p=>{F.error({executionId:c,error:p},"dispatch_workflow execution failed")});let S=e.steps.map(p=>{let y=p.roleId??(p.autoSelectRole?"[auto-selected]":"[no role]");return(p.roleId?I(p.roleId):void 0)?.name??y});return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(S)],status:"started"})}),u("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Sn,async e=>{let{goalId:t,taskId:r,strategyId:o}=e,i=rt(t??"",r);return o&&t&&$.recordTrial(o,t,r,i.reward,i.breakdown.L2||void 0,i.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:i.reward,metricL2Score:i.breakdown.L2||void 0,metricL3Score:i.breakdown.L3||void 0,source:i.source,reasoning:`Evaluated via ${i.source} with confidence ${i.confidence.toFixed(2)}`})}),u("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Rn,async e=>{let{roleId:t,taskType:r}=e;await ie.generateVariants(t,r,3,1);let o=$.getStrategies(t,r),i=o[o.length-1];return s(i?{id:i.id,name:i.name,promptTemplate:i.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),u("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",_n,async e=>{let t=e.status;return s(et(t,e.limit??10,0))}),u("delete_goal","Delete a goal by ID.",{goalId:n.string()},async e=>q(e.goalId)?(tt(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),u("pause_goal","Pause an active goal.",{goalId:n.string()},async e=>q(e.goalId)?(oe(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),u("assign_role","Assign a role to a pending task.",Dn,async e=>{let{taskId:t,roleId:r}=e;if(!x(t))return s({error:`Task not found: ${t}`});let i=I(r);return i?(G(t,{roleId:r}),F.debug({taskId:t,roleId:r,roleName:i.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...ut(),u("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",En,async e=>{if(e.taskId){let r=x(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(O(t,e.limit??100,0))}),u("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Cn,async e=>{if(!I(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=ue(e.osCapabilities)}catch(o){return s({error:o instanceof Error?o.message:String(o)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),U(e.roleId,r),s({success:!0})}),u("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Pn,async e=>{if(!I(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...o}=e,i={...o,updatedAt:Date.now()};U(r,i);let a=I(r);if(!a)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=me(a.name);Ut(l)&&je(l,a)}return s({success:!0,role:a})}),u("view_audit_log","View the evolution audit log for role changes.",xn,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-OQDGPKYI.js"),r=t(e.limit??50);return s({entries:r})}),u("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks. Pass requirements to get ranked results with fitScore showing which roles best match the task.",On,async e=>{if(e.requirements){let o=e.requirements,a=Qe(o).slice(0,e.limit??50).map(l=>{let d=l.role,m=ne(d),c=m.plugins.map(v=>v.name),h=me(d.name),f=Je(d,h),g=o.tools?(d.allowedTools??[]).filter(v=>o.tools.includes(v)):void 0,b=o.paths?o.paths.filter(v=>He(v,f)):void 0,S=new Set((d.osCapabilities??[]).map(v=>v.id)),p=o.osCapabilities?o.osCapabilities.filter(v=>S.has(v.id)).map(v=>v.id):void 0,y=new Set(c),Ae=o.plugins?o.plugins.filter(v=>y.has(v)):void 0,qt=o.network===!0?(d.osCapabilities??[]).some(v=>v.id==="local-network"):void 0,jt=l.missing?.osCapabilities,Ft=Ye(d,o);return{id:d.id,name:d.name,status:d.status,allowedTools:d.allowedTools??[],disallowedTools:d.disallowedTools??[],osCapabilities:d.osCapabilities??[],additionalDirectories:d.additionalDirectories??[],cagPrompt:d.cagPrompt.slice(0,500)+(d.cagPrompt.length>500?"...":""),capabilitySummary:C(d,m),plugins:m.plugins.map(v=>({name:v.name,skills:v.skills.map(de=>de.name),agents:v.agents.map(de=>de.name)})),fitScore:l.fitScore,fits:l.evaluation.ok,matchedTools:g,matchedPaths:b,matchedOsCapabilities:p,matchedPlugins:Ae,matchedNetwork:qt,missingCapabilities:l.missing?{tools:l.missing.tools,paths:l.missing.paths,osCapabilities:jt?.map(v=>v.id),plugins:l.missing.plugins,network:l.missing.network}:void 0,warnings:Ft,why:l.evaluation.ok?`Role '${d.name}' satisfies all requirements (fitScore: ${l.fitScore.toFixed(2)})`:`Role '${d.name}' does not satisfy requirements: ${l.evaluation.ok?"unknown":l.evaluation.reason}`}});return s({roles:a})}let r=A(e.status,e.limit??50,0).map(o=>{let i=ne(o);return{id:o.id,name:o.name,status:o.status,allowedTools:o.allowedTools??[],disallowedTools:o.disallowedTools??[],osCapabilities:o.osCapabilities??[],additionalDirectories:o.additionalDirectories??[],cagPrompt:o.cagPrompt.slice(0,500)+(o.cagPrompt.length>500?"...":""),capabilitySummary:C(o,i),plugins:i.plugins.map(a=>({name:a.name,skills:a.skills.map(l=>l.name),agents:a.agents.map(l=>l.name)}))}});return s({roles:r})}),u("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",An,async e=>{let t;try{t=ue(e.osCapabilities)}catch(i){return s({error:i instanceof Error?i.message:String(i)})}let r=`role-${T().slice(0,8)}`,o={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${T().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return Le(o),X(o),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:o.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),u("retire_role","Retire a role (marks as retired, stops receiving tasks).",$n,async e=>I(e.roleId)?(U(e.roleId,{status:"retired"}),F.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),u("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Mn,async e=>{let t=T(),r=Date.now(),o=r+10080*60*1e3,i={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??o,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};re(i),ht(t,i.metricType);let a=q(t);return s({goalId:a.id,name:a.name,status:a.status})}),u("create_template","Create a recurring scheduled task. triggerType values: 'cron' (recurring via cron expression), 'template_complete' (fires when a specific template's task completes; set triggerEvent to 'template_complete:<templateId>'), 'workflow_complete' (similar), 'event' (fires when an Event def fires; set eventDefId to the event def UUID \u2014 use list_event_defs or create_event_def first). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Nn,async e=>{let{createTaskTemplate:t}=await import("./task-templates-YPNWJOVV.js"),r=T(),o=T();if(e.triggerType==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});if(e.triggerType!=="event"&&e.eventDefId)return s({error:"eventDefId only valid when triggerType='event'"});let i=e.deliverTo?await R(e.deliverTo):void 0,a=e.reportTo?await R(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent,eventDefId:e.eventDefId},steps:[{id:o,prompt:e.prompt,...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:i,reportTo:a};try{t(l)}catch(d){let{TemplateRoleConfigError:m}=await import("./task-templates-YPNWJOVV.js");if(d instanceof m)return s({code:d.code,error:d.message,failingStepIds:d.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object (e.g., {tools:['Read']}) on the template. Use list_roles to find an appropriate role."});throw d}return s({templateId:r,name:l.name,trigger:l.trigger})}),u("create_event_def","Create an Event definition \u2014 a user-configured source that fires on schedule/webhook/directory/manual. Event defs are the trigger half of the Event Slot; pair with create_template(triggerType='event', eventDefId=<returned id>) to bind work to the trigger. sourceType is validated at runtime against the installed source registry (currently: webhook, cron, directory_watch, manual \u2014 additional types may be registered at runtime). sourceConfig is per-type: cron \u2192 {cron: '0 9 * * *'}; directory_watch \u2192 {path: '/abs/path', glob?: '*.md'}; webhook/manual \u2192 {}.",{name:n.string().min(1).max(100).describe("Human-readable name (unique within workspace)."),sourceType:n.string().describe("Source type \u2014 validated against installed registry at call time. Currently: 'webhook' | 'cron' | 'directory_watch' | 'manual'. If the value is rejected, the error message lists the currently-registered types."),sourceConfig:n.record(n.string(),n.unknown()).describe("Per-sourceType configuration. See tool description."),enabled:n.boolean().optional().describe("Default true."),description:n.string().max(500).optional()},async e=>{if(!H().includes(e.sourceType))return s({error:`Unknown sourceType: '${e.sourceType}'. Currently registered: ${H().join(", ")}`});let t=xe(e.sourceType,e.sourceConfig);if(!t.ok)return s({error:`Invalid sourceConfig: ${t.error}`});let r=T(),o=Dt({id:r,name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled??!0,description:e.description});try{Pe(o)}catch(i){Se(r);let a=i instanceof Error?i.message:String(i);return s({error:`Failed to start source: ${a}. Event def was not created.`})}return s({id:o.id,name:o.name,sourceType:o.sourceType,enabled:o.enabled})}),u("list_event_defs","List Event definitions. Use before create_template(triggerType='event') to find the eventDefId, or before fire_event_def / list_event_firings.",{sourceType:n.string().optional().describe("Filter by source type (e.g., 'cron', 'webhook')."),enabled:n.boolean().optional().describe("Filter by enabled flag.")},async e=>{let t=se({sourceType:e.sourceType,enabled:e.enabled});return s(t.map(r=>({id:r.id,name:r.name,sourceType:r.sourceType,sourceConfig:r.sourceConfig,enabled:r.enabled,description:r.description,createdAt:r.createdAt})))}),u("update_event_def","Update an Event definition. Changing `enabled` or `sourceConfig` on an active def automatically restarts the runtime source handler. Use list_event_defs first to get the id.",{id:n.string().uuid().describe("Event def id."),name:n.string().min(1).max(100).optional(),sourceType:n.string().optional().describe("Only set when migrating to a different source type."),sourceConfig:n.record(n.string(),n.unknown()).optional(),enabled:n.boolean().optional(),description:n.string().max(500).optional()},async e=>{let t=j(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});if(e.sourceType!==void 0||e.sourceConfig!==void 0){let l=e.sourceType??t.sourceType;if(!H().includes(l))return s({error:`Unknown sourceType: '${l}'`});let d=xe(l,e.sourceConfig??t.sourceConfig);if(!d.ok)return s({error:`Invalid sourceConfig: ${d.error}`})}let r=t.enabled,o=e.enabled??t.enabled,i=e.sourceType!==void 0||e.sourceConfig!==void 0;r&&(!o||i)&&le(t.id,t.sourceType);let a=Te(e.id,{name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled,description:e.description});if(!a)return s({error:"Update failed"});if(o&&(!r||i))try{Pe(a)}catch(l){Te(e.id,{enabled:!1});let d=l instanceof Error?l.message:String(l);return s({error:`Failed to start source with new config: ${d}. Event def has been marked disabled to match runtime state.`})}return s({id:a.id,name:a.name,sourceType:a.sourceType,enabled:a.enabled})}),u("delete_event_def","Delete an Event definition. Stops the runtime source handler (cron/fswatch) first, then deletes the DB row. Templates bound to this event def become orphaned and will not fire.",{id:n.string().uuid().describe("Event def id.")},async e=>{let t=j(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});try{le(t.id,t.sourceType)}catch(o){F.warn({defId:t.id,err:o},"stopEventDefSource failed during delete \u2014 proceeding with row deletion")}let r=Se(e.id);return s({ok:r,id:e.id})}),u("fire_event_def","Fire an Event definition now. For manual defs: creates a real manual event (same as clicking 'Fire now' in the UI). For any source type: with test=true, creates a synthetic test event (source='manual-test-<defId>') that flows through the EventDispatcher \u2014 useful for debugging why a Template bound to the event didn't fire. Payload is optional.",{id:n.string().uuid().describe("Event def id."),test:n.boolean().optional().describe("Test mode. Required (=true) when source type != 'manual'. Default false. In test mode the event does NOT collide with real firings' dedup keys."),payload:n.record(n.string(),n.unknown()).optional().describe("Optional event payload. Must be < 64 KB when JSON-serialized.")},async e=>{let t=j(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});let r=e.test===!0;if(t.sourceType!=="manual"&&!r)return s({error:`Can only directly fire manual event defs; this def has source type '${t.sourceType}'. Pass test=true to dry-run.`});if(e.payload){let o=Buffer.byteLength(JSON.stringify(e.payload),"utf8");if(o>65536)return s({error:`Payload exceeds 64 KB limit (got ${o} bytes)`})}try{let o=r?Ee(t,e.payload):De(t,e.payload);return s({ok:!0,eventId:o.eventId,test:r})}catch(o){let i=o instanceof Error?o.message:String(o);return s({error:i})}}),u("list_event_firings","List recent firings of an Event definition \u2014 for debugging 'why didn't my automation fire' and inspecting event history. Returns id, occurredAt, type, source, dedupKey, confidence, and a truncated payload (500 char cap for display). For full payloads, use REST GET /event-defs/:id/firings.",{eventDefId:n.string().uuid().describe("Event def id. Use list_event_defs to find it."),since:n.string().optional().describe("ISO 8601 start timestamp (inclusive). Omit for unlimited range."),until:n.string().optional().describe("ISO 8601 end timestamp (inclusive)."),limit:n.number().int().positive().max(500).optional().describe("Max rows (default 50, max 500).")},async e=>{let t=j(e.eventDefId);if(!t)return s({error:`Event def '${e.eventDefId}' not found`});let r=Rt({eventDefId:e.eventDefId,since:e.since,until:e.until,limit:e.limit??50}),o=500;return s({eventDefName:t.name,sourceType:t.sourceType,count:r.length,firings:r.map(i=>{let a=JSON.stringify(i.payload);return{id:i.id,occurredAt:i.occurredAt,type:i.type,source:i.source,dedupKey:i.dedupKey,confidence:i.confidence,payloadPreview:a.length>o?a.slice(0,o)+"...[truncated]":a,payloadTruncated:a.length>o}})})}),u("create_skill","Author a Claude Code Skill file under a target Role's workspace. The Skill becomes available next time the Role runs. Preset Roles (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator) require overwrite=true to replace an existing skill \u2014 first-time creation is unrestricted. Returns the written file path.",{roleId:n.string().describe("Role to target. Use list_roles to find it."),skillName:n.string().regex(/^[a-z0-9_][a-z0-9_-]{0,39}$/,"skillName must be 1-40 chars: lowercase letters, digits, underscores, optional hyphen in middle. No leading dot or dash.").describe("Skill directory name (used as the directory under .claude/skills/)."),description:n.string().max(500).describe("One-line description shown to the Role's LLM when choosing a Skill."),instructions:n.string().describe("The skill body: what it does and how to do it."),parameters:n.record(n.string(),n.object({type:n.string().describe("Parameter type name"),description:n.string().describe("Parameter description")})).optional().describe("Named input parameters and their types."),overwrite:n.boolean().optional().describe("Required (=true) to overwrite an existing SKILL.md under a preset Role (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator). First-time skill creation and non-preset Roles do not require this flag.")},async e=>{let{getRole:t}=await import("./roles-KYXNMO5H.js"),{ensureRoleWorkspace:r}=await import("./role-workspace-URSOBCDH.js"),{mkdir:o,writeFile:i}=await import("fs/promises"),{resolve:a}=await import("path"),l=t(e.roleId);if(!l)return s({error:`Role '${e.roleId}' not found`});let d=r(l),m=a(d,".claude","skills",e.skillName);if(Fe(l)){let{existsSync:g}=await import("fs"),b=a(m,"SKILL.md");if(g(b)&&e.overwrite!==!0)return s({error:`Role '${l.name}' is a preset. Skill '${e.skillName}' already exists at ${b}. Pass overwrite=true to replace, or choose a different skillName to add alongside.`,requiresOverwrite:!0,existingPath:b})}let c=a(d,".claude","skills");if(!m.startsWith(c+(process.platform==="win32"?"\\":"/")))return s({error:"Path traversal rejected"});await o(m,{recursive:!0});let h=bn(e),f=a(m,"SKILL.md");return await i(f,h,"utf8"),s({ok:!0,path:f})}),u("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:n.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:n.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-YPNWJOVV.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(o=>({id:o.id,name:o.name,description:o.description,trigger:o.trigger,enabled:o.enabled,rolePreference:o.rolePreference,deliverTo:o.deliverTo,createdAt:o.createdAt})))}),u("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:n.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:n.string().describe("The message content to send (text caption when sending media)"),mediaUrl:n.string().optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:n.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!Ut(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:o}=await import("./outbound-gateway-QRL36F7K.js"),a=await o().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:a.success,channelName:e.channelName,...a.error?{error:a.error}:{}})}),u("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Un,async e=>{let t=be(e.enabled),r=[...ve("active"),...ve("archived")],o=t.map(i=>{let a,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===i.id&&d.source.chatId);return l?.source.chatId?a=l.source.chatId:a=i.config?.userId,{id:i.id,name:i.name,platform:i.platform,status:i.status,chatId:a}});return s({channels:o})}),u("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Ln,async()=>{let e=_(),t=O("running"),r=O("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),u("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",jn,async e=>{let t=I(e.roleId);if(!t||t.status!=="active"){let f=A("active",20,0).filter(g=>g.source!=="system").map(g=>({id:g.id,name:g.name,allowedTools:g.allowedTools??[],capabilitySummary:C(g)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),o;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)o=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(o=new Date(e.runAt).getTime(),isNaN(o))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(o<=r)return s({error:"Scheduled time must be in the future"});let i=10080*60*1e3;if(o-r>i)return s({error:"Schedule exceeds maximum of 7 days"});let a=T(),l=new Date(o).toISOString(),d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0;ye({id:a,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{..._().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:m});let{getBreeEngine:c}=await import("./bree-engine-M5CZ6A62.js"),h=c();return h&&h.scheduleOnceJob(a),s({templateId:a,executeAt:l,prompt:e.prompt})}),u("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:n.string().describe("The template ID returned by schedule_task")},async e=>{let t=B(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});dt(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-M5CZ6A62.js"),o=r();return o&&await o.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),u("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",Fn,async e=>{let t=Ge(),r=te(),o=e.roleId?(()=>{let{getRoleWorkspacePath:i}=(ee(),P(fe)),{getRole:a}=(Z(),P(pe)),{listInstalledPlugins:l}=(ze(),P(Wt)),d=a(e.roleId);if(!d)return[];let m=i(d.name);return l({scope:"project",projectPath:m}).map(c=>c.id)})():[];return s({plugins:r.map(i=>({id:i.id,name:i.name,scope:i.scope,projectPath:i.projectPath,enabled:i.enabled,globalEnabled:t[i.id]??i.enabled,isInstalledInRole:o.includes(i.id),description:i.version?`v${i.version}`:void 0}))})}),u("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",Gn,async e=>{let{getRole:t}=(Z(),P(pe)),{getRoleWorkspacePath:r}=(ee(),P(fe)),o=t(e.roleId);if(!o)return s({error:`Role not found: ${e.roleId}`});let i=r(o.name);try{return Ie(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:i})}catch(a){return s({error:`Failed to install plugin: ${a}`})}}),u("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Vn,async e=>{let{getRole:t}=(Z(),P(pe)),{getRoleWorkspacePath:r}=(ee(),P(fe)),o=t(e.roleId);if(!o)return s({error:`Role not found: ${e.roleId}`});let i=r(o.name);try{return ke(e.pluginId,"project",i),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return s({error:`Failed to uninstall plugin: ${a}`})}}),u("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Wn,async e=>{let t=I(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let o={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return U(e.roleId,{mcpServers:o}),X(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:o})}catch(i){return s({error:`Failed to bind MCP server: ${i}`})}}),u("unbind_mcp_from_role","Remove an MCP server binding from a role.",Bn,async e=>{let t=I(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return U(e.roleId,{mcpServers:r}),X(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(o){return s({error:`Failed to unbind MCP server: ${o}`})}}),u("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",qn,async()=>{let{listTaskTemplates:e}=await import("./task-templates-YPNWJOVV.js"),t=_(),r=A(void 0,100,0),o=be(),i=e(!0,100,0),a=O("running"),l=O("pending"),d=ft(),m=await gt();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let h=ne(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:C(c,h),plugins:h.plugins.map(f=>({name:f.name,skills:f.skills.map(g=>g.name),agents:f.agents.map(g=>g.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:m},registry:Ue(d.platform,m)},channels:{description:"Send/receive messages via connected platforms",connected:o.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:te().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:i.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),u("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",Kn,async e=>{try{return kt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),u("disable_plugin","Disable a globally installed plugin (removes it from all roles).",zn,async e=>{try{return Tt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),u("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Jn,async e=>{try{return Ie(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),u("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Hn,async e=>{try{return ke(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),u("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Yn,async()=>{try{let e=It(),t=te();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),u("list_marketplace_sources","List configured plugin marketplace sources.",Qn,async()=>{let e=Be();return s({sources:e})}),u("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Zn,async e=>{let t=We(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=Ve(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),u("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Xn,async e=>{let{getRole:t}=await import("./roles-KYXNMO5H.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let o=Ke(e.path);return s({roleId:e.roleId,path:e.path,config:o})}catch(o){return s({error:`Failed to scan directory: ${o}`})}}),u("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",er,async e=>{let t=x(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;G(e.taskId,{status:"cancelled"});let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");return o.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),u("view_task_logs","Retrieve step-by-step execution logs for a task.",tr,async e=>{let t=Oe(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),u("delete_role","Delete a role by ID. This removes the role and its workspace.",nr,async e=>I(e.roleId)?(qe(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),u("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",rr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-VDBZZ4KG.js"),r=_(),o={};try{let d=_().server?.port??7100,m=await fetch(`http://127.0.0.1:${d}/config`);m.ok&&(o=await m.json())}catch{}let i=[...e,...t],a=[...t],l={};for(let d of i){let m=d.split("."),c=r;for(let h of m)if(c&&typeof c=="object")c=c[h];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),u("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",or,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-VDBZZ4KG.js"),{setConfigValue:r}=await import("./config-KFPS7IEH.js"),o=$e(e.updates,r);if(e.updates["logging.level"]&&Me(e.updates["logging.level"]),o.updated.length>0){let{serverBus:i}=await import("./server-bus-GEGVMSCA.js");i.emit({type:"config_changed",changes:o.updated.map(a=>({path:a,value:e.updates[a]}))})}return s(o)}),u("list_memories","List memories stored under a specific role.",ir,async e=>{let t=at(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),u("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",sr,async e=>{let t=B(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0||e.autoSelectRole!==void 0||e.requirements!==void 0){let i=t.steps?.length?[...t.steps]:[];i.length===0&&i.push({id:T(),prompt:e.prompt??""});let a=i[0];i[0]={...a,...e.prompt!==void 0?{prompt:e.prompt}:{},...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}},r.steps=i}if(e.triggerCron!==void 0||e.triggerEvent!==void 0||e.triggerType!==void 0||e.eventDefId!==void 0){let i=e.triggerType??(e.triggerEvent?e.triggerEvent.split(":")[0]:e.eventDefId?"event":"cron");if(i==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});r.trigger={type:i,...e.triggerCron!==void 0?{cron:e.triggerCron}:{},...e.triggerEvent!==void 0?{event:e.triggerEvent}:{},...e.eventDefId!==void 0?{eventDefId:e.eventDefId}:{}}}e.roleId!==void 0&&(r.rolePreference=e.roleId);try{lt(e.templateId,r)}catch(i){let{TemplateRoleConfigError:a}=await import("./task-templates-YPNWJOVV.js");if(i instanceof a)return s({code:i.code,error:i.message,failingStepIds:i.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object."});throw i}return s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),u("delete_template","Delete a task template by ID.",ar,async e=>B(e.templateId)?(ct(e.templateId),s({success:!0,templateId:e.templateId})):s({error:`Template not found: ${e.templateId}`})),u("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",lr,async e=>{let t=B(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=_().server?.port??7100,o=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),i=await o.json();return o.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:i}):s({error:`Webhook failed: ${i.code??o.status} \u2014 ${i.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),u("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",dr,async e=>{let t=we(e.enabled);return s({count:t.length,rules:t})}),u("create_delivery_rule","Create a new delivery rule for event-driven result routing.",cr,async e=>{let t=T(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return pt(r),s({success:!0,ruleId:t,rule:r})}),u("delete_delivery_rule","Delete a delivery rule by ID.",ur,async e=>we().find(o=>o.id===e.ruleId)?(mt(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),u("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",pr,async e=>{let t;if(e.roleId)t=Xe(e.roleId);else{let{getDb:r}=await import("./db-PZ2V7UCK.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(i=>({id:i.id,roleId:i.role_id,name:i.name,taskType:i.task_type,createdAt:i.created_at,updatedAt:i.updated_at??void 0,promptTemplate:i.prompt_template??"",alpha:i.alpha,beta:i.beta,totalTrials:i.trials,avgReward:i.total_reward&&i.trials>0?i.total_reward/i.trials:void 0,enabled:i.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),u("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:n.string(),operationId:n.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:n.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=he(e.taskId),r=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return r?(new Q().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),u("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:n.string(),operationId:n.string().optional(),reason:n.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=he(e.taskId),r=e.operationId?t.find(i=>i.id===e.operationId):t.find(i=>i.status==="pending");return r?(new Q().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function Qo(){return Lt.map(e=>e.name).sort().join(",")}function Zo(){return yn({name:"adam-tools",version:"1.0.0",tools:Lt})}export{Q as a,br as b,vr as c,ht as d,It as e,Ie as f,ke as g,kt as h,Tt as i,Dr as j,Rt as k,Dt as l,j as m,se as n,Te as o,Se as p,M as q,De as r,Ee as s,Pe as t,le as u,oo as v,H as w,xe as x,Qo as y,Zo as z};
@@ -1,4 +1,4 @@
1
- import{b as e,d as p}from"./chunk-JAS3TUZX.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
1
+ import{b as e,d as p}from"./chunk-NCFVJCNQ.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
2
2
  INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
3
3
  tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -1,4 +1,4 @@
1
- import{a as p,g as N}from"./chunk-7L2WQM7N.js";import{b as o,d as C}from"./chunk-JAS3TUZX.js";import{b as l,h as g}from"./chunk-WBAPIPST.js";import{c,e as A}from"./chunk-FCV2DPZQ.js";import*as h from"os";import*as y from"path";function u(e){return e.startsWith("~/")||e==="~"?y.join(h.homedir(),e.slice(1)):e}var _=c(()=>{"use strict";g()});function R(e){return w.includes(e)}function S(e){return v[e]}function E(){return w.map(e=>v[e])}function V(e,i=e!=="none"){return E().map(s=>T(s,e,i))}function T(e,i,s=i!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(i!=="sandbox-exec"||!s)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function z(e){if(!e?.length)return;for(let s of e)if(!R(s.id))throw new Error(`Unknown OS capability: ${s.id}`);let i=d(e);if(i?.length){for(let s of i){let t=S(s.id);if(t.status!=="runtime-enforced")throw new Error(`OS capability '${t.label}' is not editable in Role settings`);if(t.supportsTargets){if(!s.targets?.length)throw new Error(`OS capability '${t.label}' requires at least one target bundle id`);for(let n of s.targets)if(!D(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(s.targets?.length)throw new Error(`OS capability '${t.label}' does not accept targets`)}return i}}function d(e){if(!e||e.length===0)return;let i=new Set,s=[];for(let t of e){if(!R(t.id))throw new Error(`Unknown OS capability: ${t.id}`);if(i.has(t.id))continue;i.add(t.id);let n=S(t.id),a={id:t.id};n.supportsTargets&&t.targets?.length&&(a.targets=[...new Set(t.targets.map(r=>r.trim()).filter(Boolean))]),s.push(a)}return s.length>0?s.sort((t,n)=>t.id.localeCompare(n.id)):void 0}function D(e){return x.test(e)}var w,v,x,O=c(()=>{"use strict";w=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],v={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},x=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});var L={};A(L,{createRole:()=>J,deleteRole:()=>U,getRole:()=>P,getRoleByName:()=>I,listRoles:()=>B,updateRole:()=>k,validateAdditionalDirectories:()=>f});import{existsSync as M}from"fs";import{resolve as m}from"path";function f(e,i){for(let s of e){let t=typeof s=="string"?s:s.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let n=m(u(t));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let a of l){let r=m(u(a));if(n.startsWith(r))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${a}'`)}if(i?.length)for(let a of i){let r=m(u(a));if(n.startsWith(r)||r.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${t}' conflicts with '${a}'`)}if(!M(n))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function b(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let i=JSON.parse(e.additional_directories);return Array.isArray(i)?i.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?d(JSON.parse(e.os_capabilities)):void 0}}function J(e){let i=p("defaults.deniedReadPaths")??[...l];e.additionalDirectories&&f(e.additionalDirectories,i),o().prepare(`
1
+ import{a as p,g as N}from"./chunk-G5ESQEXN.js";import{b as o,d as C}from"./chunk-NCFVJCNQ.js";import{b as l,h as g}from"./chunk-WBAPIPST.js";import{c,e as A}from"./chunk-FCV2DPZQ.js";import*as h from"os";import*as y from"path";function u(e){return e.startsWith("~/")||e==="~"?y.join(h.homedir(),e.slice(1)):e}var _=c(()=>{"use strict";g()});function R(e){return w.includes(e)}function S(e){return v[e]}function E(){return w.map(e=>v[e])}function V(e,i=e!=="none"){return E().map(s=>T(s,e,i))}function T(e,i,s=i!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(i!=="sandbox-exec"||!s)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function z(e){if(!e?.length)return;for(let s of e)if(!R(s.id))throw new Error(`Unknown OS capability: ${s.id}`);let i=d(e);if(i?.length){for(let s of i){let t=S(s.id);if(t.status!=="runtime-enforced")throw new Error(`OS capability '${t.label}' is not editable in Role settings`);if(t.supportsTargets){if(!s.targets?.length)throw new Error(`OS capability '${t.label}' requires at least one target bundle id`);for(let n of s.targets)if(!D(n))throw new Error(`Invalid automation target bundle id: ${n}`)}else if(s.targets?.length)throw new Error(`OS capability '${t.label}' does not accept targets`)}return i}}function d(e){if(!e||e.length===0)return;let i=new Set,s=[];for(let t of e){if(!R(t.id))throw new Error(`Unknown OS capability: ${t.id}`);if(i.has(t.id))continue;i.add(t.id);let n=S(t.id),a={id:t.id};n.supportsTargets&&t.targets?.length&&(a.targets=[...new Set(t.targets.map(r=>r.trim()).filter(Boolean))]),s.push(a)}return s.length>0?s.sort((t,n)=>t.id.localeCompare(n.id)):void 0}function D(e){return x.test(e)}var w,v,x,O=c(()=>{"use strict";w=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],v={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},x=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});var L={};A(L,{createRole:()=>J,deleteRole:()=>U,getRole:()=>P,getRoleByName:()=>I,listRoles:()=>B,updateRole:()=>k,validateAdditionalDirectories:()=>f});import{existsSync as M}from"fs";import{resolve as m}from"path";function f(e,i){for(let s of e){let t=typeof s=="string"?s:s.path;if(!t.startsWith("/")&&!t.startsWith("~/")&&t!=="~")throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);let n=m(u(t));if(!n.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${t}' is not absolute`);for(let a of l){let r=m(u(a));if(n.startsWith(r))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${t}' matches '${a}'`)}if(i?.length)for(let a of i){let r=m(u(a));if(n.startsWith(r)||r.startsWith(n))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${t}' conflicts with '${a}'`)}if(!M(n))throw new Error(`additionalDirectories path does not exist: '${t}'`)}}function b(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let i=JSON.parse(e.additional_directories);return Array.isArray(i)?i.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?d(JSON.parse(e.os_capabilities)):void 0}}function J(e){let i=p("defaults.deniedReadPaths")??[...l];e.additionalDirectories&&f(e.additionalDirectories,i),o().prepare(`
2
2
  INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
3
3
  performance_score, preferences, created_at, updated_at,
4
4
  allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
@@ -1,4 +1,4 @@
1
- import{n as y,r as T}from"./chunk-GBTG5B5R.js";import{d as h,h as F}from"./chunk-WBAPIPST.js";import{c as R,h as P}from"./chunk-INNDBLZE.js";import{c as v,e as A}from"./chunk-FCV2DPZQ.js";import{readFileSync as b,writeFileSync as C,existsSync as k}from"fs";import{join as W}from"path";function w(e){let n=W(d(e),".env");if(!k(n))return null;let i=b(n,"utf-8"),t={};for(let o of i.split(`
1
+ import{n as y,r as T}from"./chunk-7ZGSJCX5.js";import{d as h,h as F}from"./chunk-WBAPIPST.js";import{c as R,h as P}from"./chunk-MRTJFYPR.js";import{c as v,e as A}from"./chunk-FCV2DPZQ.js";import{readFileSync as b,writeFileSync as C,existsSync as k}from"fs";import{join as W}from"path";function w(e){let n=W(d(e),".env");if(!k(n))return null;let i=b(n,"utf-8"),t={};for(let o of i.split(`
2
2
  `)){let s=o.trim();if(!s||s.startsWith("#"))continue;let c=s.startsWith("export ")?s.slice(7).trim():s,u=c.indexOf("=");if(u===-1)continue;let f=c.slice(0,u).trim(),r=c.slice(u+1).trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),!(r.includes("$")&&(r=r.replace(/\$\{(\w+)\}|\$(\w+)/g,(p,l,a)=>{let g=l??a;return t[g]??process.env[g]??""}),!r))&&(t[f]=r)}return t}function V(e,n){let i=w(e);if(!i)return n;let t={...n},o=0;for(let[s,c]of Object.entries(i)){if(s.startsWith("ANTHROPIC_")){x.warn({roleName:e,key:s},"Role .env contains ANTHROPIC_* key; ignored (managed globally)");continue}s in t||(t[s]=c,o++)}return o>0&&x.info({roleName:e,seeded:o},"Seeded role envVars from .env file"),Object.keys(t).length>0?t:void 0}function M(e,n){let i=w(e);if(!i)return[];let t=n??{},o=[];for(let[s,c]of Object.entries(i)){if(s.startsWith("ANTHROPIC_"))continue;let u=t[s]??"";u!==c&&o.push({envKey:s,dbValue:u,envValue:c})}for(let[s,c]of Object.entries(t))s in i||o.push({envKey:s,dbValue:c,envValue:""});return o}function N(e,n){let i=W(d(e),".env"),t=n??{},o=[],s=new Set;if(k(i)){let u=b(i,"utf-8");for(let f of u.split(`
3
3
  `)){let r=f.trim();if(!r||r.startsWith("#")){o.push(f);continue}let p=r.startsWith("export ")?r.slice(7).trim():r,l=p.indexOf("=");if(l===-1){o.push(f);continue}let a=p.slice(0,l).trim(),g=r.startsWith("export ")?"export ":"";a in t&&(o.push(`${g}${a}=${t[a]}`),s.add(a))}}let c=0;for(let[u,f]of Object.entries(t)){if(s.has(u)){c++;continue}f&&f.length>0&&(o.push(`${u}=${f}`),c++)}return C(i,o.join(`
4
4
  `)+`
@@ -18,4 +18,4 @@ When summarizing, preserve:
18
18
  - Key decisions made and their rationale
19
19
  - Role assignments and execution outcomes
20
20
  - Channel/session routing context
21
- `),S(m(e,"CLAUDE.md"),t,"utf-8")}function I(e,n,i){let t={};n&&(t.allowedTools=n),S(m(i,".claude","settings.json"),JSON.stringify(t,null,2),"utf-8")}var _,O=v(()=>{"use strict";F();E();T();_=process.env.ADAM_TEST_DIR||h});export{w as a,M as b,N as c,E as d,d as e,K as f,j as g,I as h,U as i,O as j};
21
+ `),S(m(e,"CLAUDE.md"),t,"utf-8")}function I(e,n,i){let t={};n&&(t.allowedTools=n),S(m(i,".claude","settings.json"),JSON.stringify(t,null,2),"utf-8")}var _,O=v(()=>{F();E();T();_=process.env.ADAM_TEST_DIR||h});export{w as a,M as b,N as c,E as d,d as e,K as f,j as g,I as h,U as i,O as j};
@@ -1,4 +1,4 @@
1
- import{a as B}from"./chunk-R4GIIQ7G.js";import{a as C}from"./chunk-2CMR5AG7.js";import{a as L,b as k,c as T,j as $}from"./chunk-C6BOQJJF.js";import{d as I,h as P,i as de}from"./chunk-GBTG5B5R.js";import{b as _,d as se}from"./chunk-JAS3TUZX.js";import{c as D,h as ie}from"./chunk-INNDBLZE.js";import{tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";import{v4 as le}from"uuid";function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var ce={query:a.string().describe("Search query for memory retrieval"),roleId:a.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:a.number().optional().describe("Max results to return (default 5)")},pe={query:a.string().describe("Search query for memory retrieval"),topK:a.number().optional().describe("Max results to return (default 5)")},me={id:a.string().optional().describe("Memory ID to update. Omit to create new."),roleId:a.string().describe("Role ID to save memory under"),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ue={id:a.string().optional().describe("Memory ID to update. Omit to create new."),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:a.string().describe("Memory ID to delete")};async function j(t,e){let r=t??e.roleId,n=e.topK??5,i=await B(r,e.query,{topK:n});return l({results:i.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function F(t,e){let r=t??e.roleId;if(!r)return l({error:"roleId is required"});let n,i=!0;try{n=await C(e.content)}catch{i=!1}if(e.id){if(!k(e.id))return l({error:`Memory ${e.id} not found`});let v=T(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return l({id:e.id,action:"updated",success:v,embeddingUpdated:i})}let o=`mem-${le().slice(0,8)}`,s=Date.now();return L({id:o,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:s,lastAccessed:s,retrievedCount:0,tier:e.tier??"episodic"}),l({id:o,action:"created",success:!0,embeddingUpdated:i})}async function K(t,e){if(t){let r=k(e.id);if(!r)return l({error:`Memory ${e.id} not found`});if(r.roleId!==t)return l({error:`Memory ${e.id} does not belong to this role`})}return $(e.id),l({id:e.id,deleted:!0})}function Ue(t){return t?[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",pe,async e=>j(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.",ue,async e=>F(t,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(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=>j(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.",me,async e=>F(void 0,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}import{accessSync as q,constants as H}from"fs";import{accessSync as fe,constants as ye,existsSync as U,realpathSync as be}from"fs";import{join as E}from"path";import{spawn as he}from"child_process";import{execFileSync as ge}from"child_process";var u=null;function f(){if(u)return u;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=E(t,"landlock-exec","landlock-exec");if(U(e))return u=e,e;let r=process.env.PATH?.split(":").find(n=>U(E(n,"landlock-exec")));return r?(u=E(r,"landlock-exec"),u):e}var y=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{fe(f(),ye.X_OK)}catch{return!1}try{return ge(f(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],i=[];for(let o of e.visiblePaths??[]){let s=o.mode==="rw"?"--rw":"--ro",d;try{d=be(o.path)}catch{d=o.path}i.push(s,d),d!==o.path&&i.push(s,o.path)}return i.push("--",r,...n),he(f(),i,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function G(){if(process.platform==="linux")try{return q(f(),H.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return q("/usr/bin/sandbox-exec",H.X_OK),"sandbox-exec"}catch{return"none"}return"none"}ie();import{spawn as _e}from"child_process";import{readFileSync as z,writeFileSync as Pe,mkdtempSync as ke,realpathSync as A,rmSync as Ee}from"fs";import{join as c}from"path";import{tmpdir as Ae}from"os";de();var ve=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],xe=["com.apple.coreservices.appleevents"];function Se(t){if(!I.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function V(t,e){return P(t)?.find(r=>r.id===e)}function we(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...xe.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)Se(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
1
+ import{a as B}from"./chunk-52PR7XTN.js";import{a as C}from"./chunk-SWP2JC54.js";import{a as L,b as k,c as T,j as $}from"./chunk-YHVYX3F4.js";import{d as I,h as P,i as de}from"./chunk-7ZGSJCX5.js";import{b as _,d as se}from"./chunk-NCFVJCNQ.js";import{c as D,h as ie}from"./chunk-MRTJFYPR.js";import{tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";import{v4 as le}from"uuid";function l(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var ce={query:a.string().describe("Search query for memory retrieval"),roleId:a.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:a.number().optional().describe("Max results to return (default 5)")},pe={query:a.string().describe("Search query for memory retrieval"),topK:a.number().optional().describe("Max results to return (default 5)")},me={id:a.string().optional().describe("Memory ID to update. Omit to create new."),roleId:a.string().describe("Role ID to save memory under"),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ue={id:a.string().optional().describe("Memory ID to update. Omit to create new."),content:a.string().describe("Memory content text"),type:a.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:a.array(a.string()).optional().describe("Keywords for BM25 search"),importance:a.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:a.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:a.string().describe("Memory ID to delete")};async function j(t,e){let r=t??e.roleId,n=e.topK??5,i=await B(r,e.query,{topK:n});return l({results:i.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function F(t,e){let r=t??e.roleId;if(!r)return l({error:"roleId is required"});let n,i=!0;try{n=await C(e.content)}catch{i=!1}if(e.id){if(!k(e.id))return l({error:`Memory ${e.id} not found`});let v=T(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return l({id:e.id,action:"updated",success:v,embeddingUpdated:i})}let o=`mem-${le().slice(0,8)}`,s=Date.now();return L({id:o,roleId:r,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:s,lastAccessed:s,retrievedCount:0,tier:e.tier??"episodic"}),l({id:o,action:"created",success:!0,embeddingUpdated:i})}async function K(t,e){if(t){let r=k(e.id);if(!r)return l({error:`Memory ${e.id} not found`});if(r.roleId!==t)return l({error:`Memory ${e.id} does not belong to this role`})}return $(e.id),l({id:e.id,deleted:!0})}function Ue(t){return t?[p("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",pe,async e=>j(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.",ue,async e=>F(t,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(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=>j(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.",me,async e=>F(void 0,e)),p("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}import{accessSync as q,constants as H}from"fs";import{accessSync as fe,constants as ye,existsSync as U,realpathSync as be}from"fs";import{join as E}from"path";import{spawn as he}from"child_process";import{execFileSync as ge}from"child_process";var u=null;function f(){if(u)return u;let t=typeof import.meta.dirname=="string"?import.meta.dirname:__dirname??".",e=E(t,"landlock-exec","landlock-exec");if(U(e))return u=e,e;let r=process.env.PATH?.split(":").find(n=>U(E(n,"landlock-exec")));return r?(u=E(r,"landlock-exec"),u):e}var y=class{platform="landlock";async isAvailable(){if(process.platform!=="linux")return!1;try{fe(f(),ye.X_OK)}catch{return!1}try{return ge(f(),["--check"],{timeout:5e3,stdio:["ignore","pipe","pipe"]}),!0}catch{return!1}}spawn(e){let r=e.command??"node",n=e.args??[],i=[];for(let o of e.visiblePaths??[]){let s=o.mode==="rw"?"--rw":"--ro",d;try{d=be(o.path)}catch{d=o.path}i.push(s,d),d!==o.path&&i.push(s,o.path)}return i.push("--",r,...n),he(f(),i,{cwd:e.cwd,env:e.env,stdio:"pipe",signal:e.signal})}};function G(){if(process.platform==="linux")try{return q(f(),H.X_OK),"landlock"}catch{return"none"}if(process.platform==="darwin")try{return q("/usr/bin/sandbox-exec",H.X_OK),"sandbox-exec"}catch{return"none"}return"none"}ie();import{spawn as _e}from"child_process";import{readFileSync as z,writeFileSync as Pe,mkdtempSync as ke,realpathSync as A,rmSync as Ee}from"fs";import{join as c}from"path";import{tmpdir as Ae}from"os";de();var ve=["com.apple.Accessibility","com.apple.CoreGraphics","com.apple.SpeakSelection","com.apple.TimeMachine","com.apple.assistant","com.apple.assistant.backedup","com.apple.assistant.support"],xe=["com.apple.coreservices.appleevents"];function Se(t){if(!I.test(t))throw new Error(`Invalid bundle id for SBPL appleevent destination: ${t}`)}function V(t,e){return P(t)?.find(r=>r.id===e)}function we(t){if(!t)return"";let e=["","; ===== Role OS capability: Automation =====","(allow lsopen)","(allow mach-lookup",...xe.map(n=>` (global-name "${n}")`),")"],r=t.targets??[];for(let n of r)Se(n),e.push(`(allow appleevent-send (appleevent-destination "${n}"))`);return e.join(`
2
2
  `)}function Re(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",...ve.map(r=>` (preference-domain "${r}")`),")"].join(`
3
3
  `):""}function X(t){let e=P(t);return e?.length?[we(V(e,"automation")),Re(V(e,"accessibility"))].filter(Boolean).join(`
4
4
  `):""}var Y=D("sandbox-macos"),J="/usr/bin/sandbox-exec";function Oe(){let t=[c(typeof import.meta.dirname=="string"?import.meta.dirname:".","profiles","role-sandbox.sb"),c(typeof import.meta.dirname=="string"?import.meta.dirname:".","..","src","sandbox","profiles","role-sandbox.sb"),c(process.cwd(),"src","sandbox","profiles","role-sandbox.sb")];for(let e of t)try{return z(e,"utf-8"),e}catch{}return t[t.length-1]}var Me=Oe();function b(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 De(t){let e=[`
@@ -1,4 +1,4 @@
1
- import{b as He,c as Qe,d as N,e as et}from"./chunk-5XUR3M23.js";import{a as pe,d as Ke,e as me}from"./chunk-H54ZXA26.js";import{b as fe,c as Ye,d as Ge,e as Xe,f as Ze}from"./chunk-YHVFZB6Q.js";import{j as je}from"./chunk-VRJ7R766.js";import{a as Le,b as $e}from"./chunk-Y3AMO6WC.js";import{b as B,c as O,d as J,f as Oe}from"./chunk-ISZJV72D.js";import{a as U,e as tt}from"./chunk-5S6BMWD2.js";import{a as Ve}from"./chunk-DZEVMYPB.js";import{e as G,f as We,j as ze}from"./chunk-QWCRZDZS.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as Fe}from"./chunk-QVKI7H7W.js";import{b as Je}from"./chunk-R4GIIQ7G.js";import{b as qe}from"./chunk-T33BLZV2.js";import{d as z,i as Be}from"./chunk-GSMC3VUM.js";import{a as Y,b as Ne,l as R,n as L,o as ue,r as $}from"./chunk-GBTG5B5R.js";import{a as Ue,g as Ft}from"./chunk-7L2WQM7N.js";import{b as _,d as q}from"./chunk-JAS3TUZX.js";import{d as le,h as jt}from"./chunk-WBAPIPST.js";import{c as b,h as P}from"./chunk-INNDBLZE.js";q();function Kt(e){return{id:e.id,roleId:e.role_id,taskId:e.task_id,scores:JSON.parse(e.score_json),emaScore:e.ema_score,createdAt:e.created_at}}function ot(e){_().prepare(`
1
+ import{b as He,c as Qe,d as N,e as et}from"./chunk-DWRYIN5N.js";import{a as U,e as tt}from"./chunk-TSPQ44HT.js";import{a as pe,d as Ke,e as me}from"./chunk-TNL2LZB7.js";import{b as Je}from"./chunk-52PR7XTN.js";import{b as fe,c as Ye,d as Ge,e as Xe,f as Ze}from"./chunk-N4ES7TCL.js";import{j as je}from"./chunk-3LY6PD6A.js";import{a as Le,b as $e}from"./chunk-7446ZS6D.js";import{b as B,c as O,d as J,f as Oe}from"./chunk-I7ZZKPHE.js";import{a as Ve}from"./chunk-MJSSCKMB.js";import{e as G,f as We,j as ze}from"./chunk-DBP7GPWG.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as Fe}from"./chunk-RLJYEEQC.js";import{b as qe}from"./chunk-T33BLZV2.js";import{d as z,i as Be}from"./chunk-GSMC3VUM.js";import{a as Y,b as Ne,l as R,n as L,o as ue,r as $}from"./chunk-7ZGSJCX5.js";import{a as Ue,g as Ft}from"./chunk-G5ESQEXN.js";import{b as _,d as q}from"./chunk-NCFVJCNQ.js";import{d as le,h as jt}from"./chunk-WBAPIPST.js";import{c as b,h as P}from"./chunk-MRTJFYPR.js";q();function Kt(e){return{id:e.id,roleId:e.role_id,taskId:e.task_id,scores:JSON.parse(e.score_json),emaScore:e.ema_score,createdAt:e.created_at}}function ot(e){_().prepare(`
2
2
  INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
3
3
  VALUES (?, ?, ?, ?, ?, ?)
4
4
  `).run(e.id,e.roleId,e.taskId,JSON.stringify(e.scores),e.emaScore,e.createdAt)}function X(e,t=50){return _().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(e,t).map(Kt)}function rt(e){return _().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(e)?.ema_score}function nt(e){let r=_().prepare(`
@@ -57,11 +57,11 @@ ${i}
57
57
  - Report completion with a clear result summary
58
58
  - If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
59
59
  - If a tool is unavailable, state it clearly in the result rather than guessing
60
- `}import{isAbsolute as Zt,relative as Qt,resolve as eo}from"path";Ne();P();var to=new Set(["Read","Glob","Grep","LSP"]),oo=new Set(["Edit","Write","NotebookEdit"]);function ge(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function he(e){return eo(Y(e))}function pt(e,t){return t.some(r=>{let i=he(r),s=Qt(i,e);return s===""||!s.startsWith("..")&&!Zt(s)})}function mt(e,t,r){return async(i,s,{agentID:n,blockedPath:o})=>{if(o){let c=he(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=he(d);if(pt(c,[u]))return ro.warn({toolName:i,blockedPath:o,agentID:n,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${o} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&pt(c,r.roleScope)?{behavior:"allow",updatedInput:s}:t?await t(i,s,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(to.has(i))return{behavior:"allow",updatedInput:s};if(oo.has(i))return{behavior:"allow",updatedInput:s};let a=e(n??"");if(i==="Bash"&&a){let c=s.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(ge(d).test(c))return{behavior:"allow",updatedInput:s}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(ge(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(i))return{behavior:"deny",message:`Tool ${i} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=i==="Bash"?s.command??"":`${i} ${JSON.stringify(s)}`;for(let d of a.approvalRequired)try{if(ge(d).test(c))return await t(i,s,d,n)}catch{}}return{behavior:"allow",updatedInput:s}}}var ro=b("manager");function ft(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,i=e.roleId==="role-chat-manager";if(!i&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-QMYJPBAE.js"),n=e.taskPrompt||"role context and recent interactions",o=i?["semantic","working"]:["semantic","episodic"],a=await s(e.roleId,n,o,{topK:5});if(a.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
60
+ `}import{isAbsolute as Zt,relative as Qt,resolve as eo}from"path";Ne();P();var to=new Set(["Read","Glob","Grep","LSP"]),oo=new Set(["Edit","Write","NotebookEdit"]);function ge(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${t}$`)}function he(e){return eo(Y(e))}function pt(e,t){return t.some(r=>{let i=he(r),s=Qt(i,e);return s===""||!s.startsWith("..")&&!Zt(s)})}function mt(e,t,r){return async(i,s,{agentID:n,blockedPath:o})=>{if(o){let c=he(o);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let u=he(d);if(pt(c,[u]))return ro.warn({toolName:i,blockedPath:o,agentID:n,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${o} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&pt(c,r.roleScope)?{behavior:"allow",updatedInput:s}:t?await t(i,s,`blockedPath:${o}`,n):{behavior:"deny",message:`Access denied: ${o} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(to.has(i))return{behavior:"allow",updatedInput:s};if(oo.has(i))return{behavior:"allow",updatedInput:s};let a=e(n??"");if(i==="Bash"&&a){let c=s.command??"";if(a.allowedBashPatterns?.length)for(let d of a.allowedBashPatterns)try{if(ge(d).test(c))return{behavior:"allow",updatedInput:s}}catch{}if(a.deniedBashPatterns?.length)for(let d of a.deniedBashPatterns)try{if(ge(d).test(c))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(a?.disallowedTools?.includes(i))return{behavior:"deny",message:`Tool ${i} is not allowed for this role.`};if(t&&a?.approvalRequired?.length){let c=i==="Bash"?s.command??"":`${i} ${JSON.stringify(s)}`;for(let d of a.approvalRequired)try{if(ge(d).test(c))return await t(i,s,d,n)}catch{}}return{behavior:"allow",updatedInput:s}}}var ro=b("manager");function ft(e){return{SessionStart:[{hooks:[async t=>{if(!e.roleId)return{};let r=t.source,i=e.roleId==="role-chat-manager";if(!i&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-M5ADGITG.js"),n=e.taskPrompt||"role context and recent interactions",o=i?["semantic","working"]:["semantic","episodic"],a=await s(e.roleId,n,o,{topK:5});if(a.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
61
61
  ${a.map(u=>`- [${u.tier??"episodic"}] ${u.content}`).join(`
62
62
  `)}
63
63
 
64
- `}}}catch{}return{}}]}],SubagentStart:[{hooks:[async t=>{let r=e.roleId??t.agent_id;if(!r)return{};try{let i=e.taskPrompt||"role context",s=await Je(i,r,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:i}=await import("./memories-ZII5QSTJ.js"),{getDb:s}=await import("./db-YUYXVV3A.js"),n=t.transcript;if(!n||n.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(e.currentTaskId))return{};let a=`[Task ${e.currentTaskId} reasoning] ${n.slice(0,3e3)}`;i({id:`session-${Date.now()}`,roleId:e.roleId??r,type:"thought",content:a,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:e.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async t=>{if(!e.currentTaskId)return{};let r=t.tool_name,i=t.tool_input,s=t.tool_response,n=typeof s=="string"?s:JSON.stringify(s??"");try{Le({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(i??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:i,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:i}=await import("./memories-ZII5QSTJ.js");i({id:`compact-${Date.now()}`,roleId:e.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}$();ze();jt();P();q();import{randomUUID as no}from"crypto";function gt(e,t,r){let s=_().prepare(`
64
+ `}}}catch{}return{}}]}],SubagentStart:[{hooks:[async t=>{let r=e.roleId??t.agent_id;if(!r)return{};try{let i=e.taskPrompt||"role context",s=await Je(i,r,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async t=>{let r=t.agent_id;if(!r||!e.currentTaskId)return{};try{let{createMemory:i}=await import("./memories-QGMRSBJJ.js"),{getDb:s}=await import("./db-PZ2V7UCK.js"),n=t.transcript;if(!n||n.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(e.currentTaskId))return{};let a=`[Task ${e.currentTaskId} reasoning] ${n.slice(0,3e3)}`;i({id:`session-${Date.now()}`,roleId:e.roleId??r,type:"thought",content:a,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:e.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async t=>{if(!e.currentTaskId)return{};let r=t.tool_name,i=t.tool_input,s=t.tool_response,n=typeof s=="string"?s:JSON.stringify(s??"");try{Le({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:e.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(i??{})} \u2192 ${n.slice(0,200)}`,toolName:r,toolInput:i,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async t=>{let r=t.compact_summary;if(!r)return{};try{let{createMemory:i}=await import("./memories-QGMRSBJJ.js");i({id:`compact-${Date.now()}`,roleId:e.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}$();ze();jt();P();q();import{randomUUID as no}from"crypto";function gt(e,t,r){let s=_().prepare(`
65
65
  INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
66
66
  VALUES (?, ?, ?, ?, ?, ?)
67
67
  `),n=Date.now();for(let o of t){let a=o.split("/").pop()??o;s.run(no(),e,o,a,r??null,n)}}function Xo(e){return _().prepare(`
@@ -94,6 +94,6 @@ ${a.map(u=>`- [${u.tier??"episodic"}] ${u.content}`).join(`
94
94
  size_bytes, outcome, error_reason
95
95
  )
96
96
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
97
- `).run(e.timestamp,e.taskId??null,e.roleId??null,e.executionId,e.stepId??null,e.tool,e.artifactKey??null,e.artifactId??null,e.sizeBytes??null,e.outcome,e.errorReason??null)}catch(t){io.error({err:t,entry:e},"Failed to write artifact access log")}}var ao=/^[A-Za-z0-9._-]{1,256}$/,co=/^[A-Za-z0-9._-]{1,128}$/,kt=256*1024,lo=/^[a-z]+\/[a-z0-9.+-]+$/;async function uo(e){let{listChannels:t}=await import("./channels-HYSB2EEK.js"),r=t(),{listSessions:i}=await import("./session-manager-GRJ3FV3L.js"),s=[...i("active"),...i("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=s.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:a}}function f(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return ao.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function we(e){return co.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function wt(e,t){let r=e?R(e):void 0,i=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=B(t);if(!n)return{error:`task not found: ${t}`};if(!n.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!n.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=n.roleId??e;if(!o)return{error:"this workflow task has no role context"};let a=R(o);return a?{executionId:n.parentId,stepId:n.stepId,roleId:o,roleWorkspacePath:G(a.name),taskId:t}:{error:`role not found: ${o}`}},s=[...Qe(e),A("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-HYSB2EEK.js"),o=n();return f({channels:o.map(a=>({id:a.id,name:a.name,enabled:a.enabled,type:a.config?.type??"unknown"}))})}),A("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:v.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:v.string().describe("The message content to send")},async n=>{if(r?.allowedChannels!==void 0){if(r.allowedChannels.length===0)return f({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return f({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await uo(n.channelName);if(!o)return f({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-6K6P2BEH.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return f({success:d.success,channelName:n.channelName})}),A("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:v.string(),value:v.unknown()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>kt){let l=`Artifact JSON exceeds ${kt} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,sizeBytes:d,outcome:"denied",errorReason:l}),f({error:l})}let u=yt();return Ie({id:u,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"json",value:n.value,sizeBytes:d,createdAt:Date.now()}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,artifactId:u,sizeBytes:d,outcome:"success"}),f({success:!0,artifactId:u,sizeBytes:d})}catch(c){let d=c instanceof Error?c.message:String(c);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"error",errorReason:d}),f({error:d})}}),A("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:v.string(),key:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"denied",errorReason:l}),f({error:l})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"success"}),f({value:u.value,sizeBytes:u.sizeBytes})}),A("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:v.string(),sourcePath:v.string(),mime:v.string().optional(),cleanup:v.boolean().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});if(n.mime&&!lo.test(n.mime)){let l=`Invalid MIME type: ${n.mime}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:l}),f({error:l})}try{fe(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let c=yt(),d=null,u=!1;try{let l=Ye({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,Ie({id:c,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"file",blobPath:d,mime:n.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),u=!0,n.cleanup===!0&&Ge(n.sourcePath),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{It(c)}catch{}if(d)try{Ze(d)}catch{}let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,outcome:"error",errorReason:g}),f({error:g})}}),A("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:v.string(),key:v.string(),destPath:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});try{fe(n.destPath,o.roleWorkspacePath,!1)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="file"||!u.blobPath){let l="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"denied",errorReason:l}),f({error:l})}try{let l=Xe({blobPath:u.blobPath,destPath:n.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"error",errorReason:g}),f({error:g})}}),A("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:v.string().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=n.stepId?we(n.stepId):null;if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:a}),f({error:a});let c=ke(o.executionId,n.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:c.length,outcome:"success"}),f({artifacts:c.map(d=>({id:d.id,stepId:d.stepId,key:d.key,kind:d.kind,sizeBytes:d.sizeBytes,mime:d.mime,createdAt:d.createdAt}))})})];return so({name:"execution-tools",version:"1.0.0",tools:s})}Ft();Ne();import{realpathSync as mo}from"fs";var w=b("execution"),bt=new Set;async function fo(e,t){if(t&&bt.has(t))return w.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=_t(),i={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return pe({id:r,taskId:e,plan:i,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:i}),w.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(s=>{let o=setTimeout(()=>{c(),me(r,"denied"),w.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),s(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(w.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&bt.add(t),s(!0)):(w.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),s(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let i=Date.now(),s,n,o;O(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),w.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.config.executionProfile;if(!a){let m=t.roleId?R(t.roleId):void 0;if(m){w.info({taskId:t.id,roleId:t.roleId},"Lazy-backfilled executionProfile from live Role"),a=m;let h=B(t.id);h&&O(t.id,{config:{...h.config,executionProfile:m}})}}let c=le;a&&(We(a),c=G(a.name));let d={taskId:t.id,prompt:t.prompt,roleName:a?.name,roleCagPrompt:a?.cagPrompt,allowedTools:a?.allowedTools,cwd:c,workflowStep:t.parentId&&t.stepId?{executionId:t.parentId,stepId:t.stepId}:void 0},u=ut(d),l=ft({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),g=t.config.approvalTimeout??300,E=async(m,h,k,D)=>{let x=_t(),Ce=He(D??t.roleId,t.prompt,"medium");if(Ce)return w.info({operationId:x,ruleId:Ce.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ae={steps:[{index:0,description:`${m}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[m],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return pe({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ae,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ae}),w.info({taskId:t.id,operationId:x,toolName:m,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(ce=>{let zt=setTimeout(()=>{Me(),me(x,"denied"),w.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),ce({behavior:"deny",message:`Operation timed out after ${g}s. Auto-denied. Try a safer alternative that does not require approval.`})},g*1e3),De=M=>{if(M.planId===x)if(Me(),M.decision==="allow")w.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),ce({behavior:"allow",updatedInput:h});else{let Vt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";w.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),ce({behavior:"deny",message:Vt})}},Me=()=>{clearTimeout(zt),y.off("plan_approval_decision",De)};y.on("plan_approval_decision",De)})},C=(Ue("defaults.deniedReadPaths")??[]).map(m=>{let h=Y(m);try{return mo(h)}catch{return h}}),p=a,K=p?.additionalDirectories??[],se=p?je(p):[],ve=[...K.map(m=>m.path)].filter((m,h,k)=>k.indexOf(m)===h),Dt=mt(m=>({disallowedTools:p?.disallowedTools,approvalRequired:p?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:p?.allowedBashPatterns,deniedBashPatterns:p?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...ve]}),Mt=Be({roleEnvVars:p?.envVars,taskEnv:t.config.env}),Bt=t.config.maxBudgetUsd??z().defaults.maxBudgetUsd,Ot=t.config.maxTurns??100,Lt=wt(t.roleId??"",t.id),$t=p?.mcpServers??{},Nt=t.config.mcpServers??{},Ut={...$t,...Nt,"execution-tools":Lt},ae=[{path:c,mode:"rw"}];t.roleId===Ve&&ae.push({path:le,mode:"ro"});for(let m of K)ae.push({path:m.path,mode:m.mode??"rw"});let Se=N();if(Se.platform==="none"&&!await fo(t.id,a?.name))return O(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Te=p?.permissionMode??"default",Wt=po({prompt:t.prompt,options:{cwd:c,additionalDirectories:ve,systemPrompt:u,maxTurns:Ot,maxBudgetUsd:Bt,allowedTools:p?.allowedTools,model:p?.model,mcpServers:Ut,settingSources:p?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:Dt,env:Mt,plugins:se.map(m=>({type:"local",path:m})),permissionMode:Te,...Te==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:m=>{let h=Se.spawn({command:m.command,args:m.args,cwd:m.cwd,env:m.env,signal:m.signal,visiblePaths:ae,deniedReadPaths:C,osCapabilities:p?.osCapabilities}),k=h;k.pid&&(xt(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>Rt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(w.error({taskId:t.id,roleId:t.roleId,exitCode:x,stderr:D.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:t.roleId??"unknown",taskId:t.id,path:c,operation:`sandbox_init_failure:exit_${x}`,timestamp:Date.now()}))}),h},stderr:m=>{m.trim()&&w.debug({stderr:m.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),H="",Ee=0,Pe=()=>{w.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Pe);try{for await(let m of Wt){let h=m;if(w.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(H=h.result),h.type==="result"){Ee++,typeof h.total_cost_usd=="number"&&(n=h.total_cost_usd);let k=h.usage;k?.input_tokens!==void 0&&k?.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}if(h.token_usage){let k=h.token_usage;k.input_tokens!==void 0&&k.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Pe)}o=Ee;let de=Date.now()-i;return O(t.id,{status:"completed",result:H,completedAt:Date.now(),costUsd:n,tokenUsage:s,numTurns:o,totalDurationMs:de}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:H}),se.length>0&&gt(t.id,se,t.roleId),w.info({taskId:t.id,durationMs:de,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:H,costUsd:n,tokenUsage:s,numTurns:o,durationMs:de}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-i;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&w.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),O(t.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:d}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:t.id,error:c}),w.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=b("execution-pool"),be=new Map;function xt(e,t,r){be.set(e,{roleId:t,taskId:r})}function Rt(e){be.delete(e)}function _e(e){return be.get(e)}var vt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(i,s)=>({index:s,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",i=>{this.onTaskCreated(i.taskId)}),y.on("task_status_change",i=>{i.newStatus==="pending"&&this.pickupPendingTasks()});let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),S.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let t of this.slots)t.abortController&&(t.abortController.abort(),t.taskId=null,t.abortController=null);S.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(t){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let t=this.slots.find(a=>a.taskId===null);if(!t){S.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let s=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=s.id,t.abortController=new AbortController;let n=t.index,o=s.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let i=this.slots[r];if(!i)return;let s="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,i.abortController?.signal);s=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{i.taskId=null,i.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:s}),this.emitSlotChange(),this.runPostCompletion(t.id,t.roleId).catch(n=>{S.error({taskId:t.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let t=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let i=qe();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Oe(i)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:i}=await import("./memory-extractor-DIYJFBCI.js"),s=await i(t,r);s>0&&S.debug({taskId:t,roleId:r,memoriesStored:s},"Post-completion: memories extracted")}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: memory extraction failed")}try{let{processTaskReview:i}=await import("./learner-IJN6B7KV.js");await i(t)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:i}=await import("./audit-manager-YCJT2WP5.js");i(t,r)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(i=>i.taskId!==null).length,r=J("pending");return{active:t,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(t){let r=this.slots.find(i=>i.taskId===t);r&&(S.warn({taskId:t,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};P();var T=b("audit"),go="sandbox_violation",V=new Map,xe=1440*60*1e3,ne=[],ho=100;function Re(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let i=Date.now()-xe;if(r.timestamps=r.timestamps.filter(s=>s>=i),V.set(t,r),r.count%100===0)for(let[s,n]of V.entries()){let o=Date.now()-xe;n.timestamps.filter(a=>a>=o).length===0&&V.delete(s)}ne.push(e),ne.length>ho&&ne.shift();try{Fe({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:e.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:go,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(s){T.error({error:s},"Failed to record violation to delivery_log")}try{let s=R(e.roleId);U({timestamp:e.timestamp,oldRules:"sandbox_violation",newRules:`${e.operation} on ${e.path}`,diff:`Sandbox violation: ${e.operation} on ${e.path} (taskId=${e.taskId??"unknown"})`,roleId:e.roleId,source:"audit"})}catch(s){T.error({error:s},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp})}async function Pt(){let e=N();if(e.platform==="none")return T.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await e.isAvailable())return T.warn({platform:e.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return e.platform==="sandbox-exec"?r=Io():e.platform==="landlock"&&(r=await yo()),()=>{if(r){let i=r;r=null,i.kill("SIGTERM");let s=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},2e3);i.on("exit",()=>clearTimeout(s))}T.info("Violation watcher stopped")}}function Io(){let e=Et("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return e.stdout?.on("data",t=>{let r=t.toString().split(`
97
+ `).run(e.timestamp,e.taskId??null,e.roleId??null,e.executionId,e.stepId??null,e.tool,e.artifactKey??null,e.artifactId??null,e.sizeBytes??null,e.outcome,e.errorReason??null)}catch(t){io.error({err:t,entry:e},"Failed to write artifact access log")}}var ao=/^[A-Za-z0-9._-]{1,256}$/,co=/^[A-Za-z0-9._-]{1,128}$/,kt=256*1024,lo=/^[a-z]+\/[a-z0-9.+-]+$/;async function uo(e){let{listChannels:t}=await import("./channels-J4STJ4X2.js"),r=t(),{listSessions:i}=await import("./session-manager-LZ77OT7A.js"),s=[...i("active"),...i("archived")],n=r.find(c=>c.name.toLowerCase().includes(e.toLowerCase()));if(!n)return null;let a=s.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:a}}function f(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}function te(e){return ao.test(e)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function we(e){return co.test(e)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function wt(e,t){let r=e?R(e):void 0,i=async()=>{if(!t)return{error:"artifact tools require a task context"};let n=B(t);if(!n)return{error:`task not found: ${t}`};if(!n.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!n.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=n.roleId??e;if(!o)return{error:"this workflow task has no role context"};let a=R(o);return a?{executionId:n.parentId,stepId:n.stepId,roleId:o,roleWorkspacePath:G(a.name),taskId:t}:{error:`role not found: ${o}`}},s=[...Qe(e),A("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:n}=await import("./channels-J4STJ4X2.js"),o=n();return f({channels:o.map(a=>({id:a.id,name:a.name,enabled:a.enabled,type:a.config?.type??"unknown"}))})}),A("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:v.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:v.string().describe("The message content to send")},async n=>{if(r?.allowedChannels!==void 0){if(r.allowedChannels.length===0)return f({error:"This role is not allowed to send to any channels"});if(!r.allowedChannels.some(l=>l.toLowerCase()===n.channelName.toLowerCase()))return f({error:`Channel "${n.channelName}" is not in the allowed channels list for this role`})}let o=await uo(n.channelName);if(!o)return f({error:`Channel "${n.channelName}" not found or has no chatId available`});let{getOutboundGateway:a}=await import("./outbound-gateway-QRL36F7K.js"),d=await a().send({channelId:o.channelId,chatId:o.chatId,content:n.message,messageType:"reply"});return f({success:d.success,channelName:n.channelName})}),A("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:v.string(),value:v.unknown()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});try{let c=JSON.stringify(n.value),d=Buffer.byteLength(c,"utf8");if(d>kt){let l=`Artifact JSON exceeds ${kt} bytes`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,sizeBytes:d,outcome:"denied",errorReason:l}),f({error:l})}let u=yt();return Ie({id:u,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"json",value:n.value,sizeBytes:d,createdAt:Date.now()}),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,artifactId:u,sizeBytes:d,outcome:"success"}),f({success:!0,artifactId:u,sizeBytes:d})}catch(c){let d=c instanceof Error?c.message:String(c);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:n.key,outcome:"error",errorReason:d}),f({error:d})}}),A("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:v.string(),key:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"denied",errorReason:l}),f({error:l})}return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:n.key,artifactId:u.id,sizeBytes:u.sizeBytes,outcome:"success"}),f({value:u.value,sizeBytes:u.sizeBytes})}),A("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:v.string(),sourcePath:v.string(),mime:v.string().optional(),cleanup:v.boolean().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=te(n.key);if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:a}),f({error:a});if(n.mime&&!lo.test(n.mime)){let l=`Invalid MIME type: ${n.mime}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:l}),f({error:l})}try{fe(n.sourcePath,o.roleWorkspacePath,!0)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let c=yt(),d=null,u=!1;try{let l=Ye({executionId:o.executionId,artifactId:c,sourcePath:n.sourcePath});return d=l.blobPath,Ie({id:c,executionId:o.executionId,stepId:o.stepId,key:n.key,kind:"file",blobPath:d,mime:n.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),u=!0,n.cleanup===!0&&Ge(n.sourcePath),I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,artifactId:c,sizeBytes:l.sizeBytes})}catch(l){if(u)try{It(c)}catch{}if(d)try{Ze(d)}catch{}let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:n.key,artifactId:c,outcome:"error",errorReason:g}),f({error:g})}}),A("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:v.string(),key:v.string(),destPath:v.string()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=we(n.stepId),c=te(n.key),d=a??c;if(d)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:d}),f({error:d});try{fe(n.destPath,o.roleWorkspacePath,!1)}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"denied",errorReason:g}),f({error:g})}let u=ye(o.executionId,n.stepId,n.key);if(!u){let l=`no artifact at ${n.stepId}/${n.key}`;return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,outcome:"error",errorReason:l}),f({error:l})}if(u.kind!=="file"||!u.blobPath){let l="artifact is not a file";return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"denied",errorReason:l}),f({error:l})}try{let l=Xe({blobPath:u.blobPath,destPath:n.destPath});return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,sizeBytes:l.sizeBytes,outcome:"success"}),f({success:!0,sizeBytes:l.sizeBytes,mime:u.mime,destPath:n.destPath})}catch(l){let g=l instanceof Error?l.message:String(l);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:n.key,artifactId:u.id,outcome:"error",errorReason:g}),f({error:g})}}),A("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:v.string().optional()},async n=>{let o=await i();if("error"in o)return f({error:o.error});let a=n.stepId?we(n.stepId):null;if(a)return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:a}),f({error:a});let c=ke(o.executionId,n.stepId);return I({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:c.length,outcome:"success"}),f({artifacts:c.map(d=>({id:d.id,stepId:d.stepId,key:d.key,kind:d.kind,sizeBytes:d.sizeBytes,mime:d.mime,createdAt:d.createdAt}))})})];return so({name:"execution-tools",version:"1.0.0",tools:s})}Ft();Ne();import{realpathSync as mo}from"fs";var w=b("execution"),bt=new Set;async function fo(e,t){if(t&&bt.has(t))return w.info({taskId:e,roleName:t},"Sandbox bypass: approved from session cache"),!0;let r=_t(),i={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return pe({id:r,taskId:e,plan:i,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e,planId:r,plan:i}),w.info({taskId:e,operationId:r,roleName:t},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(s=>{let o=setTimeout(()=>{c(),me(r,"denied"),w.warn({taskId:e,operationId:r},"Sandbox bypass timed out, auto-denied"),s(!1)},12e4),a=d=>{d.planId===r&&(c(),d.decision==="allow"?(w.info({taskId:e,operationId:r},"Sandbox bypass approved by user"),t&&bt.add(t),s(!0)):(w.info({taskId:e,operationId:r},"Sandbox bypass denied by user"),s(!1)))},c=()=>{clearTimeout(o),y.off("plan_approval_decision",a)};y.on("plan_approval_decision",a)})}var oe=class{async execute(t,r){let i=Date.now(),s,n,o;O(t.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:t.status,newStatus:"running"}),w.info({taskId:t.id,roleId:t.roleId},"ExecutionManager: starting task");try{let a=t.config.executionProfile;if(!a){let m=t.roleId?R(t.roleId):void 0;if(m){w.info({taskId:t.id,roleId:t.roleId},"Lazy-backfilled executionProfile from live Role"),a=m;let h=B(t.id);h&&O(t.id,{config:{...h.config,executionProfile:m}})}}let c=le;a&&(We(a),c=G(a.name));let d={taskId:t.id,prompt:t.prompt,roleName:a?.name,roleCagPrompt:a?.cagPrompt,allowedTools:a?.allowedTools,cwd:c,workflowStep:t.parentId&&t.stepId?{executionId:t.parentId,stepId:t.stepId}:void 0},u=ut(d),l=ft({currentTaskId:t.id,roleId:t.roleId,taskPrompt:t.prompt}),g=t.config.approvalTimeout??300,E=async(m,h,k,D)=>{let x=_t(),Ce=He(D??t.roleId,t.prompt,"medium");if(Ce)return w.info({operationId:x,ruleId:Ce.id,taskId:t.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:h};let Ae={steps:[{index:0,description:`${m}: ${JSON.stringify(h).slice(0,300)}`,toolsNeeded:[m],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return pe({id:x,taskId:t.id,roleId:D??t.roleId,plan:Ae,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t.id,planId:x,plan:Ae}),w.info({taskId:t.id,operationId:x,toolName:m,matchedPattern:k},"Privilege escalation: awaiting user decision"),new Promise(ce=>{let zt=setTimeout(()=>{Me(),me(x,"denied"),w.warn({taskId:t.id,operationId:x},"Privilege escalation timed out, auto-denied"),ce({behavior:"deny",message:`Operation timed out after ${g}s. Auto-denied. Try a safer alternative that does not require approval.`})},g*1e3),De=M=>{if(M.planId===x)if(Me(),M.decision==="allow")w.info({taskId:t.id,operationId:x,approvalType:M.approvalType},"Operation authorized by user"),ce({behavior:"allow",updatedInput:h});else{let Vt=M.reason?`Operation denied by user: ${M.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";w.info({taskId:t.id,operationId:x,reason:M.reason??"no reason given"},"Operation denied by user"),ce({behavior:"deny",message:Vt})}},Me=()=>{clearTimeout(zt),y.off("plan_approval_decision",De)};y.on("plan_approval_decision",De)})},C=(Ue("defaults.deniedReadPaths")??[]).map(m=>{let h=Y(m);try{return mo(h)}catch{return h}}),p=a,K=p?.additionalDirectories??[],se=p?je(p):[],ve=[...K.map(m=>m.path)].filter((m,h,k)=>k.indexOf(m)===h),Dt=mt(m=>({disallowedTools:p?.disallowedTools,approvalRequired:p?.approvalRequired??t.config.approvalRequired,allowedBashPatterns:p?.allowedBashPatterns,deniedBashPatterns:p?.deniedBashPatterns}),E,{deniedReadPaths:C,roleScope:[c,...ve]}),Mt=Be({roleEnvVars:p?.envVars,taskEnv:t.config.env}),Bt=t.config.maxBudgetUsd??z().defaults.maxBudgetUsd,Ot=t.config.maxTurns??100,Lt=wt(t.roleId??"",t.id),$t=p?.mcpServers??{},Nt=t.config.mcpServers??{},Ut={...$t,...Nt,"execution-tools":Lt},ae=[{path:c,mode:"rw"}];t.roleId===Ve&&ae.push({path:le,mode:"ro"});for(let m of K)ae.push({path:m.path,mode:m.mode??"rw"});let Se=N();if(Se.platform==="none"&&!await fo(t.id,a?.name))return O(t.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:t.id,status:"failed",error:"Sandbox bypass denied"};let Te=p?.permissionMode??"default",Wt=po({prompt:t.prompt,options:{cwd:c,additionalDirectories:ve,systemPrompt:u,maxTurns:Ot,maxBudgetUsd:Bt,allowedTools:p?.allowedTools,model:p?.model,mcpServers:Ut,settingSources:p?.inheritUserSettings?["project","user"]:["project"],hooks:l,canUseTool:Dt,env:Mt,plugins:se.map(m=>({type:"local",path:m})),permissionMode:Te,...Te==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:m=>{let h=Se.spawn({command:m.command,args:m.args,cwd:m.cwd,env:m.env,signal:m.signal,visiblePaths:ae,deniedReadPaths:C,osCapabilities:p?.osCapabilities}),k=h;k.pid&&(xt(k.pid,t.roleId??"unknown",t.id),k.on("exit",()=>Rt(k.pid)));let D="";return k.stderr?.on("data",x=>{D+=x.toString()}),k.on("exit",x=>{x!==null&&x!==0&&D.includes("sandbox")&&(w.error({taskId:t.id,roleId:t.roleId,exitCode:x,stderr:D.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:t.roleId??"unknown",taskId:t.id,path:c,operation:`sandbox_init_failure:exit_${x}`,timestamp:Date.now()}))}),h},stderr:m=>{m.trim()&&w.debug({stderr:m.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),H="",Ee=0,Pe=()=>{w.warn({taskId:t.id},"ExecutionManager: abort signal received")};r&&r.addEventListener("abort",Pe);try{for await(let m of Wt){let h=m;if(w.debug({eventType:h.type,taskId:t.id},"ExecutionManager SDK event"),h.type==="result"&&typeof h.result=="string"&&(H=h.result),h.type==="result"){Ee++,typeof h.total_cost_usd=="number"&&(n=h.total_cost_usd);let k=h.usage;k?.input_tokens!==void 0&&k?.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}if(h.token_usage){let k=h.token_usage;k.input_tokens!==void 0&&k.output_tokens!==void 0&&(s={input:k.input_tokens,output:k.output_tokens})}}}finally{r&&r.removeEventListener("abort",Pe)}o=Ee;let de=Date.now()-i;return O(t.id,{status:"completed",result:H,completedAt:Date.now(),costUsd:n,tokenUsage:s,numTurns:o,totalDurationMs:de}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:t.id,result:H}),se.length>0&&gt(t.id,se,t.roleId),w.info({taskId:t.id,durationMs:de,costUsd:n},"ExecutionManager: task completed"),{taskId:t.id,status:"completed",result:H,costUsd:n,tokenUsage:s,numTurns:o,durationMs:de}}catch(a){let c=a instanceof Error?a.message:String(a),d=Date.now()-i;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&w.warn({taskId:t.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),O(t.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:d}),y.emit({type:"task_status_change",taskId:t.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:t.id,error:c}),w.error({taskId:t.id,error:a},"ExecutionManager: task failed"),{taskId:t.id,status:"failed",error:c,durationMs:d}}}};P();var S=b("execution-pool"),be=new Map;function xt(e,t,r){be.set(e,{roleId:t,taskId:r})}function Rt(e){be.delete(e)}function _e(e){return be.get(e)}var vt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(t,r){this.slots=Array.from({length:t},(i,s)=>({index:s,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",i=>{this.onTaskCreated(i.taskId)}),y.on("task_status_change",i=>{i.newStatus==="pending"&&this.pickupPendingTasks()});let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),S.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let t of this.slots)t.abortController&&(t.abortController.abort(),t.taskId=null,t.abortController=null);S.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=z().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(t){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let t=this.slots.find(a=>a.taskId===null);if(!t){S.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let s=[...r].sort((a,c)=>a.createdAt-c.createdAt)[0];t.taskId=s.id,t.abortController=new AbortController;let n=t.index,o=s.id;S.info({slotIndex:n,taskId:o},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,n).catch(a=>{S.error({taskId:o,error:a},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(t,r){let i=this.slots[r];if(!i)return;let s="completed";try{y.emit({type:"execution_task_start",taskId:t.id,slotIndex:r});let n=await this.executor.execute(t,i.abortController?.signal);s=n.status,S.info({taskId:t.id,status:n.status,slotIndex:r},"ExecutionPool: task finished")}finally{i.taskId=null,i.abortController=null,y.emit({type:"execution_task_end",taskId:t.id,slotIndex:r,status:s}),this.emitSlotChange(),this.runPostCompletion(t.id,t.roleId).catch(n=>{S.error({taskId:t.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let t=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:t,max:this.slots.length,queued:r.length});let i=qe();y.emit({type:"stats_update",activeTasks:t,queuedTasks:r.length,totalCostToday:Oe(i)})}async runPostCompletion(t,r){if(r){try{let{processTaskCompletion:i}=await import("./memory-extractor-3MRK43A2.js"),s=await i(t,r);s>0&&S.debug({taskId:t,roleId:r,memoriesStored:s},"Post-completion: memories extracted")}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: memory extraction failed")}try{let{processTaskReview:i}=await import("./learner-QCD6BH2J.js");await i(t)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:i}=await import("./audit-manager-LC5EQXCI.js");i(t,r)}catch(i){S.error({taskId:t,roleId:r,error:i},"Post-completion: audit evaluation failed")}}}getStatus(){let t=this.slots.filter(i=>i.taskId!==null).length,r=J("pending");return{active:t,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(t){let r=this.slots.find(i=>i.taskId===t);r&&(S.warn({taskId:t,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};P();var T=b("audit"),go="sandbox_violation",V=new Map,xe=1440*60*1e3,ne=[],ho=100;function Re(e){let t=e.roleId,r=V.get(t)??{count:0,timestamps:[]};r.count++,r.timestamps.push(e.timestamp);let i=Date.now()-xe;if(r.timestamps=r.timestamps.filter(s=>s>=i),V.set(t,r),r.count%100===0)for(let[s,n]of V.entries()){let o=Date.now()-xe;n.timestamps.filter(a=>a>=o).length===0&&V.delete(s)}ne.push(e),ne.length>ho&&ne.shift();try{Fe({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:e.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:go,source:"audit",createdAt:e.timestamp,deliveredAt:e.timestamp,expiresAt:e.timestamp+864e5,error:`${e.operation} on ${e.path}`})}catch(s){T.error({error:s},"Failed to record violation to delivery_log")}try{let s=R(e.roleId);U({timestamp:e.timestamp,oldRules:"sandbox_violation",newRules:`${e.operation} on ${e.path}`,diff:`Sandbox violation: ${e.operation} on ${e.path} (taskId=${e.taskId??"unknown"})`,roleId:e.roleId,source:"audit"})}catch(s){T.error({error:s},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp})}async function Pt(){let e=N();if(e.platform==="none")return T.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await e.isAvailable())return T.warn({platform:e.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return e.platform==="sandbox-exec"?r=Io():e.platform==="landlock"&&(r=await yo()),()=>{if(r){let i=r;r=null,i.kill("SIGTERM");let s=setTimeout(()=>{try{i.kill("SIGKILL")}catch{}},2e3);i.on("exit",()=>clearTimeout(s))}T.info("Violation watcher stopped")}}function Io(){let e=Et("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return e.stdout?.on("data",t=>{let r=t.toString().split(`
98
98
  `).filter(Boolean);for(let i of r)try{let s=JSON.parse(i),n=s.eventMessage??s.message??"";if(n.includes("deny")&&(n.includes("file-read")||n.includes("file-write"))){let o=ko(s,n);o&&Re(o)}}catch{}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString()},"log stream stderr")}),e.on("error",t=>{T.warn({error:t},"macOS violation watcher failed to start")}),T.info("macOS sandbox violation watcher started (log stream)"),e}async function yo(){let e=await St("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(e)return Tt(e),T.info("Linux violation watcher started (journalctl -kf)"),e;let t=await St("dmesg",["-w","-t"]);return t?(Tt(t),T.info("Linux violation watcher started (dmesg -w)"),t):(T.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function St(e,t){return new Promise(r=>{let i=Et(e,t,{stdio:["ignore","pipe","pipe"]}),s=setTimeout(()=>r(i),500);i.on("error",()=>{clearTimeout(s),r(null)}),i.on("exit",n=>{n!==0&&(clearTimeout(s),r(null))})})}function Tt(e){e.stdout?.on("data",t=>{let r=t.toString().split(`
99
99
  `).filter(Boolean);for(let i of r)if(i.includes("landlock")&&i.includes("denied")){let s=wo(i);s&&Re(s)}}),e.stderr?.on("data",t=>{T.debug({msg:t.toString().trim()},"Linux watcher stderr")})}function ko(e,t){let r=t.match(/(?:path|file)=["']([^"']+)["']/),i=t.match(/deny\s+(file-read|file-write|file-[^\s]+)/),s=r?.[1],n=i?.[1]??"unknown";if(!s)return null;let o=typeof e.processID=="number"?e.processID:void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function wo(e){let t=e.match(/path="([^"]+)"/)??e.match(/\/[\w\-\.\/\+ ]+/g),r=e.match(/deny\s+(\w+)/),i=e.match(/pid=(\d+)/),s=Array.isArray(t)?t[t.length-1]:t?.[1],n=r?.[1]??"unknown";if(!s)return null;let o=i?parseInt(i[1],10):void 0,a=o?_e(o):void 0;return{roleId:a?.roleId??"unknown",taskId:a?.taskId,path:s,operation:n,timestamp:Date.now(),count:1}}function re(e){Re({roleId:e.roleId,taskId:e.taskId,path:e.path,operation:e.operation,timestamp:e.timestamp,count:1})}function Ct(e){let t=V.get(e);if(!t)return 0;let r=Date.now()-xe;return t.timestamps.filter(i=>i>=r).length}function At(){return[...ne]}$();P();var j=b("audit"),bo=.4,_o=1440*60*1e3,F=null,ie=null;function pn(e,t,r=bo){let i=R(t);if(!i||i.status==="retired"||i.status==="inactive"||i.status==="dead")return;let s=st(t,e);L(t,{performanceScore:s}),lt(t,s,r)?j.info({roleId:t,emaScore:s},"Probation role graduated"):s<r&&dt(t,s,r)&&ct(t)}async function mn(){F===null&&(F=setInterval(()=>{j.info("Running daily diagnostic reports");let e=ue(void 0,1e3);for(let t of e)if(!(t.status==="retired"||t.status==="inactive"))try{Q(t.id)}catch(r){j.error({roleId:t.id,error:r},"Daily diagnostic failed")}},_o),ie=await Pt(),j.info("AuditManager started"))}function fn(){F!==null&&(clearInterval(F),F=null),ie!==null&&(ie(),ie=null),j.info("AuditManager stopped")}function gn(e){re(e)}async function hn(){let e=N(),t=ue(void 0,1e3),i=Date.now()-1440*60*1e3,s=At(),n=s.filter(c=>c.timestamp>=i).length,o=t.map(c=>{let d=s.filter(l=>l.roleId===c.id),u=d[d.length-1];return{roleId:c.id,roleName:c.name,sandboxed:e.platform!=="none",violationCount:Ct(c.id),lastViolation:u?.timestamp}}),a=await et();return{platform:e.platform,available:a,violationCount24h:n,rolePostures:o}}export{X as a,rt as b,mt as c,ft as d,Xo as e,Zo as f,ke as g,tr as h,or as i,pn as j,mn as k,fn as l,gn as m,hn as n,vt as o};
@@ -1,4 +1,4 @@
1
- import{b as i,d as u}from"./chunk-JAS3TUZX.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
1
+ import{b as i,d as u}from"./chunk-NCFVJCNQ.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
2
2
  INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
3
3
  title, created_at, last_active_at, archived_at, message_count)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)