adam-agent-server 1.2.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +22 -9
  2. package/dist/App-JGH6G5US.js +13 -0
  3. package/dist/adam-tools-KTLBI4PA.js +1 -0
  4. package/dist/{approval-handler-JYIS2PKQ.js → approval-handler-JZSXM4AD.js} +1 -1
  5. package/dist/audit-manager-BPJEAX22.js +1 -0
  6. package/dist/bree-engine-CRK73AI4.js +1 -0
  7. package/dist/{channels-WZOYE4O4.js → channels-PUOPR5Y2.js} +1 -1
  8. package/dist/channels-WMTZJAO4.js +1 -0
  9. package/dist/{chunk-KLQOILIJ.js → chunk-24GTCFEV.js} +1 -1
  10. package/dist/{chunk-KKLZIXBN.js → chunk-3567PCEJ.js} +2 -2
  11. package/dist/{chunk-KVSO3KGZ.js → chunk-4VHBKJD5.js} +56 -6
  12. package/dist/{chunk-GMCIKDTC.js → chunk-6THDALGC.js} +1 -1
  13. package/dist/{chunk-4TCP2AT7.js → chunk-7BSWC62F.js} +1 -1
  14. package/dist/{chunk-SBX3HMDA.js → chunk-7K4AQBDD.js} +1 -1
  15. package/dist/{chunk-EGS6U3V5.js → chunk-CKIVKM5T.js} +2 -2
  16. package/dist/chunk-DBI36EGR.js +83 -0
  17. package/dist/{chunk-BIIP363C.js → chunk-DMZM7RU6.js} +1 -1
  18. package/dist/{chunk-OFOVSC72.js → chunk-EZGMA3VV.js} +1 -1
  19. package/dist/chunk-GSMC3VUM.js +1 -0
  20. package/dist/{chunk-AJVN3KPM.js → chunk-GYHOPV4Q.js} +1 -1
  21. package/dist/chunk-HQ66TFYI.js +12 -0
  22. package/dist/{chunk-QN6BEJF5.js → chunk-HYDCXE5K.js} +1 -1
  23. package/dist/{chunk-AR2IZMM2.js → chunk-I5IUTZA3.js} +1 -1
  24. package/dist/chunk-I67UMGJM.js +10 -0
  25. package/dist/chunk-J3NIPZ73.js +8 -0
  26. package/dist/{chunk-RPTHFQX7.js → chunk-JKPSEMUZ.js} +1 -1
  27. package/dist/{chunk-SWPXG2CY.js → chunk-KO5AFX5U.js} +1 -1
  28. package/dist/chunk-KOWFPY2J.js +1 -0
  29. package/dist/{chunk-6YURWVQG.js → chunk-L4Y3GR6W.js} +1 -1
  30. package/dist/{chunk-CDVIT7L5.js → chunk-NOUSHXGX.js} +1 -1
  31. package/dist/{chunk-GUQAIWCQ.js → chunk-NZEDILAK.js} +1 -1
  32. package/dist/{chunk-7LBDLAUQ.js → chunk-QQWRV23T.js} +1 -1
  33. package/dist/{chunk-2HN2TSP6.js → chunk-RUY23IJK.js} +1 -1
  34. package/dist/{chunk-Z5ET7WW2.js → chunk-T33BLZV2.js} +1 -1
  35. package/dist/{chunk-6DXNXLYG.js → chunk-T7GEINGZ.js} +2 -2
  36. package/dist/{chunk-ZM6YED5F.js → chunk-UQJZU3R5.js} +1 -1
  37. package/dist/chunk-WRETNOC3.js +99 -0
  38. package/dist/chunk-XAMLLKKA.js +7 -0
  39. package/dist/{chunk-PMHNW5IL.js → chunk-XF4IERYF.js} +1 -1
  40. package/dist/{chunk-EJVUUIAV.js → chunk-YHH3QMLL.js} +1 -1
  41. package/dist/chunk-YHVFZB6Q.js +1 -0
  42. package/dist/chunk-ZRUVORAJ.js +49 -0
  43. package/dist/cli.js +2 -2
  44. package/dist/{config-EI3SCA4W.js → config-CBNOT66B.js} +1 -1
  45. package/dist/config-XMQS2NPT.js +1 -0
  46. package/dist/{db-4NY7ZOS2.js → db-XQUI4IBL.js} +1 -1
  47. package/dist/{delivery-log-SC2ULFCK.js → delivery-log-T56ZYDWO.js} +1 -1
  48. package/dist/engine-7DFJOADQ.js +1 -0
  49. package/dist/{evolution-audit-KUBXFUHI.js → evolution-audit-JZ2U7J4C.js} +1 -1
  50. package/dist/{external-api-A4JXX4ZE.js → external-api-7XV2PXPC.js} +1 -1
  51. package/dist/index.js +12 -11
  52. package/dist/learner-4EO7ZKK4.js +1 -0
  53. package/dist/{memories-FQCRKMK6.js → memories-EKREXLT6.js} +1 -1
  54. package/dist/{memory-extractor-FUOJ5D77.js → memory-extractor-JO7OHBZP.js} +2 -2
  55. package/dist/memory-service-Y3HVQYHM.js +1 -0
  56. package/dist/outbound-gateway-U5LP54JG.js +1 -0
  57. package/dist/role-presets-HWZHXBBA.js +1 -0
  58. package/dist/roles-3AEHVOEW.js +1 -0
  59. package/dist/{runtime-B2DP3JNB.js → runtime-VDBZZ4KG.js} +1 -1
  60. package/dist/{session-manager-Z6MIYRD3.js → session-manager-PWJLU6KZ.js} +1 -1
  61. package/dist/{task-templates-PSP7GOJJ.js → task-templates-ED2UCUPE.js} +1 -1
  62. package/dist/workflow-executor-XFTTJQNE.js +1 -0
  63. package/package.json +2 -2
  64. package/web/dist/assets/AlertDialog-r3y6IhpW.js +51 -0
  65. package/web/dist/assets/Button-BjXgrQ95.js +1 -0
  66. package/web/dist/assets/Card-C153tGfJ.js +1 -0
  67. package/web/dist/assets/ChannelDetail-C2uAZv1u.js +1 -0
  68. package/web/dist/assets/Channels-C62Qrg-n.js +12 -0
  69. package/web/dist/assets/Chat-kH2owmB_.js +1 -0
  70. package/web/dist/assets/Dashboard-BhD8SpFb.js +1 -0
  71. package/web/dist/assets/EmptyState-CXwJFCDQ.js +1 -0
  72. package/web/dist/assets/EnvVarEditor-GSapLD96.js +1 -0
  73. package/web/dist/assets/Evolution-BO5hysLD.js +6 -0
  74. package/web/dist/assets/GoalDetail-cxa8OvEi.js +1 -0
  75. package/web/dist/assets/Goals-Dz3qqp_l.js +1 -0
  76. package/web/dist/assets/Logs-Ckp3-hYV.js +1 -0
  77. package/web/dist/assets/Memories-DEuSRoP3.js +1 -0
  78. package/web/dist/assets/NotFound-Bvn39vSk.js +1 -0
  79. package/web/dist/assets/PageHeader-BMvN0xiB.js +1 -0
  80. package/web/dist/assets/Plugins-CRym22JF.js +1 -0
  81. package/web/dist/assets/RoleDetail-BWMjP9aZ.js +33 -0
  82. package/web/dist/assets/Roles-DD7NBDku.js +1 -0
  83. package/web/dist/assets/SectionHeader-CiCj3Is0.js +1 -0
  84. package/web/dist/assets/Settings-BlU19KuR.js +1 -0
  85. package/web/dist/assets/Strategies-CJ_q94-v.js +1 -0
  86. package/web/dist/assets/Switch-CoUUy5jr.js +1 -0
  87. package/web/dist/assets/Table-CaFJieh_.js +1 -0
  88. package/web/dist/assets/TaskDetail-DVrjU-E6.js +2 -0
  89. package/web/dist/assets/Work-BMl61RRi.js +1 -0
  90. package/web/dist/assets/dist-Bdqp1ixJ.js +1 -0
  91. package/web/dist/assets/index-DcXMQByM.css +2 -0
  92. package/web/dist/assets/index-pF--tN9F.js +2 -0
  93. package/web/dist/assets/ui-B_uMx2Fy.js +1 -0
  94. package/web/dist/assets/useIsMobileLayout-Bwrm84kJ.js +1 -0
  95. package/web/dist/assets/vendor-icons-BlMaTTx3.js +1 -0
  96. package/web/dist/assets/{vendor-react-DLRtONKt.js → vendor-react-7e01TWy7.js} +2 -2
  97. package/web/dist/assets/vendor-state-Bj70wnRm.js +1 -0
  98. package/web/dist/index.html +8 -6
  99. package/dist/App-RIYRYLKD.js +0 -9
  100. package/dist/adam-tools-V22LRDCP.js +0 -1
  101. package/dist/audit-manager-QDFDBK4E.js +0 -1
  102. package/dist/bree-engine-EKZFCS4Q.js +0 -1
  103. package/dist/channels-WMCY4QC3.js +0 -1
  104. package/dist/chunk-6HD6NYIB.js +0 -1
  105. package/dist/chunk-B4WHT7DX.js +0 -8
  106. package/dist/chunk-IHP7JV6J.js +0 -1
  107. package/dist/chunk-ITUBFUJQ.js +0 -67
  108. package/dist/chunk-IZWULGUS.js +0 -83
  109. package/dist/chunk-JNRCXAW3.js +0 -49
  110. package/dist/chunk-OEKM2W3K.js +0 -4
  111. package/dist/chunk-W3554FQ7.js +0 -7
  112. package/dist/config-7HYICF5P.js +0 -1
  113. package/dist/engine-5RJ7NJSM.js +0 -1
  114. package/dist/learner-B6XVQKBF.js +0 -1
  115. package/dist/memory-service-ANR67OPY.js +0 -1
  116. package/dist/outbound-gateway-6FQRWYFF.js +0 -1
  117. package/dist/role-presets-LRP6P5O2.js +0 -1
  118. package/dist/roles-3UTFKSHI.js +0 -1
  119. package/web/dist/assets/Card-4mOZntHG.js +0 -1
  120. package/web/dist/assets/ChannelDetail-eWtIGhAd.js +0 -1
  121. package/web/dist/assets/Channels-2veauYsm.js +0 -12
  122. package/web/dist/assets/Chat-Bha4vXwT.js +0 -1
  123. package/web/dist/assets/Dashboard-cDHpOWnY.js +0 -1
  124. package/web/dist/assets/EmptyState-BlgMMAr-.js +0 -1
  125. package/web/dist/assets/EnvVarEditor-CaCpNT3y.js +0 -1
  126. package/web/dist/assets/Evolution-Ao-gdHbS.js +0 -6
  127. package/web/dist/assets/GoalDetail-CX2i9A5a.js +0 -1
  128. package/web/dist/assets/Goals-DdM0tFus.js +0 -1
  129. package/web/dist/assets/Logs-DJhpDtCA.js +0 -1
  130. package/web/dist/assets/Memories-CYN99g2T.js +0 -1
  131. package/web/dist/assets/NotFound-CSjhzSGa.js +0 -1
  132. package/web/dist/assets/Plugins-gcMpBdyq.js +0 -1
  133. package/web/dist/assets/RoleDetail-s7u-Shk3.js +0 -33
  134. package/web/dist/assets/Roles-CCy1H7PY.js +0 -1
  135. package/web/dist/assets/Settings-JbgBxBeo.js +0 -1
  136. package/web/dist/assets/Strategies-CO4LwZjS.js +0 -1
  137. package/web/dist/assets/Switch-CTAIxUd_.js +0 -1
  138. package/web/dist/assets/Table-BxbnOSbq.js +0 -1
  139. package/web/dist/assets/TaskDetail-DEg_oUwx.js +0 -2
  140. package/web/dist/assets/Work-BpKK_uXA.js +0 -1
  141. package/web/dist/assets/dist-HyCSN_hp.js +0 -1
  142. package/web/dist/assets/index-CaocwyO8.css +0 -2
  143. package/web/dist/assets/index-rvaixveh.js +0 -52
  144. package/web/dist/assets/vendor-icons-CkI4-NxL.js +0 -1
  145. package/web/dist/assets/vendor-state-B_-GdGNJ.js +0 -1
  146. /package/web/dist/assets/{format-DvtQjPZn.js → format-CHfBBLog.js} +0 -0
@@ -1,83 +0,0 @@
1
- import{a as Z}from"./chunk-5V36ACKZ.js";import{a as xe,c as Le,d as Pe,e as K,f as Ce,g as Ee,h as De,i as mt,j as Ae,k as Ve,l as U,n as he}from"./chunk-OEKM2W3K.js";import{b as _e,c as pe,e as Me}from"./chunk-EJVUUIAV.js";import{b as J}from"./chunk-GMCIKDTC.js";import{a as Be,c as be,e as qe}from"./chunk-6YURWVQG.js";import{a as Q,b as k,c as X,d as Fe,e as Ge}from"./chunk-CDVIT7L5.js";import{a as W,b as h,c as E,d as L}from"./chunk-W3554FQ7.js";import{j as fe}from"./chunk-RPTHFQX7.js";import{d as ge}from"./chunk-SWPXG2CY.js";import{f as Y,i as ue,j as z}from"./chunk-KLQOILIJ.js";import{a as me}from"./chunk-L7JP7DUO.js";import{g as Ne}from"./chunk-4TCP2AT7.js";import{a as Ue,b as N,c as $e,f as je,g as Oe}from"./chunk-6DXNXLYG.js";import{d as I,j as Te}from"./chunk-6HD6NYIB.js";import{d as ke,e as T,g as D,h as A,i as Re,j as de,k as H}from"./chunk-B4WHT7DX.js";import{b,d as ce}from"./chunk-KVSO3KGZ.js";import{c as w,d as Se,h as C}from"./chunk-INNDBLZE.js";import{f as _}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Dt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";H();z();import{v4 as j}from"uuid";ce();function gt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function $(e){b().prepare(`
2
- INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
3
- weight, calibration_factor, created_at)
4
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5
- `).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function We(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(gt)}C();var ft=w("goal-manager");async function Nr(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await ht(e)}let r=bt(t);return{goalState:t,validationResult:r,rawInput:e}}async function ht(e){let t=`Extract SMART goal fields from this natural language input.
6
-
7
- Input: "${e}"
8
-
9
- Respond ONLY with a JSON object:
10
- {
11
- "name": "short goal name (max 100 chars)",
12
- "description": "detailed description of what the goal aims to achieve",
13
- "metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
14
- "targetValue": <number, the target to reach>,
15
- "deadline_days": <number, days from now to complete>,
16
- "budget": <number, estimated budget in USD>,
17
- "role": "<best matching role: engineer | analyst | content_creator | reviewer>"
18
- }
19
-
20
- Rules:
21
- - name: concise, actionable title
22
- - metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
23
- - targetValue: realistic target for the metric; use 1 for binary goals
24
- - deadline_days: reasonable timeframe; default 7 if unclear
25
- - budget: estimated cost in USD; default 5 if unclear
26
- - role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await Z(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),i=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+i*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){ft.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 bt(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 Ur(e,t,r){let n=j(),o=Date.now(),i={id:n,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:o,deliverTo:t,reportTo:r};return Q(i),i}function Je(e,t){let r=Date.now(),n=[],o={id:j(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),$(o);let i={id:j(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(i),$(i);let s={id:j(),goalId:e,level:"L2",parentId:i.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(s),$(s);let l={id:j(),goalId:e,level:"L3",parentId:s.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),$(l),n}var ee=class{static collect(t,r){let n=h(t);if(!n)return this.emptyMetrics(t,r);let o=J(t,500,0),i=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,s=new Set,l=0,d=0;for(let m of o)m.type==="tool_call"&&m.toolName&&s.add(m.toolName),m.type==="error"&&l++,m.type==="approval_request"&&d++;let u={taskId:t,goalId:r,timestamp:Date.now(),durationMs:i,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:s.size,errorCount:l,approvalCount:d,rawScore:0,isComplete:n.status==="completed"};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),i=1-Math.min(t.costUsd/5,1),l=1-Math.min(t.turns/50,1),d;t.toolCount>=3&&t.toolCount<=15?d=1:t.toolCount<3?d=t.toolCount/3:d=Math.max(0,1-(t.toolCount-15)/15);let u=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),m=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*i+.2*l+.1*d+.15*u+.05*m}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};ce();function yt(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function He(e){b().prepare(`
27
- INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
28
- metric_l2_score, metric_l3_score, context, completed_at)
29
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
30
- `).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function Ye(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(yt)}var te=class{static collect(t){let r=k(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,i=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),s=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-s/r.budgetUsd):1,d=this.calculateExpectedCompletion(r),u={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:i,budgetRemainingPct:l,expectedCompletionPct:d,rawScore:0};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let i=o/n;if(i<.1)return .5;let s=t.targetValue>0?t.currentValue/t.targetValue:0;return i>0?s/i:0}static calculateBudgetSpent(t){let r=Ye(t,1e3),n=0,o=new Set;for(let i of r)if(i.taskId&&!o.has(i.taskId)){o.add(i.taskId);let s=h(i.taskId);s?.costUsd&&(n+=s.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};C();var wt=w("agent"),O=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await Z(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let i=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,i.score??0)),confidence:Math.max(.3,Math.min(.95,i.confidence??.5)),reasoning:i.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let i=h(t);if(!i){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let s=this.getPromptTemplate(i.prompt??"",i.result??i.error??"",r),l,d,u;try{let g=await this.callClaude(s);l=g.score,d=g.confidence,u=g.reasoning}catch(g){wt.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),i.status==="failed"?(l=.1,d=.6,u=`Task failed: ${i.error??"unknown error"} (heuristic fallback)`):i.status==="completed"&&i.result?(l=.7,d=.5,u="Task completed with result (heuristic fallback due to API error)"):i.status==="completed"?(l=.5,d=.4,u="Task completed without explicit result (heuristic fallback)"):(l=.3,d=.3,u=`Task in status: ${i.status} (heuristic fallback)`)}let m={taskId:t,criteria:r,score:l,confidence:d,reasoning:u,evaluatedAt:Date.now()};return this.cache.set(n,m),m}static shouldUseObjective(t){let r=h(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
31
-
32
- Task: ${t}
33
- Result: ${r}
34
- Criteria: ${n}
35
-
36
- Provide:
37
- 1. Score (0-1): How well did the task meet the criteria?
38
- 2. Confidence (0-1): How confident are you in this evaluation?
39
- 3. Reasoning: Brief explanation of your scoring
40
-
41
- Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var vt={L0:.2,L1:.15,L2:.35,L3:.3},re=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let o=n.parentId,i=this.children.get(o)??[];i.push(n),this.children.set(o,i)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=We(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,i=0;for(let s of n){let l=r.get(s.id)??0,d=s.weight*s.calibrationFactor;o+=l*d,i+=d}return i>0?o/i:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(vt)){let i=this.aggregateScores(n,t);r+=i*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};C();var on=w("agent");function ne(e,t){let r=Date.now(),n=re.buildFromGoal(e),o=new Map,i=te.collect(e);for(let d of n.queryPath("L0"))o.set(d.id,i.rawScore);let s=It(n);if(t){let d=ee.collect(t,e);if(d.isComplete){for(let m of n.queryPath("L3"))o.set(m.id,d.rawScore);let u=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,d.rawScore*.65+i.rawScore*.35));return{goalId:e,taskId:t,reward:u,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:d.rawScore},calibrationFactors:s,source:"objective",confidence:.9,computedAt:r}}}if(t&&!O.shouldUseObjective(t)){let u=O.evaluate(t,"general_quality"),m=i.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:i.rawScore,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:s,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):i.rawScore;return{goalId:e,reward:l,breakdown:{L0:i.rawScore,L1:0,L2:0,L3:0},calibrationFactors:s,source:"fallback",confidence:.3,computedAt:r}}function It(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as Ze}from"uuid";ce();function oe(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function ze(e){b().prepare(`
42
- INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
43
- alpha, beta, total_trials, avg_reward, created_at, updated_at)
44
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
45
- `).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function Ke(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?oe(r):void 0}function ln(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(oe)}function Qe(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(oe)}function M(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(oe)}function Xe(e,t){b().prepare(`
46
- UPDATE strategies
47
- SET alpha = alpha + ?,
48
- beta = beta + ?,
49
- total_trials = total_trials + 1,
50
- avg_reward = CASE
51
- WHEN total_trials = 0 THEN ?
52
- ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
53
- END,
54
- updated_at = ?
55
- WHERE id = ?
56
- `).run(t,1-t,t,t,Date.now(),e)}var F=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let i,s;do i=this.randn(),s=1+o*i;while(s<=0);s=s*s*s;let l=Math.random();if(l<1-.0331*i*i*i*i||Math.log(l)<.5*i*i+n*(1-s+Math.log(s)))return n*s/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let o of t){let i=this.sampleBeta(o.alpha,o.beta);i>n&&(n=i,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let i=0;i<r;i++){let s=this.sample(t);s&&n.set(s.id,(n.get(s.id)||0)+1)}let o=new Map;for(let[i,s]of n)o.set(i,s/r);return o}};var Tt=5,ye=20,et=.5,v=class{static selectStrategy(t,r){let n=M(t,r);return F.sample(n)}static recordTrial(t,r,n,o,i,s,l){Xe(t,o),He({id:Ze(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:i,metricL3Score:s,context:l,completedAt:Date.now()})}static getStrategies(t,r){return M(t,r)}static getStrategyById(t){return Ke(t)}static getPopulationStats(t,r){let n=M(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let i=n.reduce((d,u)=>d+u.totalTrials,0)/n.length,s=n.filter(d=>d.avgReward!==void 0).map(d=>d.avgReward),l=s.length>0?s.reduce((d,u)=>d+u,0)/s.length:0;return{count:n.length,avgTrials:i,avgReward:l,minTrials:Math.min(...n.map(d=>d.totalTrials)),maxTrials:Math.max(...n.map(d=>d.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Tt?!0:n.count<ye&&n.maxTrials>0}static addStrategy(t,r,n,o){if(M(t,r).length>=ye)throw new Error(`Strategy population at maximum (${ye}) for ${t}/${r}`);let s={id:`strat-${Ze().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:et,beta:et,totalTrials:0,createdAt:Date.now()};return ze(s),s}static getTopStrategies(t,r,n=3){let i=M(t,r).filter(s=>s.totalTrials>0);return i.sort((s,l)=>(l.avgReward??0)-(s.avgReward??0)),i.slice(0,n)}static getSamplingProbabilities(t,r){let n=M(t,r);return F.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,i,s){let l=ne(r,n);return this.recordTrial(t,r,n,l.reward,o,i,s),l.reward}};var St=3,kt=2,ae=class{static async generateVariants(t,r,n=St,o=kt){let i=v.getTopStrategies(t,r,n);if(i.length===0){let l=`baseline-${r}-v1`;return v.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let s=[];for(let l=0;l<o;l++){let d=i[0].totalTrials+l+1,u=`${r}-evolved-v${d}`,m=i[0].promptTemplate,g=this.mutateTemplate(m);v.addStrategy(t,r,u,g),s.push(u)}return s}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
57
-
58
- ## Core Focus
59
- Complete tasks with high quality.
60
-
61
- ## Approach
62
- 1. Understand the task requirements thoroughly
63
- 2. Plan your approach before executing
64
- 3. Execute systematically, checking your work
65
- 4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
66
-
67
- ## Evolution
68
- ${n}`}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,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};C();Ae();import{v4 as y}from"uuid";import{spawnSync as tt}from"child_process";import{createRequire as Rt}from"module";import{dirname as _t,join as rt}from"path";import{openSync as Mt,readFileSync as xt,unlinkSync as Lt}from"fs";var Pt=3e4,nt=12e4;function ot(){let t=Rt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return rt(_t(t),"cli.js")}function G(e,t){let r=ot(),n=t?.timeout??Pt;if(t?.json){let i=rt("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),s=Mt(i,"w");try{let l=tt("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",s,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return xt(i,"utf-8")}finally{try{Lt(i)}catch{}}}let o=tt("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr?.trim()||`CLI exited with status ${o.status}`);return o.stdout}function at(){let e=G(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function we(e,t="user",r){return G(["plugin","install",e,"--scope",t],{cwd:r,timeout:nt})}function ve(e,t,r){let n=["plugin","uninstall",e];return t&&n.push("--scope",t),G(n,{cwd:r,timeout:nt})}function it(e,t){return G(["plugin","enable",e])}function st(e,t){return G(["plugin","disable",e])}function Sn(){try{return!!ot()}catch{return!1}}C();import*as lt from"crypto";var V=w("api"),B=class{cancelTask(t){let r=h(t);r&&(E(t,{status:"cancelled",completedAt:Date.now()}),me.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),V.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return V.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=_e(t);if(!i)return V.warn({planId:t},"Plan not found or already resolved"),!1;let s=h(i.taskId);return s?(Me(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xe({id:lt.randomUUID(),roleId:i.roleId,taskPattern:s.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:s.id}),me.emit({type:"plan_approval_decision",taskId:s.id,planId:t,decision:r,approvalType:n,reason:o}),V.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(V.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as At}from"fs";function ct(e,t){return t?{allowedTools:Et(t.allowedTools,e.allowedTools),disallowedTools:Ie(e.disallowedTools,t.disallowedTools),approvalRequired:Ie(e.approvalRequired,t.approvalRequired),maxBudgetUsd:t.maxBudgetUsd!==void 0&&t.maxBudgetUsd>0?Math.min(t.maxBudgetUsd,e.maxBudgetUsd):e.maxBudgetUsd,plugins:Ie(e.plugins??[],t.plugins)}:{allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,approvalRequired:e.approvalRequired,maxBudgetUsd:e.maxBudgetUsd,plugins:e.plugins??[]}}function Et(e,t){if(e===void 0)return t;if(e.length===0)return[];if(t.length===0)return e;let r=new Set(t);return e.filter(n=>r.has(n))}function Ie(e,t){return t===void 0?e:[...new Set([...e,...t])]}var ie=w("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function R(e){let{listChannels:t}=await import("./channels-WZOYE4O4.js"),r=t(),{listSessions:n}=await import("./session-manager-Z6MIYRD3.js"),o=[...n("active"),...n("archived")],i=[];for(let s of e)if(s.type==="session"&&s.sessionId)i.push({type:"session",sessionId:s.sessionId});else if(s.type==="channel"){let l=s.channelId,d=s.chatId;if(!l&&s.channelName){let u=r.find(m=>m.name.toLowerCase().includes(s.channelName.toLowerCase()));u&&(l=u.id)}if(l&&!d){let u=o.find(m=>m.source.type==="channel"&&m.source.channelId===l&&m.source.chatId);u?.source.chatId?d=u.source.chatId:d=r.find(g=>g.id===l)?.config?.userId}l&&d?i.push({type:"channel",channelId:l,chatId:d}):ie.warn({channelName:s.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return i}async function Nt(e){let{listRoles:t}=await import("./roles-3UTFKSHI.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var Ut={goalId:a.string()},$t={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},jt={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},x=a.union([a.object({type:a.literal("session"),sessionId:a.string()}),a.object({type:a.literal("channel"),channelName:a.string()}),a.object({type:a.literal("channel"),channelId:a.string(),chatId:a.string().optional()})]),Ot={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(x).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(x).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:a.object({allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional()}).optional()},Ft={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},Gt={roleId:a.string(),taskType:a.string(),name:a.string().optional()},Vt={status:a.string().optional(),limit:a.number().optional()},Bt={taskId:a.string(),roleId:a.string()},qt={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},Wt={roleId:a.string(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),mode:a.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional(),allowedChannels:a.array(a.string()).optional(),inheritUserSettings:a.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Jt={roleId:a.string().optional(),limit:a.number().optional()},Ht={name:a.string(),cagPrompt:a.string(),traits:a.array(a.string()).optional(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),mode:a.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional()},Yt={roleId:a.string(),reason:a.string().optional()},zt={name:a.string(),description:a.string().optional(),roleId:a.string().optional(),metric:a.string().optional(),targetValue:a.number().optional(),deadline:a.number().optional(),budgetUsd:a.number().optional(),deliverTo:a.array(x).optional().describe("Where to deliver goal completion notifications.")},Kt={name:a.string(),description:a.string().optional(),triggerType:a.enum(["cron","event"]),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),prompt:a.string(),roleId:a.string().optional(),enabled:a.boolean().optional(),goalIds:a.array(a.string()).optional(),deliverTo:a.array(x).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(x).optional().describe("Where to send status reports (completion summary).")},Qt={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Xt={enabled:a.boolean().optional()},Zt={},er={},tr={prompt:a.string().describe("The task prompt to execute after the delay"),delayMinutes:a.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:a.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:a.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:a.array(x).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(x).optional().describe("Where to send status reports (completion summary).")},rr={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},nr={roleId:a.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:a.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},or={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},ar={roleId:a.string().describe("Role ID to bind the MCP server to."),mcpName:a.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:a.record(a.string(),a.unknown()).describe("MCP server configuration object.")},ir={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},sr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},lr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},cr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},dr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ur={},pr={},mr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},gr={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},fr={taskId:a.string().describe("Task ID to cancel.")},hr={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},br={roleId:a.string().describe("Role ID to delete.")},yr={},wr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},vr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},Ir={templateId:a.string().describe("Template ID to update."),name:a.string().optional(),enabled:a.boolean().optional(),prompt:a.string().optional(),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),roleId:a.string().optional()},Tr={templateId:a.string().describe("Template ID to delete.")},Sr={templateId:a.string().describe("Template ID to run immediately.")},kr={enabled:a.boolean().optional().describe("Filter by enabled status.")},Rr={eventType:a.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:a.string().describe("Channel ID to deliver to."),format:a.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:a.record(a.string(),a.unknown()).optional().describe("JSON match criteria for event fields."),enabled:a.boolean().optional().describe("Enable this rule immediately (default true).")},_r={ruleId:a.string().describe("Delivery rule ID to delete.")},Mr={roleId:a.string().optional().describe("Role ID to filter strategies by.")},dt=[p("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.",Ut,async e=>{let t=k(e.goalId);if(!t)return c({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return c({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:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),p("update_goal_state","Update a goal's status, current value, or budget.",$t,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),X(e.goalId,t)),c({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",jt,async e=>{let t=I(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),i=`Decompose this goal into ${r} actionable subtasks.
69
-
70
- Goal: ${e.goalDescription}
71
-
72
- Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
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.`,s=o({prompt:i,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let u of s){let m=u;m.type==="result"&&typeof m.result=="string"&&(l=m.result)}let d=l.match(/\[[\s\S]*\]/);if(d){let u=JSON.parse(d[0]),m=[];for(let g=0;g<Math.min(u.length,r);g++){let f=u[g],q=`subtask-${y().slice(0,8)}`,P=f.role,se=P?await Nt(P):void 0;W({id:q,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:se,config:t.defaults,createdAt:Date.now()}),m.push({id:q,description:f.description,prompt:f.prompt,dependencies:g>0?[m[g-1].id]:[],estimatedComplexity:f.complexity??"medium",role:P})}if(m.length>0)return c({subtasks:m})}}catch(o){ie.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let i=`subtask-${y().slice(0,8)}`,s=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
79
-
80
- Subtask ${o+1}/${r}`;W({id:i,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:i,description:s,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),p("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Ot,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let le=A("active",20,0).filter(S=>S.source!=="system").map(S=>({id:S.id,name:S.name,allowedTools:S.allowedTools??[],capabilitySummary:U(S)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:le})}let r=y(),n=I(),o=e.prompt.toLowerCase(),i={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},s="general";for(let[le,S]of Object.entries(i))if(S.some(pt=>o.includes(pt))){s=le;break}let l,d=e.prompt,u=v.selectStrategy(e.roleId,s);u?.promptTemplate&&(d=`${u.promptTemplate}
81
-
82
- ## Task
83
- ${e.prompt}`,l=u.id);let m=t?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools,approvalRequired:t.approvalRequired,maxBudgetUsd:t.maxBudgetUsd,plugins:void 0}:void 0,g=ct(n.defaults,m),f=g.allowedTools;e.toolOverrides?.allowedTools&&(f=[...e.toolOverrides.allowedTools]);let q={...n.defaults,...g,allowedTools:f,disallowedTools:e.toolOverrides?.disallowedTools??g.disallowedTools},P=e.deliverTo?await R(e.deliverTo):void 0,se=e.reportTo?await R(e.reportTo):void 0;W({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:P,reportTo:se,config:q,createdAt:Date.now()});let{serverBus:ut}=await import("./server-bus-GEGVMSCA.js");return ut.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),p("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Ft,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=ne(t??"",r);return n&&t&&v.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),c({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),p("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",Gt,async e=>{let{roleId:t,taskType:r}=e;await ae.generateVariants(t,r,3,1);let n=v.getStrategies(t,r),o=n[n.length-1];return c(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),p("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.",Vt,async e=>{let t=e.status;return c(Fe(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>k(e.goalId)?(Ge(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),p("pause_goal","Pause an active goal.",{goalId:a.string()},async e=>k(e.goalId)?(X(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),p("assign_role","Assign a role to a pending task.",Bt,async e=>{let{taskId:t,roleId:r}=e;if(!h(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(E(t,{roleId:r}),ie.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),c({success:!0,taskId:t,roleId:r})):c({error:`Role not found: ${r}`})}),...Ve(),p("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.",qt,async e=>{if(e.taskId){let r=h(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(L(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Wt,async e=>{if(!T(e.roleId))return c({error:`Role not found: ${e.roleId}`});let r={};return e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),D(e.roleId,r),c({success:!0})}),p("view_audit_log","View the evolution audit log for role changes.",Jt,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-KUBXFUHI.js"),r=t(e.limit??50);return c({entries:r})}),p("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",Qt,async e=>{let r=A(e.status,e.limit??50,0).map(n=>{let o=he(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:U(n,o),plugins:o.plugins.map(i=>({name:i.name,skills:i.skills.map(s=>s.name),agents:i.agents.map(s=>s.name)}))}});return c({roles:r})}),p("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",Ht,async e=>{let t=`role-${y().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${y().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return ke(r),Y(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),p("retire_role","Retire a role (marks as retired, stops receiving tasks).",Yt,async e=>T(e.roleId)?(D(e.roleId,{status:"retired"}),ie.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),p("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",zt,async e=>{let t=y(),r=Date.now(),n=r+10080*60*1e3,o={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??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};Q(o),Je(t,o.metricType);let i=k(t);return c({goalId:i.id,name:i.name,status:i.status})}),p("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Kt,async e=>{let{createTaskTemplate:t}=await import("./task-templates-PSP7GOJJ.js"),r=y(),n=y(),o=e.deliverTo?await R(e.deliverTo):void 0,i=e.reportTo?await R(e.reportTo):void 0,s={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:i};return t(s),c({templateId:r,name:s.name,trigger:s.trigger})}),p("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:a.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:a.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-PSP7GOJJ.js"),r=t(e.enabled,e.limit??50,0);return c(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),p("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:a.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:a.string().describe("The message content to send (text caption when sending media)"),mediaUrl:a.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:a.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 c({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 s=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!At(s))return c({error:`Media file not found: ${s}. Verify the file exists before sending.`});if(!e.mediaType)return c({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 c({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return c({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-6FQRWYFF.js"),i=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return c({success:i.success,channelName:e.channelName,...i.error?{error:i.error}:{}})}),p("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.",Xt,async e=>{let t=ge(e.enabled),r=[...fe("active"),...fe("archived")],n=t.map(o=>{let i,s=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return s?.source.chatId?i=s.source.chatId:i=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:i}});return c({channels:n})}),p("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.",Zt,async()=>{let e=I(),t=L("running"),r=L("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),p("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.",tr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=A("active",20,0).filter(f=>f.source!=="system").map(f=>({id:f.id,name:f.name,allowedTools:f.allowedTools??[],capabilitySummary:U(f)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return c({error:"Invalid ISO 8601 timestamp in runAt"})}else return c({error:"Provide either delayMinutes or runAt"});if(n<=r)return c({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return c({error:"Schedule exceeds maximum of 7 days"});let i=y(),s=new Date(n).toISOString(),l=e.deliverTo?await R(e.deliverTo):void 0,d=e.reportTo?await R(e.reportTo):void 0;Ue({id:i,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:s},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...I().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:l,reportTo:d});let{getBreeEngine:u}=await import("./bree-engine-EKZFCS4Q.js"),m=u();return m&&m.scheduleOnceJob(i),c({templateId:i,executeAt:s,prompt:e.prompt})}),p("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:a.string().describe("The template ID returned by schedule_task")},async e=>{let t=N(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return c({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});je(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-EKZFCS4Q.js"),n=r();return n&&await n.unscheduleJob(e.templateId),c({cancelled:!0,templateId:e.templateId})}),p("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.",rr,async e=>{let t=Le(),r=K(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(z(),_(ue)),{getRole:i}=(H(),_(de)),{listInstalledPlugins:s}=(Ae(),_(mt)),l=i(e.roleId);if(!l)return[];let d=o(l.name);return s({scope:"project",projectPath:d}).map(u=>u.id)})():[];return c({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),p("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",nr,async e=>{let{getRole:t}=(H(),_(de)),{getRoleWorkspacePath:r}=(z(),_(ue)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return we(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(i){return c({error:`Failed to install plugin: ${i}`})}}),p("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",or,async e=>{let{getRole:t}=(H(),_(de)),{getRoleWorkspacePath:r}=(z(),_(ue)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return ve(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(i){return c({error:`Failed to uninstall plugin: ${i}`})}}),p("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",ar,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return D(e.roleId,{mcpServers:n}),Y(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),p("unbind_mcp_from_role","Remove an MCP server binding from a role.",ir,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return c({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return D(e.roleId,{mcpServers:r}),Y(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),p("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",er,async()=>{let{listTaskTemplates:e}=await import("./task-templates-PSP7GOJJ.js"),t=I(),r=A(void 0,100,0),n=ge(),o=e(!0,100,0),i=L("running"),s=L("pending");return c({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(l=>l.status==="active"&&l.source!=="system").map(l=>{let d=he(l);return{name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[],capabilitySummary:U(l,d),plugins:d.plugins.map(u=>({name:u.name,skills:u.skills.map(m=>m.name),agents:u.agents.map(m=>m.name)}))}}),retired:r.filter(l=>l.status==="retired").length,probation:r.filter(l=>l.status==="probation").length},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(l=>l.enabled).map(l=>({name:l.name,platform:l.platform,status:l.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:K().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:i.length,queued:s.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"]})}),p("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",sr,async e=>{try{return it(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),p("disable_plugin","Disable a globally installed plugin (removes it from all roles).",lr,async e=>{try{return st(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),p("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",cr,async e=>{try{return we(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),p("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",dr,async e=>{try{return ve(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),p("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",ur,async()=>{try{let e=at(),t=K();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),p("list_marketplace_sources","List configured plugin marketplace sources.",pr,async()=>{let e=Ee();return c({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",mr,async e=>{let t=Ce(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Pe(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),p("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",gr,async e=>{let{getRole:t}=await import("./roles-3UTFKSHI.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=De(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),p("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",fr,async e=>{let t=h(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;E(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),c({success:!0,taskId:e.taskId,status:"cancelled"})}),p("view_task_logs","Retrieve step-by-step execution logs for a task.",hr,async e=>{let t=J(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),p("delete_role","Delete a role by ID. This removes the role and its workspace.",br,async e=>T(e.roleId)?(Re(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),p("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",yr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-B2DP3JNB.js"),r=I(),n={};try{let l=I().server?.port??7100,d=await fetch(`http://127.0.0.1:${l}/config`);d.ok&&(n=await d.json())}catch{}let o=[...e,...t],i=[...t],s={};for(let l of o){let d=l.split("."),u=r;for(let m of d)if(u&&typeof u=="object")u=u[m];else{u=void 0;break}s[l]={value:u,mutable:!t.includes(l)}}return c({config:s,mutable:[...e],restartRequired:[...t]})}),p("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",wr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-B2DP3JNB.js"),{setConfigValue:r}=await import("./config-EI3SCA4W.js"),n=Te(e.updates,r);if(e.updates["logging.level"]&&Se(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(i=>({path:i,value:e.updates[i]}))})}return c(n)}),p("list_memories","List memories stored under a specific role.",vr,async e=>{let t=Ne(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),p("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Ir,async e=>{let t=N(e.templateId);if(!t)return c({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){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:y(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),$e(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",Tr,async e=>N(e.templateId)?(Oe(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),p("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Sr,async e=>{let t=N(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=I().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?c({success:!0,templateId:e.templateId,templateName:t.name,response:o}):c({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return c({error:`Failed to trigger template: ${r}`})}}),p("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",kr,async e=>{let t=be(e.enabled);return c({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Rr,async e=>{let t=y(),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 Be(r),c({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",_r,async e=>be().find(n=>n.id===e.ruleId)?(qe(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),p("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",Mr,async e=>{let t;if(e.roleId)t=Qe(e.roleId);else{let{getDb:r}=await import("./db-4NY7ZOS2.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return c({roleId:e.roleId??null,count:t.length,strategies:t})}),p("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:a.string(),operationId:a.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:a.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=pe(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new B().resolvePlanApproval(r.id,"allow",e.scope),c({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):c({error:"No pending operation found for this task"})}),p("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:a.string(),operationId:a.string().optional(),reason:a.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=pe(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new B().resolvePlanApproval(r.id,"deny","once",e.reason),c({success:!0,operationId:r.id,decision:"deny"})):c({error:"No pending operation found for this task"})})];function ao(){return dt.map(e=>e.name).sort().join(",")}function io(){return Dt({name:"adam-tools",version:"1.0.0",tools:dt})}export{B as a,Nr as b,Ur as c,Je as d,ln as e,Qe as f,v as g,at as h,we as i,ve as j,it as k,st as l,Sn as m,ao as n,io as o};
@@ -1,49 +0,0 @@
1
- import{a as S,b as P}from"./chunk-CDVIT7L5.js";import{a as k,b as m}from"./chunk-W3554FQ7.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as I}from"./chunk-4TCP2AT7.js";import{a as C,b as c,d as y,f as R}from"./chunk-6DXNXLYG.js";import{d as T}from"./chunk-SBX3HMDA.js";import{h as x,k as J}from"./chunk-B4WHT7DX.js";import{c as h,h as b}from"./chunk-INNDBLZE.js";b();J();import{v4 as l}from"uuid";import{CronExpressionParser as D}from"cron-parser";b();import{v4 as M}from"uuid";var g=h("scheduler"),v=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let o=T(),r={timeout:e.config?.timeout??o.timeout,approvalRequired:o.approvalRequired,approvalTimeout:o.approvalTimeout,plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??o.model,maxTurns:e.config?.maxTurns??o.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??o.maxBudgetUsd,env:{...o.env,...e.config?.env},claudeCodePath:o.claudeCodePath},s={templateId:e.id,executionId:t,stepResults:new Map,config:r,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo},i=this.sortSteps(e.steps);for(let a of i){try{await this.executeStep(a,s)}catch(p){g.error({stepId:a.id,error:p},"Workflow step failed");break}if(s.stepResults.get(a.id)?.status==="failed"){g.warn({stepId:a.id},"Workflow step failed, workflow aborted");break}}g.info({executionId:t,completedSteps:s.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,o=[],r=new Map(e.map(i=>[i.id,i])),s=i=>{if(!t.has(i.id)){if(t.add(i.id),i.dependsOn)for(let a of i.dependsOn){let d=r.get(a);d&&s(d)}o.push(i)}};for(let i of e)s(i);return o}async executeStep(e,t){let o=this.resolveVariables(e.prompt,t.stepResults),r=M();k({id:r,status:"pending",prompt:o,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId,roleId:t.rolePreference,deliverTo:t.deliverTo,reportTo:t.reportTo}),g.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let s=await this.executeWithRetry(r,e.id),i=m(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:s==="completed"?"completed":"failed",result:i?.result,error:i?.error})}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(o,r)=>t.get(r)?.result??`[no result from ${r}]`)}async executeWithRetry(e,t){let o=0;for(;o<this.maxRetries;){if(o++,await this.waitForTaskCompletion(e)==="completed")return"completed";if(o<this.maxRetries){let s=this.baseDelayMs*Math.pow(2,o-1);g.info({stepId:t,attempt:o,maxRetries:this.maxRetries,delayMs:s},"Workflow step failed, retrying"),await this.sleep(s)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(o=>{let r=Date.now(),s=()=>{if(Date.now()-r>t){o("failed");return}let i=m(e);if(!i){o("failed");return}if(i.status==="completed"){o("completed");return}if(i.status==="failed"||i.status==="cancelled"){o("failed");return}setTimeout(s,500)};s()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=h("scheduler"),w="ai-hourly-digest";function O(){if(c(w)){n.debug({templateId:w},"Built-in template already exists");return}let e={id:w,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
2
-
3
- \u641C\u7D22\u6765\u6E90:
4
- 1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
5
- 2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
6
- 3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
7
-
8
- \u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
9
-
10
- \u8F93\u51FA\u683C\u5F0F:
11
- - \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
12
- - \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
13
- - \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
14
- - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
15
-
16
- \u6587\u7AE0\u4FE1\u606F:
17
- {{search_ai_news.result}}
18
-
19
- \u8BF7:
20
- 1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
21
- 2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
22
- 3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
23
-
24
- \u603B\u7ED3\u7ED3\u6784:
25
- ## \u6838\u5FC3\u53D1\u73B0
26
- [\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
27
-
28
- ## \u6280\u672F\u7EC6\u8282
29
- [\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
30
-
31
- ## \u5F71\u54CD/\u610F\u4E49
32
- [\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
33
-
34
- ## \u539F\u6587\u94FE\u63A5
35
- [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
36
-
37
- \u603B\u7ED3\u5185\u5BB9:
38
- {{summarize_article.result}}
39
-
40
- \u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
41
-
42
- osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
43
-
44
- \u6CE8\u610F\uFF1A
45
- - \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
46
- - \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
47
- - \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
48
-
49
- \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};C(e),n.info({templateId:w,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var A=class{cronJobs=new Map;workflowExecutor=new v;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,O();let e=y(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let o=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),o++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(s=>{n.error({taskId:r.taskId,error:s},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:o},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=x(void 0,1e3,0),t=0;for(let o of e)t+=I(o.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let o;try{o=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=o.next().getTime()-Date.now();return Math.max(p,1e3)},s=()=>{this.executeCronTrigger(e.id).catch(p=>{n.error({templateId:e.id,error:p},"Cron trigger failed")});let d=setTimeout(s,r());this.cronJobs.set(t,d)},i=r(),a=setTimeout(s,i);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+i).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,l()))}async scheduleJob(e){let t=c(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,o=this.cronJobs.get(t);o&&(clearTimeout(o),this.cronJobs.delete(t))}async runNow(e){let t=c(e);if(!t)throw new Error(`Template ${e} not found`);let o=l();return this.executeWorkflow(t,o).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),o}async checkEventTriggers(e){let t=m(e);if(!t)return;let o=y(!0),r=o.filter(s=>s.trigger.type==="event"&&s.trigger.event==="task_complete");for(let s of r)n.debug({templateName:s.name},"Event trigger matched"),await this.executeWorkflow(s,l());if(t.templateId){let s=o.filter(i=>i.trigger.type!=="event"||!i.trigger.event?!1:i.trigger.event===`template_complete:${t.templateId}`);for(let i of s)n.info({templateName:i.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(i,l())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let o of e.goalIds){let r=P(o);if(!r){n.warn({goalId:o,templateId:e.id},"Goal reference not found, skipping");continue}let s=l();S({id:s,name:r.name,description:r.description,roleId:r.roleId,metricType:r.metricType,targetValue:r.targetValue,currentValue:0,deadline:r.deadline,budgetUsd:r.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let i=l();k({id:i,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:s,config:T(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:i}),n.info({templateId:e.id,sourceGoalId:o,newGoalId:s,taskId:i},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}scheduleOnceJob(e){let t=c(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let s=`template-${e}`;this.cronJobs.has(s)&&clearTimeout(this.cronJobs.get(s));let i=setTimeout(()=>{this.cronJobs.delete(s),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(s,i),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,l()),R(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},_=null;function Y(){return _}function Z(f){_=f}export{A as a,Y as b,Z as c};
@@ -1,4 +0,0 @@
1
- import{e as I,j as G}from"./chunk-KLQOILIJ.js";import{a as J}from"./chunk-GUQAIWCQ.js";import{a as j}from"./chunk-2CMR5AG7.js";import{a as E,b as S,c as D,j as T}from"./chunk-4TCP2AT7.js";import{b as P,d as B}from"./chunk-KVSO3KGZ.js";import{c as W,e as q}from"./chunk-FCV2DPZQ.js";var Q={};q(Q,{getGlobalEnabledState:()=>w,getInstalledPlugin:()=>z,getPluginManifest:()=>_,listInstalledPlugins:()=>A,listMarketplaceSources:()=>V,resolvePluginPaths:()=>M,scanDirectoryConfig:()=>x});import{existsSync as y,readFileSync as k,readdirSync as C}from"fs";import{join as p}from"path";import L from"os";function h(t){try{if(!y(t))return null;let e=k(t,"utf-8");return JSON.parse(e)}catch{return null}}function w(){return h(Y())?.enabledPlugins??{}}function _(t){let e=t;function s(n,r){let o={};try{if(!y(n))return o;let d=k(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let m of r){let i=new RegExp(`^${m}:\\s*(.+)$`,"m"),a=d.match(i);a&&(o[m]=a[1].trim())}}catch{}return o}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},r=p(e,".claude-plugin","plugin.json");if(y(r))try{let i=JSON.parse(k(r,"utf-8"));n.name=i.name??"",n.version=i.version,n.description=i.description,Array.isArray(i.lspServers)&&(n.lspServers=i.lspServers),Array.isArray(i.mcpServers)&&(n.mcpServers=i.mcpServers),Array.isArray(i.hooks)&&(n.hooks=i.hooks)}catch{}let o=p(e,"skills");if(y(o)){let i=C(o,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()&&!a.isSymbolicLink())continue;let u=p(o,a.name,"SKILL.md"),f=s(u,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let l=p(e,"agents");if(y(l)){let i=C(l,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(".md"))continue;let u=s(p(l,a.name),["name","description"]);u.name&&n.agents.push({name:u.name,description:u.description??""})}}let d=p(e,".mcp.json");if(y(d))try{let i=JSON.parse(k(d,"utf-8"));i.mcpServers&&typeof i.mcpServers=="object"&&(n.mcpServers=Object.keys(i.mcpServers))}catch{}let m=p(e,"hooks","hooks.json");if(y(m))try{let i=JSON.parse(k(m,"utf-8"));Array.isArray(i)&&(n.hooks=i.map(a=>typeof a=="object"&&a!==null&&"event"in a?String(a.event):String(a)))}catch{}return n}catch{return null}}function A(t){let e=h(R());if(!e?.plugins)return[];let s=w(),n=[];for(let[r,o]of Object.entries(e.plugins))if(!(!Array.isArray(o)||o.length===0))for(let l of o){let d=l.scope??"user";t?.scope&&d!==t.scope||t?.projectPath&&l.projectPath!==t.projectPath||n.push({id:r,name:r.split("@")[0],version:l.version??"",scope:d,projectPath:l.projectPath,installPath:l.installPath??p(v(),r),enabled:s[r]??l.enabled??!0,installedAt:l.installedAt??"",lastUpdated:l.lastUpdated??""})}return n}function z(t){let e=h(R());if(!e?.plugins?.[t])return null;let s=e.plugins[t];if(!Array.isArray(s)||s.length===0)return null;let n=s[0],r=w();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??p(v(),t),enabled:r[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function M(t){let e=h(R()),s=new Map;for(let n of t){let r=e?.plugins?.[n];Array.isArray(r)&&r.length>0&&s.set(n,r[0].installPath??p(v(),n))}return s}function V(){return h(H())?.marketplaces??[]}function x(t){let e=p(t,".claude","settings.json"),s=h(e);return{enabledPlugins:s?.enabledPlugins??{},mcpServers:s?.mcpServers??{},allowedTools:s?.allowedTools??[],disallowedTools:s?.disallowedTools??[]}}var v,R,H,Y,O=W(()=>{"use strict";v=()=>p(L.homedir(),".claude","plugins"),R=()=>p(v(),"installed_plugins.json"),H=()=>p(v(),"known_marketplaces.json"),Y=()=>p(L.homedir(),".claude","settings.json")});import{tool as b}from"@anthropic-ai/claude-agent-sdk";import{z as c}from"zod";import{v4 as X}from"uuid";function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Z={query:c.string().describe("Search query for memory retrieval"),roleId:c.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:c.number().optional().describe("Max results to return (default 5)")},ee={query:c.string().describe("Search query for memory retrieval"),topK:c.number().optional().describe("Max results to return (default 5)")},te={id:c.string().optional().describe("Memory ID to update. Omit to create new."),roleId:c.string().describe("Role ID to save memory under"),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ne={id:c.string().optional().describe("Memory ID to update. Omit to create new."),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:c.string().describe("Memory ID to delete")};async function F(t,e){let s=t??e.roleId,n=e.topK??5,r=await J(s,e.query,{topK:n});return g({results:r.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function $(t,e){let s=t??e.roleId;if(!s)return g({error:"roleId is required"});let n,r=!0;try{n=await j(e.content)}catch{r=!1}if(e.id){if(!S(e.id))return g({error:`Memory ${e.id} not found`});let m=D(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return g({id:e.id,action:"updated",success:m,embeddingUpdated:r})}let o=`mem-${X().slice(0,8)}`,l=Date.now();return E({id:o,roleId:s,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:l,lastAccessed:l,retrievedCount:0,tier:e.tier??"episodic"}),g({id:o,action:"created",success:!0,embeddingUpdated:r})}async function K(t,e){if(t){let s=S(e.id);if(!s)return g({error:`Memory ${e.id} not found`});if(s.roleId!==t)return g({error:`Memory ${e.id} does not belong to this role`})}return T(e.id),g({id:e.id,deleted:!0})}function ye(t){return t?[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ee,async e=>F(t,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ne,async e=>$(t,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Z,async e=>F(void 0,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",te,async e=>$(void 0,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}O();G();var re={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ve(t,e){let s=t.allowedTools??[];if(s.length===0)return"No tool permissions";let n=new Map,r=[];for(let i of s){let a=re[i];if(a){let u=n.get(a.category)??[];u.push(a.label),n.set(a.category,u)}else r.push(i)}let o=[];for(let[i,a]of n)o.push(`${i} (${a.join(", ")})`);r.length>0&&o.push(r.join(", "));let l=o.join(" \xB7 "),d=Object.keys(t.mcpServers??{});d.length>0&&(l+=` \xB7 MCP: ${d.join(", ")}`);let m=t.additionalDirectories??[];if(m.length>0&&(l+=` \xB7 Dirs: ${m.map(i=>i.path).join(", ")}`),e&&e.plugins.length>0){let i=e.plugins.map(a=>{let u=[];return a.skills.length>0&&u.push(`skills: ${a.skills.map(f=>f.name).join(", ")}`),a.agents.length>0&&u.push(`agents: ${a.agents.map(f=>f.name).join(", ")}`),u.length>0?`${a.name} (${u.join("; ")})`:a.name});l+=` \xB7 Plugins: ${i.join(", ")}`}return l}function oe(t){let e=[],s=t.additionalDirectories??[];for(let n of s){if(!n.inheritPlugins&&!n.inheritMcp)continue;let r=x(n.path),o=Object.entries(r.enabledPlugins).filter(([,d])=>d).map(([d])=>d),l=M(o);for(let[,d]of l)e.includes(d)||e.push(d)}try{let n=I(t.name),r=A({scope:"project",projectPath:n});for(let o of r)o.installPath&&!e.includes(o.installPath)&&e.push(o.installPath)}catch{}return e}function Pe(t){let e=oe(t),s=[];for(let n of e){let r=_(n);r&&s.push({name:r.name||n.split("/").pop()||"unknown",description:r.description,skills:r.skills,agents:r.agents,mcpServers:r.mcpServers,hooks:r.hooks})}return{plugins:s}}B();function se(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var U={low:1,medium:2,high:3};function we(t){P().prepare(`
2
- INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
3
- VALUES (?, ?, ?, ?, ?, ?)
4
- `).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function _e(t,e,s){let r=P().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let o of r)if(!(o.role_id&&o.role_id!==t)&&!(U[s]>U[o.max_risk_level]))try{if(new RegExp(o.task_pattern,"i").test(e))return se(o)}catch{}}export{we as a,_e as b,w as c,_ as d,A as e,z as f,V as g,x as h,Q as i,O as j,ye as k,ve as l,oe as m,Pe as n};
@@ -1,7 +0,0 @@
1
- import{b as i,d as a}from"./chunk-KVSO3KGZ.js";a();function d(t){return{id:t.id,parentId:t.parent_id??void 0,status:t.status,prompt:t.prompt,originalPrompt:t.original_prompt??void 0,config:JSON.parse(t.config),result:t.result??void 0,error:t.error??void 0,sdkSessionId:t.sdk_session_id??void 0,templateId:t.template_id??void 0,roleId:t.role_id??void 0,sourceSessionId:t.source_session_id??void 0,deliverTo:t.deliver_to?JSON.parse(t.deliver_to):void 0,reportTo:t.report_to?JSON.parse(t.report_to):void 0,createdAt:t.created_at,startedAt:t.started_at??void 0,completedAt:t.completed_at??void 0,costUsd:t.cost_usd??void 0,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,numTurns:t.num_turns??void 0,totalDurationMs:t.total_duration_ms??void 0}}function c(t){i().prepare(`
2
- INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
3
- sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
4
- created_at, started_at, completed_at,
5
- cost_usd, token_usage, num_turns, total_duration_ms)
6
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7
- `).run(t.id,t.parentId??null,t.status,t.prompt,t.originalPrompt??null,JSON.stringify(t.config),t.result??null,t.error??null,t.sdkSessionId??null,t.templateId??null,t.roleId??null,t.sourceSessionId??null,null,t.deliverTo?JSON.stringify(t.deliverTo):null,t.reportTo?JSON.stringify(t.reportTo):null,t.createdAt,t.startedAt??null,t.completedAt??null,t.costUsd??null,t.tokenUsage?JSON.stringify(t.tokenUsage):null,t.numTurns??null,t.totalDurationMs??null)}function g(t){let r=i().prepare("SELECT * FROM tasks WHERE id = ?").get(t);return r?d(r):void 0}function m(t,e){let r=i(),n=[],s=[],l={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[o,u]of Object.entries(l))o in e&&(n.push(`${u} = ?`),s.push(e[o]??null));"config"in e&&(n.push("config = ?"),s.push(JSON.stringify(e.config))),"tokenUsage"in e&&(n.push("token_usage = ?"),s.push(e.tokenUsage?JSON.stringify(e.tokenUsage):null)),"deliverTo"in e&&(n.push("deliver_to = ?"),s.push(e.deliverTo?JSON.stringify(e.deliverTo):null)),"reportTo"in e&&(n.push("report_to = ?"),s.push(e.reportTo?JSON.stringify(e.reportTo):null)),n.length!==0&&(s.push(t),r.prepare(`UPDATE tasks SET ${n.join(", ")} WHERE id = ?`).run(...s))}function f(t,e=100,r=0,n){let s=i(),l="SELECT * FROM tasks",o=[],u=[];return t&&(o.push("status = ?"),u.push(t)),n&&(o.push("role_id = ?"),u.push(n)),o.length>0&&(l+=" WHERE "+o.join(" AND ")),l+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",u.push(e,r),s.prepare(l).all(...u).map(d)}function T(t){return i().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(t).map(d)}function E(t){return i().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(t).total}export{c as a,g as b,m as c,f as d,T as e,E as f};
@@ -1 +0,0 @@
1
- import{a as b,b as c,d,e}from"./chunk-SBX3HMDA.js";import{a}from"./chunk-ZM6YED5F.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,e as getChatConfig,d as getDefaults,b as loadConfig,c as loadDefaultConfig};
@@ -1 +0,0 @@
1
- import{a,b,c,d}from"./chunk-KKLZIXBN.js";import"./chunk-2HN2TSP6.js";import"./chunk-EGS6U3V5.js";import"./chunk-6YURWVQG.js";import"./chunk-W3554FQ7.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,b as getDeliveryEngine,c as initDeliveryEngine,d as stopDeliveryEngine};
@@ -1 +0,0 @@
1
- import{d as l,e as D,f as S,g as $}from"./chunk-EJVUUIAV.js";import{b as h}from"./chunk-GMCIKDTC.js";import{b as u}from"./chunk-W3554FQ7.js";import{e as R,g as T,j as C}from"./chunk-KLQOILIJ.js";import{e as k,g as x,k as N}from"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import{c as d,h as y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";y();var w=d("agent");function I(n){let o=l(n);if(!o){w.debug({taskId:n},"No plan found for task, skipping review");return}let i=h(n,1e3),s=o.plan.steps,a=i.filter(e=>e.type==="tool_result"||e.type==="permission_denied").map(e=>({toolName:e.toolName??"unknown",output:e.content,planStepIndex:e.planStepIndex,permissionDenied:e.type==="permission_denied"})),t=[],r=new Set(a.map(e=>e.planStepIndex).filter(e=>e!==void 0));for(let e of s)r.has(e.index)||t.push({stepIndex:e.index,planned:e.description,actual:"Not executed",deviationType:"skipped"});let c=a.filter(e=>e.planStepIndex===void 0);for(let e of c)t.push({stepIndex:-1,planned:"",actual:`${e.toolName}: ${e.output.slice(0,200)}`,deviationType:"added"});let b=a.filter(e=>e.permissionDenied);for(let e of b)t.push({stepIndex:e.planStepIndex??-1,planned:e.planStepIndex!==void 0?s.find(E=>E.index===e.planStepIndex)?.description??"Unknown":"",actual:`PERMISSION DENIED: ${e.toolName}`,deviationType:"failed"});let p=s.length,m=a.length,g=p>0?Math.max(0,1-t.filter(e=>e.deviationType!=="added").length/p):1,v={stepsPlanned:p,stepsExecuted:m,deviations:t,overallAccuracy:g};return S(o.id,v),w.info({taskId:n,planId:o.id,stepsPlanned:p,stepsExecuted:m,deviationCount:t.length,accuracy:g},"Deviation report generated"),v}function P(n){return n.deviations.filter(i=>i.deviationType==="failed"||i.deviationType==="skipped").length===0&&n.overallAccuracy>=.7}N();C();y();var f=d("agent");function L(n,o){let i=[],a=u(n)?.prompt.slice(0,100)??"unknown task";P(o)&&i.push(`[+] Task "${a}" completed successfully with ${o.overallAccuracy*100}% plan accuracy (${o.stepsExecuted} steps). [sourceTaskId:${n}]`);for(let t of o.deviations)switch(t.deviationType){case"skipped":i.push(`[-] Planned step "${t.planned}" was skipped during "${a}". Consider if this step is necessary for similar tasks. [sourceTaskId:${n}]`);break;case"failed":i.push(`[-] Step failed: "${t.actual}" during "${a}". Check permissions and tool availability. [sourceTaskId:${n}]`);break;case"added":i.push(`[~] Unplanned action: "${t.actual}" during "${a}". Consider adding to plan for similar tasks. [sourceTaskId:${n}]`);break;case"modified":i.push(`[~] Step modified: planned "${t.planned}" but did "${t.actual}" during "${a}". [sourceTaskId:${n}]`);break}return i}async function z(n){let o=l(n);if(!o){f.debug({taskId:n},"No plan for task, skipping review/learn");return}let i=I(n);if(!i)return;let s=L(n,i);if(s.length===0)return;$(o.id,s);let a=u(n);if(a?.roleId){let t=k(a.roleId);if(t){let r=[...t.learnedRules,...s];x(a.roleId,{learnedRules:r});let c=R(t.name);T(c,{...t,learnedRules:r}),f.info({roleId:a.roleId,newRulesCount:s.length},"Role learnedRules updated and CLAUDE.md written")}}D(o.id,"completed"),f.info({taskId:n,planId:o.id,rulesExtracted:s.length,accuracy:i.overallAccuracy},"Task review and learning completed")}export{L as extractRulesFromDeviation,z as processTaskReview};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as getRelevantMemoryContext,a as queryMemory,c as queryMemoryByTier};
@@ -1 +0,0 @@
1
- import{a,b,c}from"./chunk-EGS6U3V5.js";import"./chunk-SWPXG2CY.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
@@ -1 +0,0 @@
1
- import{a,b}from"./chunk-BIIP363C.js";import"./chunk-KLQOILIJ.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
@@ -1 +0,0 @@
1
- import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,k as h}from"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";h();export{b as createRole,g as deleteRole,c as getRole,d as getRoleByName,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{nt as t}from"./vendor-icons-CkI4-NxL.js";import{t as n}from"./vendor-react-DLRtONKt.js";import{n as r}from"./dist-HyCSN_hp.js";var i=e(t(),1),a=n(),o=i.forwardRef(({className:e,padding:t=!0,...n},i)=>(0,a.jsx)(`div`,{ref:i,className:r(`rounded-lg border border-slate-800 bg-slate-900 text-slate-200 shadow-sm`,t&&`p-4`,e),...n}));o.displayName=`Card`;var s=i.forwardRef(({className:e,...t},n)=>(0,a.jsx)(`div`,{ref:n,className:r(`mb-3 flex items-center justify-between`,e),...t}));s.displayName=`CardHeader`;var c=i.forwardRef(({className:e,...t},n)=>(0,a.jsx)(`h3`,{ref:n,className:r(`text-sm font-medium text-slate-400`,e),...t}));c.displayName=`CardTitle`;var l=i.forwardRef(({className:e,...t},n)=>(0,a.jsx)(`p`,{ref:n,className:r(`text-xs text-slate-500`,e),...t}));l.displayName=`CardDescription`;var u=i.forwardRef(({className:e,...t},n)=>(0,a.jsx)(`div`,{ref:n,className:r(``,e),...t}));u.displayName=`CardContent`;var d=i.forwardRef(({className:e,...t},n)=>(0,a.jsx)(`div`,{ref:n,className:r(`flex items-center pt-2`,e),...t}));d.displayName=`CardFooter`;export{s as n,c as r,o as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,H as n,N as r,nt as i,w as a,y as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(i(),1),_=l();function v(){let{id:e}=s(),[i,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)([]),[C,w]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&((async()=>{try{l((await u(`/channels/${e}`)).channel),w(null)}catch(e){w(e instanceof Error?e.message:`Failed to load channel`)}})(),u(`/delivery-rules`).then(t=>b(t.filter(t=>t.target.type===`channel`&&t.target.channelId===e))).catch(()=>b([])),u(`/delivery-rules`).then(async t=>{let n=t.filter(t=>t.target.type===`channel`&&t.target.channelId===e),r=[];for(let e of n.slice(0,3))try{let t=await u(`/delivery-rules/${e.id}/log`);r.push(...t.log??[])}catch{}r.sort((e,t)=>t.createdAt-e.createdAt),S(r.slice(0,20))}).catch(()=>S([])))},[e]),C)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:C})]});if(!i)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let T=e=>e===`connected`?`success`:e===`connecting`?`warning`:e===`error`?`destructive`:`secondary`,E=e=>{switch(e){case`wechat`:return`WeChat`;case`telegram`:return`Telegram`;case`slack`:return`Slack`;case`discord`:return`Discord`;default:return e.charAt(0).toUpperCase()+e.slice(1)}},D={...i.config};for(let e of[`botToken`,`apiKey`,`secret`,`password`,`token`])e in D&&(D[e]=`********`);return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:T(i.status),children:i.status}),(0,_.jsx)(d,{variant:`outline`,children:E(i.platform)}),i.enabled?(0,_.jsx)(d,{variant:`success`,children:`enabled`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:i.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:i.name})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:n,label:`Created`,value:h(i.createdAt),mono:!0}),(0,_.jsx)(y,{icon:a,label:`Messages`,value:String(i.messageCount),mono:!0}),i.lastMessageAt&&(0,_.jsx)(y,{icon:n,label:`Last Message`,value:h(i.lastMessageAt),mono:!0}),i.linkedRoleId&&(0,_.jsx)(y,{icon:o,label:`Linked Role`,value:i.linkedRoleId.slice(0,8)+`...`,mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Configuration`})}),(0,_.jsx)(`pre`,{className:`max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-slate-800 p-3 font-mono text-xs text-slate-300`,children:JSON.stringify(D,null,2)})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(r,{size:14}),` Delivery Rules (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`rounded-md border border-slate-700 bg-slate-800/50 p-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(d,{variant:`outline`,children:e.eventType}),e.enabled?(0,_.jsx)(d,{variant:`success`,children:`active`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`max `,e.maxPerMinute,`/min`]})]}),(0,_.jsxs)(`p`,{className:`mt-1 text-xs text-slate-400 font-mono`,children:[`Rule: `,e.id]})]},e.id))})]}),x.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(a,{size:14}),` Delivery Log (`,x.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:x.slice(0,10).map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between rounded-md border border-slate-800 p-2`,children:[(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsx)(`span`,{className:`text-sm text-slate-300 font-mono`,children:e.taskId.slice(0,8)}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:h(e.createdAt)})]}),(0,_.jsx)(d,{variant:e.status===`delivered`?`default`:e.status===`failed`?`destructive`:`outline`,children:e.status})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as ChannelDetail};
@@ -1,12 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{S as t,b as n,g as r,nt as i,o as a,t as o,v as s,w as c,y as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{f,t as p}from"./index-rvaixveh.js";import{n as m,r as h,t as g}from"./Card-4mOZntHG.js";import{t as _}from"./EmptyState-BlgMMAr-.js";var v=e(i(),1),y=u(),b=[`telegram`,`slack`,`discord`,`openclaw`,`wechat`,`whatsapp`],x={telegram:`{
2
- "botToken": ""
3
- }`,slack:`{
4
- "botToken": "",
5
- "signingSecret": ""
6
- }`,discord:`{
7
- "botToken": ""
8
- }`,openclaw:`{
9
- "gatewayUrl": "ws://127.0.0.1:18789"
10
- }`,wechat:`{
11
- "baseUrl": "https://ilinkai.weixin.qq.com"
12
- }`,whatsapp:`{}`},S=e=>{switch(e){case`connected`:return`success`;case`connecting`:return`warning`;case`degraded`:return`warning`;case`error`:return`destructive`;default:return`secondary`}};function C({initial:e,onSubmit:t,onCancel:n}){let[r,i]=(0,v.useState)(e?.name??``),[a,s]=(0,v.useState)(e?.platform??`telegram`),[c,l]=(0,v.useState)(e?.config?JSON.stringify(e.config,null,2):x[e?.platform??`telegram`]??`{}`),[u,d]=(0,v.useState)(e?.enabled??!0),[p,m]=(0,v.useState)(``);function _(e){if(e.preventDefault(),!r.trim()){m(`Name is required`);return}let n;try{n=JSON.parse(c)}catch{m(`Invalid JSON in config`);return}m(``),t({name:r.trim(),platform:a,config:n,enabled:u})}return(0,y.jsx)(g,{children:(0,y.jsxs)(`form`,{onSubmit:_,className:`space-y-3`,children:[(0,y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,y.jsx)(h,{className:`text-slate-200`,children:e?`Edit Channel`:`New Channel`}),(0,y.jsx)(f,{variant:`ghost`,size:`icon`,type:`button`,onClick:n,children:(0,y.jsx)(o,{size:14})})]}),p&&(0,y.jsx)(`div`,{className:`text-xs text-red-400`,children:p}),(0,y.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[(0,y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,y.jsx)(`label`,{className:`text-xs text-slate-400`,children:`Name`}),(0,y.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`My Telegram Bot`,className:`rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none`})]}),(0,y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,y.jsx)(`label`,{className:`text-xs text-slate-400`,children:`Platform`}),(0,y.jsx)(`select`,{value:a,onChange:t=>{s(t.target.value),e||l(x[t.target.value]??`{}`)},className:`rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,children:b.map(e=>(0,y.jsx)(`option`,{value:e,children:e},e))})]})]}),(0,y.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,y.jsx)(`label`,{className:`text-xs text-slate-400`,children:`Config (JSON)`}),(0,y.jsx)(`textarea`,{value:c,onChange:e=>l(e.target.value),rows:4,className:`resize-none rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 font-mono text-xs text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none`})]}),(0,y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,y.jsx)(`input`,{type:`checkbox`,id:`ch-enabled`,checked:u,onChange:e=>d(e.target.checked),className:`rounded border-slate-700 bg-slate-800`}),(0,y.jsx)(`label`,{htmlFor:`ch-enabled`,className:`text-xs text-slate-400`,children:`Enabled`})]}),!e&&a===`wechat`&&(0,y.jsx)(`div`,{className:`rounded bg-blue-900/30 border border-blue-800/50 px-3 py-2 text-xs text-blue-300`,children:`Creating a WeChat channel will start a QR code scan. Have your WeChat app ready.`}),(0,y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,y.jsx)(f,{type:`submit`,size:`sm`,children:e?`Save`:a===`wechat`&&!e?`Create & Connect`:`Create`}),(0,y.jsx)(f,{type:`button`,variant:`ghost`,size:`sm`,onClick:n,children:`Cancel`})]})]})})}function w({channelId:e,onClose:t}){let[n,r]=(0,v.useState)([]),[i,a]=(0,v.useState)(!0);return(0,v.useEffect)(()=>{(async()=>{try{r((await d(`/channels/${e}/messages`)).messages)}catch{}a(!1)})()},[e]),(0,y.jsxs)(g,{children:[(0,y.jsxs)(`div`,{className:`flex items-center justify-between mb-3`,children:[(0,y.jsx)(h,{children:`Channel Messages`}),(0,y.jsx)(f,{variant:`ghost`,size:`icon`,onClick:t,children:(0,y.jsx)(o,{size:14})})]}),i?(0,y.jsx)(`div`,{className:`text-xs text-slate-500`,children:`Loading...`}):n.length===0?(0,y.jsx)(`div`,{className:`text-xs text-slate-500`,children:`No messages yet`}):(0,y.jsx)(`div`,{className:`max-h-64 overflow-y-auto space-y-2`,children:n.map(e=>(0,y.jsxs)(`div`,{className:`rounded bg-slate-800/50 px-3 py-2 text-xs`,children:[(0,y.jsx)(`span`,{className:e.role===`user`?`text-blue-400`:`text-emerald-400`,children:e.role}),(0,y.jsx)(`span`,{className:`text-slate-500 ml-2`,children:new Date(e.createdAt).toLocaleTimeString()}),(0,y.jsx)(`div`,{className:`mt-1 text-slate-300`,children:e.content})]},e.id))})]})}function T(){let[e,i]=(0,v.useState)([]),[o,u]=(0,v.useState)(!0),[b,x]=(0,v.useState)(!1),[T,E]=(0,v.useState)(null),[D,O]=(0,v.useState)(null),[k,A]=(0,v.useState)(null),[j,M]=(0,v.useState)(!1);(0,v.useEffect)(()=>{N()},[]);async function N(){try{i((await d(`/channels`)).channels)}catch{}u(!1)}async function P(e){try{let t=await d(`/channels`,{method:`POST`,body:JSON.stringify(e)});x(!1),N(),e.platform===`wechat`&&t.channel?.id&&I(t.channel.id)}catch{}}async function F(e){if(T)try{await d(`/channels/${T.id}`,{method:`PATCH`,body:JSON.stringify(e)}),E(null),N()}catch{}}async function I(t){if(e.find(e=>e.id===t)?.platform===`wechat`)try{let e=await d(`/channels/${t}/wechat/qr-start`,{method:`POST`});if(e.qrcodeUrl&&e.sessionKey){A({channelId:t,qrcodeUrl:e.qrcodeUrl,sessionKey:e.sessionKey}),M(!0);try{(await d(`/channels/${t}/wechat/qr-wait`,{method:`POST`,body:JSON.stringify({sessionKey:e.sessionKey,timeoutMs:12e4})})).connected&&N()}catch{}A(null),M(!1)}}catch{}else try{await d(`/channels/${t}/connect`,{method:`POST`}),N()}catch{}}async function L(e){try{await d(`/channels/${e}/disconnect`,{method:`POST`}),N()}catch{}}async function R(e){try{await d(`/channels/${e}`,{method:`DELETE`}),i(t=>t.filter(t=>t.id!==e))}catch{}}return o?(0,y.jsx)(`div`,{className:`flex h-full items-center justify-center`,children:(0,y.jsx)(`div`,{className:`h-8 w-8 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):(0,y.jsxs)(`div`,{className:`space-y-6`,children:[(0,y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,y.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Channels`}),(0,y.jsxs)(f,{size:`sm`,onClick:()=>{x(!0),E(null)},children:[(0,y.jsx)(s,{size:14}),` Add Channel`]})]}),b&&!T&&(0,y.jsx)(C,{onSubmit:P,onCancel:()=>x(!1)}),T&&(0,y.jsx)(C,{initial:T,onSubmit:F,onCancel:()=>E(null)}),D&&(0,y.jsx)(w,{channelId:D,onClose:()=>O(null)}),k&&(0,y.jsx)(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center bg-black/60`,children:(0,y.jsxs)(g,{className:`max-w-sm text-center`,children:[(0,y.jsx)(h,{className:`mb-3 text-slate-200`,children:`Scan QR Code with WeChat`}),(0,y.jsx)(`img`,{src:`https://api.qrserver.com/v1/create-qr-code/?size=256x256&data=${encodeURIComponent(k.qrcodeUrl)}`,alt:`WeChat QR Code`,className:`mx-auto h-64 w-64 rounded bg-white p-2`}),(0,y.jsx)(`p`,{className:`mt-3 text-xs text-slate-400`,children:j?`Waiting for scan...`:`Open WeChat and scan the QR code`}),(0,y.jsx)(`a`,{href:k.qrcodeUrl,target:`_blank`,rel:`noopener noreferrer`,className:`mt-1 block text-[10px] text-blue-400 hover:text-blue-300 truncate max-w-[280px] mx-auto`,children:k.qrcodeUrl}),(0,y.jsx)(f,{variant:`ghost`,size:`sm`,className:`mt-3`,onClick:()=>{A(null),M(!1)},children:`Cancel`})]})}),e.length===0&&!b?(0,y.jsx)(_,{icon:(0,y.jsx)(r,{size:24}),title:`No channels`,description:`Add a channel to connect Adam to messaging platforms like Telegram, Slack, or Discord.`}):(0,y.jsx)(`div`,{className:`grid gap-4 md:grid-cols-2 lg:grid-cols-3`,children:e.map(e=>(0,y.jsxs)(g,{children:[(0,y.jsxs)(m,{children:[(0,y.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,y.jsx)(r,{size:16,className:`text-slate-400`}),(0,y.jsx)(h,{className:`text-slate-200`,children:e.name})]}),(0,y.jsx)(p,{variant:S(e.status),children:e.status})]}),(0,y.jsxs)(`div`,{className:`space-y-2 text-xs text-slate-400`,children:[(0,y.jsxs)(`div`,{className:`flex justify-between`,children:[(0,y.jsx)(`span`,{children:`Platform`}),(0,y.jsx)(`span`,{className:`text-slate-300`,children:e.platform})]}),(0,y.jsxs)(`div`,{className:`flex justify-between`,children:[(0,y.jsx)(`span`,{children:`Messages`}),(0,y.jsx)(`span`,{className:`text-slate-300`,children:e.messageCount})]}),(0,y.jsxs)(`div`,{className:`flex justify-between`,children:[(0,y.jsx)(`span`,{children:`Enabled`}),(0,y.jsx)(`span`,{className:e.enabled?`text-emerald-400`:`text-slate-500`,children:e.enabled?`Yes`:`No`})]})]}),(0,y.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2 border-t border-slate-800 pt-3`,children:[e.status===`connected`?(0,y.jsxs)(f,{variant:`secondary`,size:`sm`,onClick:()=>void L(e.id),children:[(0,y.jsx)(n,{size:12}),` Disconnect`]}):(0,y.jsxs)(f,{variant:`secondary`,size:`sm`,onClick:()=>void I(e.id),children:[(0,y.jsx)(l,{size:12}),` Connect`]}),(0,y.jsx)(f,{variant:`ghost`,size:`sm`,onClick:()=>{E(e),x(!1)},children:(0,y.jsx)(t,{size:12})}),(0,y.jsx)(f,{variant:`ghost`,size:`sm`,onClick:()=>O(e.id),children:(0,y.jsx)(c,{size:12})}),(0,y.jsx)(f,{variant:`ghost`,size:`sm`,onClick:()=>void R(e.id),children:(0,y.jsx)(a,{size:12})})]})]},e.id))})]})}export{T as Channels};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{T as t,d as n,et as r,m as i,nt as a,o,v as s}from"./vendor-icons-CkI4-NxL.js";import{t as c}from"./vendor-react-DLRtONKt.js";import{a as l,r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./vendor-state-B_-GdGNJ.js";import{f}from"./index-rvaixveh.js";import{a as p}from"./format-DvtQjPZn.js";var m=e(a(),1),h=d((e,t)=>({sessions:[],activeSessionId:null,messages:[],loading:!1,sending:!1,_chatWs:null,_chatWsReconnectDelay:1e3,fetchSessions:async()=>{try{e({sessions:(await u(`/chat/sessions`)).sessions})}catch{}},fetchMessages:async t=>{e({loading:!0});try{e({messages:(await u(`/chat/sessions/${t}`)).messages,loading:!1})}catch{e({messages:[],loading:!1})}},sendMessage:async n=>{if(t().sending)return null;e({sending:!0});try{let r=await u(`/chat/messages`,{method:`POST`,body:JSON.stringify({content:n,source:{type:`web`},sessionId:t().activeSessionId??void 0})});return e({activeSessionId:r.sessionId,sending:!1}),t().fetchSessions(),r}catch{return e({sending:!1}),null}},createSession:async()=>{try{let t=await u(`/chat/sessions`,{method:`POST`,body:JSON.stringify({source:{type:`web`}})});return e(e=>({sessions:[t.session,...e.sessions],activeSessionId:t.session.id,messages:[]})),t.session}catch{return null}},archiveSession:async t=>{try{await u(`/chat/sessions/${t}/archive`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`archived`}:e),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},restoreSession:async t=>{try{await u(`/chat/sessions/${t}/restore`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`active`}:e)}))}catch{}},deleteSession:async t=>{try{await u(`/chat/sessions/${t}`,{method:`DELETE`}),e(e=>({sessions:e.sessions.filter(e=>e.id!==t),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},setActiveSession:n=>{e({activeSessionId:n,messages:[]}),n&&t().fetchMessages(n)},connectChatStream:()=>{let n=t()._chatWs;if(n&&n.readyState<=1)return;let r=window.location.protocol===`https:`?`wss:`:`ws:`,i=localStorage.getItem(`adam_api_key`),a=new URL(`${r}//${window.location.host}/chat/stream`);i&&a.searchParams.set(`api_key`,i);let o=new WebSocket(a.toString());o.onopen=()=>{e({_chatWs:o,_chatWsReconnectDelay:1e3})},o.onclose=()=>{let n=t()._chatWsReconnectDelay;e({_chatWs:null,_chatWsReconnectDelay:Math.min(n*2,1e4)}),setTimeout(()=>{t().connectChatStream()},n)},o.onerror=()=>{o.close()},o.onmessage=n=>{try{let r=JSON.parse(n.data);if(r.type===`chat_message`&&r.message){let n=r.message,{activeSessionId:i,messages:a}=t();if(n.sessionId!==i||a.some(e=>e.id===n.id))return;e(e=>({messages:[...e.messages,n]}))}else r.type===`session_created`&&t().fetchSessions()}catch{}},e({_chatWs:o})},disconnectChatStream:()=>{let n=t()._chatWs;n&&(n.onclose=null,n.onerror=null,n.onmessage=null,n.close(),e({_chatWs:null}))}})),g=c();function _({message:e}){let t=e.role===`user`;return(0,g.jsx)(`div`,{className:l(`flex`,t?`justify-end`:`justify-start`),children:(0,g.jsxs)(`div`,{className:l(`max-w-[80%] rounded-lg px-3.5 py-2.5 text-sm leading-relaxed`,t?`bg-blue-600 text-white`:`border border-slate-700 bg-slate-800 text-slate-200`),children:[(0,g.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}),(0,g.jsx)(`div`,{className:l(`mt-1.5 text-[10px]`,t?`text-blue-200/60`:`text-slate-500`),children:p(typeof e.createdAt==`number`?e.createdAt:new Date(e.createdAt).getTime())})]})})}function v({onSend:e,disabled:t,placeholder:r=`Type a message...`}){let[i,a]=(0,m.useState)(``),o=(0,m.useRef)(null),s=()=>{let n=i.trim();!n||t||(e(n),a(``),o.current&&(o.current.style.height=`auto`))},c=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),s())},l=()=>{let e=o.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};return(0,g.jsxs)(`div`,{className:`flex items-end gap-2 border-t border-slate-800 bg-slate-950 px-4 py-3`,children:[(0,g.jsx)(`textarea`,{ref:o,value:i,onChange:e=>{a(e.target.value),l()},onKeyDown:c,placeholder:r,disabled:t,rows:1,className:`flex-1 resize-none rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50`}),(0,g.jsx)(f,{onClick:s,disabled:t||!i.trim(),size:`default`,"aria-label":`Send message`,children:(0,g.jsx)(n,{size:16})})]})}function y(e){let t=Math.floor((Date.now()-e)/1e3);if(t<60)return`just now`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function b({session:e,isActive:t,onSelect:n,onArchive:a,onRestore:s,onDelete:c}){let u=e.status===`archived`;return(0,g.jsxs)(`button`,{onClick:n,className:l(`group flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors`,t?`bg-slate-800 text-slate-100`:`text-slate-400 hover:bg-slate-800/50 hover:text-slate-300`,u&&`opacity-60`),children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsx)(`span`,{className:`truncate text-xs font-medium`,children:e.title??e.id.slice(0,8)}),(0,g.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100`,children:[u?(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),s()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),s())},className:`rounded p-0.5 text-slate-500 hover:text-emerald-400`,title:`Restore`,children:(0,g.jsx)(i,{size:12})}):(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),a()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),a())},className:`rounded p-0.5 text-slate-500 hover:text-amber-400`,title:`Archive`,children:(0,g.jsx)(r,{size:12})}),(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),c()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),c())},className:`rounded p-0.5 text-slate-500 hover:text-red-400`,title:`Delete`,children:(0,g.jsx)(o,{size:12})})]})]}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-slate-500`,children:[(0,g.jsxs)(`span`,{children:[e.messageCount,` turns`]}),(0,g.jsx)(`span`,{children:y(e.lastActiveAt)}),u&&(0,g.jsx)(`span`,{className:`rounded bg-slate-700 px-1 py-0.5 text-[9px]`,children:`archived`})]})]})}function x({sessions:e,activeSessionId:t,onSelectSession:n,onNewSession:r,onArchiveSession:i,onRestoreSession:a,onDeleteSession:o}){let c=e.filter(e=>e.status===`active`),l=e.filter(e=>e.status===`archived`);return(0,g.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-800 px-3 py-2.5`,children:[(0,g.jsx)(`span`,{className:`text-xs font-medium text-slate-400`,children:`Sessions`}),(0,g.jsx)(f,{variant:`ghost`,size:`sm`,onClick:r,children:(0,g.jsx)(s,{size:14})})]}),(0,g.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-1.5 py-1.5`,children:[c.length===0&&l.length===0&&(0,g.jsx)(`div`,{className:`px-2 py-4 text-center text-xs text-slate-500`,children:`No sessions yet`}),c.length>0&&(0,g.jsx)(`div`,{className:`space-y-0.5`,children:c.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))}),l.length>0&&(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`mt-3 mb-1 px-2 text-[10px] font-medium uppercase tracking-wider text-slate-600`,children:`Archived`}),(0,g.jsx)(`div`,{className:`space-y-0.5`,children:l.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))})]})]})]})}function S(){let e=h(e=>e.sessions),n=h(e=>e.activeSessionId),r=h(e=>e.messages),i=h(e=>e.sending),a=h(e=>e.fetchSessions),o=h(e=>e.sendMessage),s=h(e=>e.createSession),c=h(e=>e.archiveSession),l=h(e=>e.restoreSession),u=h(e=>e.deleteSession),d=h(e=>e.setActiveSession),f=h(e=>e.connectChatStream),p=h(e=>e.disconnectChatStream),y=(0,m.useRef)(null);return(0,m.useEffect)(()=>{a()},[a]),(0,m.useEffect)(()=>(f(),()=>p()),[f,p]),(0,m.useEffect)(()=>{y.current?.scrollIntoView?.({behavior:`smooth`})},[r]),(0,g.jsxs)(`div`,{className:`flex h-full overflow-hidden`,children:[(0,g.jsx)(`div`,{className:`hidden w-56 flex-shrink-0 border-r border-slate-800 bg-slate-950 lg:block`,children:(0,g.jsx)(x,{sessions:e,activeSessionId:n,onSelectSession:d,onNewSession:()=>void s(),onArchiveSession:e=>void c(e),onRestoreSession:e=>void l(e),onDeleteSession:e=>void u(e)})}),(0,g.jsxs)(`div`,{className:`flex flex-1 flex-col`,children:[(0,g.jsx)(`div`,{className:`flex-1 overflow-y-auto px-4 py-4`,children:r.length===0?(0,g.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 text-slate-500`,children:[(0,g.jsx)(`div`,{className:`rounded-full bg-slate-800 p-3`,children:(0,g.jsx)(t,{size:24})}),(0,g.jsx)(`div`,{className:`text-sm`,children:`Start a conversation with Adam`}),(0,g.jsx)(`div`,{className:`text-xs text-slate-600`,children:`Type a message below to begin`})]}):(0,g.jsxs)(`div`,{className:`mx-auto max-w-3xl space-y-3`,children:[r.map(e=>(0,g.jsx)(_,{message:e},e.id)),(0,g.jsx)(`div`,{ref:y})]})}),(0,g.jsx)(`div`,{className:`mx-auto w-full max-w-3xl`,children:(0,g.jsx)(v,{onSend:async e=>{await o(e)},disabled:i})})]})]})}export{S as Chat};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{G as t,K as n,V as r,W as i,c as a,k as o,nt as s,q as c,tt as l}from"./vendor-icons-CkI4-NxL.js";import{r as u,t as d}from"./vendor-react-DLRtONKt.js";import{C as f,n as p,t as m}from"./index-rvaixveh.js";import{n as h,r as g,t as _}from"./Card-4mOZntHG.js";import{a as v,o as y,t as b}from"./format-DvtQjPZn.js";import{a as x,i as S,n as C,o as w,r as T,t as E}from"./Table-BxbnOSbq.js";var D=e(s(),1),O=d();function k(){let e=f(e=>e.tasks),s=f(e=>e.goals),d=f(e=>e.stats),k=f(e=>e.readiness),j=f(e=>e.roles),M=f(e=>e.executionPool),N=f(e=>e.fetchTasks),P=f(e=>e.fetchGoals),F=f(e=>e.fetchRoles),I=f(e=>e.fetchExecutionPool);(0,D.useEffect)(()=>{N(),P(),F(),I();let e=setInterval(()=>{N(),I()},5e3);return()=>clearInterval(e)},[N,P,F,I]);let L=e.filter(e=>e.status===`running`).length,R=e.filter(e=>e.status===`completed`).length,z=e.filter(e=>e.status===`failed`).length,B=[...e].sort((e,t)=>t.createdAt-e.createdAt).slice(0,8);return(0,O.jsxs)(`div`,{className:`space-y-6`,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,O.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Dashboard`}),k&&(0,O.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:(0,O.jsx)(m,{variant:k.status===`ready`?`success`:`destructive`,children:k.status===`ready`?`Server Ready`:`Not Ready`})})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Server statistics`,children:[(0,O.jsx)(A,{icon:o,label:`Active Tasks`,value:d.activeTasks||L,color:`text-blue-400`}),(()=>{let e=j.filter(e=>e.status===`active`).length,t=j.length,n=j.filter(e=>e.status===`probation`).length,r=j.filter(e=>e.status===`retired`).length,i=[n>0?`${n} probation`:``,r>0?`${r} retired`:``].filter(Boolean).join(` · `);return(0,O.jsx)(A,{icon:l,label:`Role Health`,value:i?`${e}/${t} | ${i}`:`${e}/${t}`,color:r>0?`text-red-400`:n>0?`text-amber-400`:`text-emerald-400`})})(),(0,O.jsx)(A,{icon:i,label:`Roles`,value:j.length,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:t,label:`Cost Today`,value:b(d.totalCostToday),color:`text-purple-400`})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Additional statistics`,children:[(0,O.jsx)(A,{icon:n,label:`Completed`,value:R,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:c,label:`Failed`,value:z,color:`text-red-400`}),(0,O.jsx)(A,{icon:a,label:`Goals`,value:s.length,color:`text-orange-400`}),(0,O.jsx)(A,{icon:r,label:`Execution Pool`,value:`${M.active}/${M.max} | ${M.queued} queued`,color:`text-blue-400`})]}),(0,O.jsx)(`div`,{className:`grid gap-4 lg:grid-cols-1`,children:(0,O.jsxs)(_,{children:[(0,O.jsx)(h,{children:(0,O.jsx)(g,{children:`System Checks`})}),k?(0,O.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:Object.entries(k.checks).map(([e,t])=>(0,O.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md bg-slate-800/30 px-3 py-2`,children:[(0,O.jsx)(`div`,{className:t?`h-2 w-2 rounded-full bg-emerald-500`:`h-2 w-2 rounded-full bg-red-500`}),(0,O.jsx)(`span`,{className:`text-xs capitalize text-slate-300`,children:e})]},e))}):(0,O.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Loading...`})]})}),(0,O.jsxs)(_,{padding:!1,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between px-4 pt-4`,children:[(0,O.jsx)(g,{children:`Recent Tasks`}),(0,O.jsx)(u,{to:`/work`,className:`text-xs text-blue-400 hover:text-blue-300`,children:`View all`})]}),(0,O.jsx)(`div`,{className:`mt-3`,children:(0,O.jsxs)(E,{children:[(0,O.jsx)(x,{children:(0,O.jsxs)(w,{children:[(0,O.jsx)(S,{children:`ID`}),(0,O.jsx)(S,{children:`Prompt`}),(0,O.jsx)(S,{children:`Status`}),(0,O.jsx)(S,{children:`Role`}),(0,O.jsx)(S,{children:`Created`})]})}),(0,O.jsxs)(C,{children:[B.map(e=>(0,O.jsxs)(w,{children:[(0,O.jsx)(T,{children:(0,O.jsx)(u,{to:`/tasks/${e.id}`,className:`font-mono text-xs text-blue-400 hover:text-blue-300`,children:e.id.slice(0,8)})}),(0,O.jsx)(T,{children:y(e.prompt,60)}),(0,O.jsx)(T,{children:(0,O.jsx)(m,{variant:p(e.status),children:e.status})}),(0,O.jsx)(T,{children:(0,O.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:e.roleId?e.roleId.slice(0,12):`—`})}),(0,O.jsx)(T,{className:`text-xs text-slate-500`,children:v(e.createdAt)})]},e.id)),B.length===0&&(0,O.jsx)(w,{children:(0,O.jsx)(T,{colSpan:5,className:`text-center text-slate-500`,children:`No tasks yet`})})]})]})})]})]})}function A({icon:e,label:t,value:n,color:r}){return(0,O.jsxs)(_,{className:`flex items-center gap-3`,children:[(0,O.jsx)(`div`,{className:`rounded-md bg-slate-800 p-2 ${r}`,children:(0,O.jsx)(e,{size:16})}),(0,O.jsxs)(`div`,{children:[(0,O.jsx)(`div`,{className:`text-lg font-semibold text-slate-100`,children:n}),(0,O.jsx)(`div`,{className:`text-xs text-slate-500`,children:t})]})]})}export{k as Dashboard};
@@ -1 +0,0 @@
1
- import{t as e}from"./vendor-react-DLRtONKt.js";import{n as t}from"./dist-HyCSN_hp.js";var n=e();function r({icon:e,title:r,description:i,action:a,className:o}){return(0,n.jsxs)(`div`,{className:t(`flex flex-col items-center justify-center py-16 text-center`,o),children:[e&&(0,n.jsx)(`div`,{className:`mb-3 text-slate-600`,children:e}),(0,n.jsx)(`h3`,{className:`text-sm font-medium text-slate-400`,children:r}),i&&(0,n.jsx)(`p`,{className:`mt-1 text-xs text-slate-500`,children:i}),a&&(0,n.jsx)(`div`,{className:`mt-4`,children:a})]})}export{r as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{L as t,R as n,a as r,nt as i,o as a,v as o}from"./vendor-icons-CkI4-NxL.js";import{t as s}from"./vendor-react-DLRtONKt.js";import{n as c,r as l}from"./dist-HyCSN_hp.js";import{f as u,w as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";var h=e(i(),1),g=s(),_=h.forwardRef(({className:e,type:t,...n},r)=>(0,g.jsx)(`input`,{type:t,className:c(`flex h-8 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-1 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-50`,e),ref:r,...n}));_.displayName=`Input`;var v=/^[A-Za-z_][A-Za-z0-9_]*$/,y=/key|token|secret|password|credential/i;function b({envVars:e,onSave:i,mode:s,roleId:c,title:b=`Environment Variables`}){let[x,S]=(0,h.useState)([]),[C,w]=(0,h.useState)(!1),[T,E]=(0,h.useState)(new Set),[D,O]=(0,h.useState)([]),[k,A]=(0,h.useState)(!1);(0,h.useEffect)(()=>{S(Object.entries(e??{}).map(([e,t])=>({key:e,value:t,isNew:!1})))},[e]);let j=(0,h.useCallback)(async()=>{try{let e=await l(s===`global`?`/config/env-diff`:`/roles/${c}/env-diff`);O(s===`global`?e.diffs.filter(e=>e.configPath?.startsWith(`defaults.env.`)):e.diffs),A(e.envFileExists)}catch{}},[s,c]);(0,h.useEffect)(()=>{j()},[j]);let M=()=>{let t=Object.fromEntries(x.filter(e=>e.key.trim()).map(e=>[e.key,e.value]));return JSON.stringify(t)!==JSON.stringify(e)},N=()=>{S(e=>[...e,{key:``,value:``,isNew:!0}])},P=e=>{S(t=>t.filter((t,n)=>n!==e))},F=(e,t,n)=>{S(r=>r.map((r,i)=>i===e?{...r,[t]:n}:r))},I=e=>{E(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},L=()=>{let e=new Set;for(let t of x){let n=t.key.trim();if(n){if(!v.test(n))return`Invalid key format: "${n}"`;if(n.startsWith(`ANTHROPIC_`))return`ANTHROPIC_* keys are managed in the Anthropic section`;if(e.has(n))return`Duplicate key: "${n}"`;e.add(n)}}return e.size>100?`Maximum 100 environment variables`:null},R=async()=>{let e=L();if(e){d.error(e);return}w(!0);try{let e={};for(let t of x){let n=t.key.trim();n&&(e[n]=t.value)}s===`global`?await l(`/config/env`,{method:`PUT`,body:JSON.stringify(e)}):await l(`/roles/${c}`,{method:`PATCH`,body:JSON.stringify({envVars:e})}),d.success(`Environment variables saved`),i(),j()}catch(e){d.error(e instanceof Error?e.message:`Failed to save`)}finally{w(!1)}},z=async()=>{try{await l(s===`global`?`/config/sync-to-env`:`/roles/${c}/sync-to-env`,{method:`POST`}),d.success(`Synced DB to .env`),j()}catch(e){d.error(e instanceof Error?e.message:`Sync failed`)}},B=async()=>{try{await l(s===`global`?`/config/load-from-env`:`/roles/${c}/load-from-env`,{method:`POST`}),d.success(`Loaded .env to DB`),i(),j()}catch(e){d.error(e instanceof Error?e.message:`Load failed`)}};return(0,g.jsxs)(m,{children:[(0,g.jsxs)(f,{children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsx)(p,{className:`text-sm`,children:b}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsxs)(u,{variant:`ghost`,size:`sm`,onClick:N,children:[(0,g.jsx)(o,{size:14,className:`mr-1`}),` Add`]}),M()&&(0,g.jsx)(u,{size:`sm`,onClick:()=>void R(),disabled:C,children:C?`Saving...`:`Save`})]})]}),s===`global`&&(0,g.jsx)(`p`,{className:`text-xs text-slate-500 mt-1`,children:`ANTHROPIC_* variables are managed in the Anthropic section above.`})]}),D.length>0&&k&&(0,g.jsx)(`div`,{className:`mx-4 mb-3 rounded border border-yellow-800 bg-yellow-950/50 p-3`,children:(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsx)(r,{size:14,className:`text-yellow-400`}),(0,g.jsxs)(`span`,{className:`text-xs text-yellow-400`,children:[`.env and DB differ on `,D.length,` key(s): `,D.map(e=>e.envKey).join(`, `)]})]}),(0,g.jsxs)(`div`,{className:`flex gap-2`,children:[(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-xs`,onClick:()=>void z(),children:`DB → .env`}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-xs`,onClick:()=>void B(),children:`.env → DB`})]})]})}),(0,g.jsxs)(`div`,{className:`px-4 pb-4 space-y-2`,children:[x.length===0&&(0,g.jsx)(`p`,{className:`text-xs text-slate-500 py-2`,children:`No environment variables configured.`}),x.map((e,r)=>{let i=y.test(e.key),o=T.has(e.key)||e.isNew;return(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsx)(_,{className:`w-48 font-mono text-xs`,placeholder:`KEY_NAME`,value:e.key,onChange:e=>F(r,`key`,e.target.value)}),(0,g.jsx)(`span`,{className:`text-slate-600`,children:`=`}),(0,g.jsxs)(`div`,{className:`relative flex-1`,children:[(0,g.jsx)(_,{className:`font-mono text-xs pr-8`,type:i&&!o?`password`:`text`,placeholder:`value`,value:e.value,onChange:e=>F(r,`value`,e.target.value)}),i&&(0,g.jsx)(`button`,{type:`button`,className:`absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300`,onClick:()=>I(e.key),children:o?(0,g.jsx)(n,{size:12}):(0,g.jsx)(t,{size:12})})]}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-red-500 hover:text-red-300`,onClick:()=>P(r),children:(0,g.jsx)(a,{size:14})})]},r)})]})]})}export{b as t};
@@ -1,6 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{F as t,h as n,nt as r}from"./vendor-icons-CkI4-NxL.js";import{t as i}from"./vendor-react-DLRtONKt.js";import{r as a}from"./dist-HyCSN_hp.js";import{C as o,f as s,t as c}from"./index-rvaixveh.js";import{t as l}from"./Card-4mOZntHG.js";import{a as u}from"./format-DvtQjPZn.js";import{t as d}from"./EmptyState-BlgMMAr-.js";var f=e(r(),1),p=i();function m(){let e=o(e=>e.roles),r=o(e=>e.fetchRoles),[i,m]=(0,f.useState)([]),[h,g]=(0,f.useState)(!0),[_,v]=(0,f.useState)(`all`);(0,f.useEffect)(()=>{r()},[r]);let y=(0,f.useCallback)(async()=>{g(!0);try{let e=new URLSearchParams({limit:`50`});_!==`all`&&e.set(`roleId`,_),m(await a(`/evolution-audit?${e}`))}catch{m([])}finally{g(!1)}},[_]);(0,f.useEffect)(()=>{y()},[y]);let b=t=>t?e.find(e=>e.id===t)?.name??t.slice(0,8):`System`;return(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,p.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Evolution Audit`}),(0,p.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,p.jsxs)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:_,onChange:e=>v(e.target.value),children:[(0,p.jsx)(`option`,{value:`all`,children:`All roles`}),e.map(e=>(0,p.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,p.jsx)(s,{variant:`ghost`,size:`sm`,onClick:()=>void y(),children:(0,p.jsx)(n,{size:14})})]})]}),(0,p.jsx)(l,{children:h?(0,p.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,p.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):i.length===0?(0,p.jsx)(d,{icon:(0,p.jsx)(t,{size:32}),title:`No evolution records`,description:`Evolution occurs when roles accumulate enough task experience`}):(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[i.length,` records`]}),i.map(e=>(0,p.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,p.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,p.jsx)(c,{variant:`info`,children:b(e.roleId)}),(0,p.jsx)(`span`,{className:`text-xs text-slate-500`,children:u(e.timestamp)}),e.triggerTaskId&&(0,p.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`triggered by task `,e.triggerTaskId.slice(0,8)]})]}),e.diff.includes(`--- Diagnostic Report ---`)?(0,p.jsxs)(`div`,{className:`space-y-2`,children:[(0,p.jsxs)(`div`,{className:`rounded bg-slate-950 p-2`,children:[(0,p.jsx)(`p`,{className:`mb-1 text-[10px] font-medium text-slate-400`,children:`Diagnostic Report`}),(0,p.jsx)(`pre`,{className:`whitespace-pre-wrap font-mono text-xs text-slate-400`,children:e.diff.split(`--- Rules Diff ---`)[0]?.replace(`--- Diagnostic Report ---
2
- `,``).trim()})]}),(0,p.jsxs)(`div`,{className:`rounded bg-slate-950 p-2`,children:[(0,p.jsx)(`p`,{className:`mb-1 text-[10px] font-medium text-slate-400`,children:`Rules Changes`}),(0,p.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap font-mono text-xs`,children:(e.diff.split(`--- Rules Diff ---`)[1]??``).trim().split(`
3
- `).map((e,t)=>(0,p.jsxs)(`span`,{className:e.startsWith(`+`)?`text-green-400`:e.startsWith(`-`)?`text-red-400`:`text-slate-400`,children:[e,`
4
- `]},t))})]})]}):(0,p.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap rounded bg-slate-950 p-2 font-mono text-xs`,children:e.diff.split(`
5
- `).map((e,t)=>(0,p.jsxs)(`span`,{className:e.startsWith(`+`)?`text-green-400`:e.startsWith(`-`)?`text-red-400`:`text-slate-400`,children:[e,`
6
- `]},t))})]},e.id))]})})]})}export{m as Evolution};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,B as n,H as r,M as i,c as a,nt as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(o(),1),_=l();function v(){let{id:e}=s(),[o,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&(async()=>{try{let t=await u(`/goals/${e}`);l(t.goal),S(null);try{b((await u(`/strategies?role=${t.goal.roleId}`)).strategies??[])}catch{}}catch(e){S(e instanceof Error?e.message:`Failed to load goal`)}})()},[e]),x)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:x})]});if(!o)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let C=o.targetValue>0?Math.min(100,o.currentValue/o.targetValue*100):0,w=o.deadline>0&&o.deadline<Date.now()&&o.status!==`completed`;return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:(e=>e===`completed`?`success`:e===`executing`||e===`evaluating`?`warning`:e===`failed`?`destructive`:`secondary`)(o.status),children:o.status}),(0,_.jsx)(d,{variant:`outline`,children:o.roleId}),(0,_.jsx)(d,{variant:`outline`,children:o.metricType}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:o.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:o.name}),o.description&&(0,_.jsx)(`p`,{className:`text-sm text-slate-400 mt-1`,children:o.description})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:a,label:`Progress`,value:`${o.currentValue} / ${o.targetValue}`}),(0,_.jsx)(y,{icon:r,label:w?`Overdue`:`Deadline`,value:h(o.deadline),mono:!0}),(0,_.jsx)(y,{icon:n,label:`Budget`,value:`$${o.budgetUsd.toFixed(2)}`}),(0,_.jsx)(y,{icon:i,label:`Created`,value:h(o.createdAt),mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Progress`})}),(0,_.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,_.jsx)(`div`,{className:`flex-1 h-3 rounded-full bg-slate-700 overflow-hidden`,children:(0,_.jsx)(`div`,{className:`h-full rounded-full transition-all ${w?`bg-red-500`:`bg-blue-500`}`,style:{width:`${C}%`}})}),(0,_.jsxs)(`span`,{className:`text-sm text-slate-300 font-mono`,children:[C.toFixed(1),`%`]})]}),(0,_.jsxs)(`div`,{className:`mt-2 flex items-center justify-between text-xs text-slate-500`,children:[(0,_.jsxs)(`span`,{children:[o.currentValue,` current`]}),(0,_.jsxs)(`span`,{children:[o.targetValue,` target`]})]})]}),(o.deliverTo??[]).length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Delivery Targets`})}),(0,_.jsx)(`div`,{className:`space-y-1.5`,children:(o.deliverTo??[]).map((e,t)=>(0,_.jsx)(`div`,{className:`flex items-center gap-2 text-sm text-slate-300`,children:e.type===`channel`?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Channel`}),(0,_.jsx)(`span`,{className:`font-mono text-xs`,children:e.channelId.slice(0,8)}),e.chatId&&(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`chat: `,e.chatId.slice(0,8)]})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Session`}),(0,_.jsx)(`span`,{className:`text-xs text-slate-400`,children:`Chat session`})]})},t))})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(i,{size:14}),` Strategies (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between text-sm border-b border-slate-800 pb-2`,children:[(0,_.jsxs)(`div`,{children:[(0,_.jsx)(`span`,{className:`text-slate-200`,children:e.name}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:e.taskType})]}),(0,_.jsxs)(d,{variant:`outline`,children:[e.trialCount,` trials`]})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as GoalDetail};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,S as n,c as r,h as i,nt as a,o,t as s,v as c,x as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{C as f,a as p,c as m,d as h,f as g,i as _,l as v,n as ee,o as y,r as b,s as te,t as x,u as ne,w as S}from"./index-rvaixveh.js";import{n as C,r as w,t as T}from"./Card-4mOZntHG.js";import{n as E,t as D}from"./format-DvtQjPZn.js";import{t as O}from"./EmptyState-BlgMMAr-.js";var k=e(a(),1),A=u();function j({value:e,onChange:t,label:n=`Delivery Targets`}){let[r,i]=(0,k.useState)([]),[a,o]=(0,k.useState)(!1);(0,k.useEffect)(()=>{let e=!1;return Promise.all([d(`/channels`).catch(()=>({channels:[]})),d(`/chat/sessions`).catch(()=>({sessions:[]}))]).then(([t,n])=>{if(e)return;let r=new Map(t.channels.map(e=>[e.id,e])),a=[];for(let e of n.sessions)if(e.source.type===`channel`&&e.source.channelId&&e.source.chatId){let t=r.get(e.source.channelId);a.push({id:e.id,channelId:e.source.channelId,channelName:t?.name??e.source.channelId.slice(0,8),platform:t?.platform??`unknown`,chatId:e.source.chatId})}let o=new Set;i(a.filter(e=>{let t=`${e.channelId}:${e.chatId}`;return o.has(t)?!1:(o.add(t),!0)}))}),()=>{e=!0}},[]);let s=(t,n)=>e.some(e=>e.type===`channel`&&e.channelId===t&&e.chatId===n),c=(n,r)=>{s(n,r)?t(e.filter(e=>!(e.type===`channel`&&e.channelId===n&&e.chatId===r))):t([...e,{type:`channel`,channelId:n,chatId:r}])},l=e.filter(e=>e.type===`channel`).length;return(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(`label`,{className:`text-xs text-slate-400`,children:n}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!a),className:`mt-1 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-left text-sm text-slate-200 hover:border-slate-600 focus:border-blue-500 focus:outline-none`,children:l===0?`Default (current session)`:`${l} channel${l>1?`s`:``} selected`}),a&&(0,A.jsxs)(`div`,{className:`absolute z-10 mt-1 w-full rounded-md border border-slate-700 bg-slate-800 py-1 shadow-lg`,children:[r.length===0?(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-slate-500`,children:`No active channel conversations. Start a chat on WeChat/Telegram first.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`px-3 py-1 text-xs text-slate-500`,children:`Channel conversations`}),r.map(e=>(0,A.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-700`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:s(e.channelId,e.chatId),onChange:()=>c(e.channelId,e.chatId),className:`rounded border-slate-600 bg-slate-700`}),(0,A.jsx)(`span`,{className:`truncate font-medium`,children:e.channelName}),(0,A.jsxs)(`span`,{className:`text-slate-500`,children:[`(`,e.platform,`)`]})]},`${e.channelId}:${e.chatId}`))]}),l>0&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{t([]),o(!1)},className:`mt-1 w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-red-400 hover:bg-slate-700`,children:`Clear all`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!1),className:`w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-slate-500 hover:bg-slate-700`,children:`Done`})]})]})}var M={active:`paused`,paused:`active`,completed:`active`,failed:`active`},N={active:(0,A.jsx)(t,{size:12}),paused:(0,A.jsx)(l,{size:12}),completed:(0,A.jsx)(i,{size:12}),failed:(0,A.jsx)(i,{size:12})};function P(){let e=f(e=>e.goals),t=f(e=>e.fetchGoals),a=f(e=>e.updateGoal),u=f(e=>e.deleteGoal),[P,F]=(0,k.useState)(!1),[I,L]=(0,k.useState)(``),[R,z]=(0,k.useState)(!1),[B,V]=(0,k.useState)(null),[H,U]=(0,k.useState)(null),[W,G]=(0,k.useState)(``),[K,q]=(0,k.useState)(``),[J,Y]=(0,k.useState)([]),[X,Z]=(0,k.useState)([]),[Q,re]=(0,k.useState)([]),[$,ie]=(0,k.useState)([]);(0,k.useEffect)(()=>{t();let e=setInterval(()=>void t(),1e4);return()=>clearInterval(e)},[t]);let ae=async()=>{if(I.trim()){z(!0),V(null);try{await d(`/goals`,{method:`POST`,body:JSON.stringify({input:I.trim(),deliverTo:Q.length>0?Q:void 0,reportTo:$.length>0?$:void 0})}),L(``),F(!1),t()}catch(e){V(e instanceof Error?e.message:`Failed to create goal`)}finally{z(!1)}}};return(0,A.jsxs)(`div`,{className:`space-y-4`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,A.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Goals`}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{variant:`ghost`,size:`sm`,onClick:()=>void t(),children:(0,A.jsx)(i,{size:14})}),(0,A.jsxs)(g,{size:`sm`,onClick:()=>F(!P),children:[(0,A.jsx)(c,{size:14}),`New Goal`]})]})]}),P&&(0,A.jsxs)(T,{className:`space-y-3`,children:[(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none`,placeholder:`Describe your goal in natural language...`,rows:3,value:I,onChange:e=>L(e.target.value)}),(0,A.jsx)(j,{value:Q,onChange:re,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:$,onChange:ie,label:`Report To (status)`}),B&&(0,A.jsx)(`p`,{className:`text-xs text-red-400`,children:B}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{onClick:()=>void ae(),disabled:R||!I.trim(),children:R?`Creating...`:`Create`}),(0,A.jsx)(g,{variant:`ghost`,onClick:()=>F(!1),children:`Cancel`})]})]}),e.length===0?(0,A.jsx)(O,{icon:(0,A.jsx)(r,{size:32}),title:`No goals`,description:`Create a goal to start goal-driven task orchestration`}):(0,A.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:e.map(e=>{let t=e.targetValue>0?Math.min(100,Math.round(e.currentValue/e.targetValue*100)):0,r=new Date(e.deadline).getTime()<Date.now()&&e.status!==`completed`,i=H===e.id;return(0,A.jsxs)(T,{children:[(0,A.jsxs)(C,{children:[i?(0,A.jsx)(`input`,{className:`flex-1 rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:W,onChange:e=>G(e.target.value),autoFocus:!0}):(0,A.jsx)(w,{className:`text-slate-200 text-sm font-medium truncate max-w-[180px]`,children:e.name}),(0,A.jsx)(x,{variant:ee(e.status),children:e.status})]}),i?(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-xs text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none mb-3`,placeholder:`Description...`,rows:2,value:K,onChange:e=>q(e.target.value)}):e.description?(0,A.jsx)(`p`,{className:`text-xs text-slate-400 mb-3 line-clamp-2`,children:e.description}):null,i&&(0,A.jsxs)(`div`,{className:`mb-3 space-y-2`,children:[(0,A.jsx)(j,{value:J,onChange:Y,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:X,onChange:Z,label:`Report To (status)`})]}),(0,A.jsxs)(`div`,{className:`mb-3`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,A.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Progress`}),(0,A.jsxs)(`span`,{className:`font-mono text-xs text-slate-300`,children:[t,`%`]})]}),(0,A.jsx)(`div`,{className:`h-1.5 rounded-full bg-slate-800`,children:(0,A.jsx)(`div`,{className:`h-full rounded-full transition-all ${t>=100?`bg-emerald-500`:`bg-blue-500`}`,style:{width:`${t}%`}})}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between mt-1`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:[e.currentValue,` / `,e.targetValue]}),(0,A.jsx)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:e.metricType})]})]}),(0,A.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Role`}),(0,A.jsx)(x,{variant:`muted`,className:`text-[10px]`,children:e.roleId})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Budget`}),(0,A.jsx)(`span`,{className:`font-mono text-slate-300`,children:D(e.budgetUsd)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500 ${r?`text-red-400`:``}`,children:`Deadline`}),(0,A.jsx)(`span`,{className:`text-slate-300 ${r?`text-red-400`:``}`,children:E(e.deadline)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Created`}),(0,A.jsx)(`span`,{className:`text-slate-400`,children:E(e.createdAt)})]})]}),(0,A.jsx)(`div`,{className:`flex items-center gap-1 mt-3 pt-3 border-t border-slate-800`,children:i?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:async()=>{try{await a(e.id,{name:W,description:K,deliverTo:J,reportTo:X}),U(null),S.success(`Goal updated`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update`)}},children:`Save`}),(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:()=>U(null),children:(0,A.jsx)(s,{size:14})})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Edit`,onClick:()=>{U(e.id),G(e.name),q(e.description??``),Y(e.deliverTo??[]),Z(e.reportTo??[])},children:(0,A.jsx)(n,{size:14})}),(0,A.jsxs)(g,{size:`sm`,variant:`ghost`,title:`Change to ${M[e.status]}`,onClick:async()=>{try{await a(e.id,{status:M[e.status]}),S.success(`Status changed to ${M[e.status]}`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update status`)}},children:[N[e.status]??(0,A.jsx)(l,{size:12}),(0,A.jsx)(`span`,{className:`ml-1 text-xs`,children:M[e.status]})]}),(0,A.jsx)(`div`,{className:`ml-auto`,children:(0,A.jsxs)(b,{children:[(0,A.jsx)(h,{asChild:!0,children:(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Delete`,className:`text-red-400 hover:text-red-300`,children:(0,A.jsx)(o,{size:14})})}),(0,A.jsxs)(y,{children:[(0,A.jsxs)(v,{children:[(0,A.jsx)(ne,{children:`Delete goal`}),(0,A.jsxs)(te,{children:[`This will permanently delete "`,e.name,`". This action cannot be undone.`]})]}),(0,A.jsxs)(m,{children:[(0,A.jsx)(p,{children:`Cancel`}),(0,A.jsx)(_,{className:`bg-red-600 hover:bg-red-700`,onClick:async()=>{try{await u(e.id),S.success(`Goal deleted`)}catch(e){S.error(e instanceof Error?e.message:`Failed to delete`)}},children:`Delete`})]})]})]})})]})})]},e.id)})})]})}export{P as Goals,j as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,nt as n,o as r,s as i,x as a}from"./vendor-icons-CkI4-NxL.js";import{t as o}from"./vendor-react-DLRtONKt.js";import{C as s,f as c}from"./index-rvaixveh.js";import{t as l}from"./Card-4mOZntHG.js";import{t as u}from"./EmptyState-BlgMMAr-.js";var d=e(n(),1),f=o(),p={debug:`text-slate-500`,info:`text-blue-400`,warn:`text-amber-400`,error:`text-red-400`},m={adam:`text-purple-400`,manager:`text-cyan-400`,worker:`text-green-400`,scheduler:`text-orange-400`,api:`text-blue-400`,ws:`text-teal-400`,store:`text-yellow-400`,embedding:`text-pink-400`},h=[`adam`,`manager`,`worker`,`scheduler`,`api`,`ws`,`store`,`embedding`],g=[`debug`,`info`,`warn`,`error`];function _(){let e=s(e=>e.logs),n=(0,d.useRef)(null),[o,_]=(0,d.useState)(!0),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(null),C=(0,d.useMemo)(()=>e.filter(e=>!(y&&e.level!==y||x&&e.component!==x)),[e,y,x]);return(0,d.useEffect)(()=>{o&&n.current&&(n.current.scrollTop=n.current.scrollHeight)},[C,o]),(0,f.jsxs)(`div`,{className:`flex h-full flex-col gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,f.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Logs`}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>_(!o),title:o?`Pause auto-scroll`:`Resume auto-scroll`,children:o?(0,f.jsx)(t,{size:14}):(0,f.jsx)(a,{size:14})}),(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{s.setState({logs:[]})},title:`Clear logs`,children:(0,f.jsx)(r,{size:14})})]})]}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Level:`}),(0,f.jsxs)(`div`,{className:`flex gap-1`,children:[(0,f.jsx)(v,{active:y===null,onClick:()=>b(null),children:`All`}),g.map(e=>(0,f.jsx)(v,{active:y===e,onClick:()=>b(y===e?null:e),children:e},e))]})]}),(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Component:`}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[(0,f.jsx)(v,{active:x===null,onClick:()=>S(null),children:`All`}),h.map(e=>(0,f.jsx)(v,{active:x===e,onClick:()=>S(x===e?null:e),children:e},e))]})]})]}),(0,f.jsx)(l,{padding:!1,className:`flex-1 min-h-0`,children:C.length===0?(0,f.jsx)(u,{icon:(0,f.jsx)(i,{size:32}),title:`No log entries`,description:`Log events will appear here in real-time via WebSocket`}):(0,f.jsx)(`div`,{ref:n,className:`h-full max-h-[calc(100vh-280px)] overflow-y-auto p-3 font-mono text-xs leading-5`,children:C.map((e,t)=>{let n=new Date(e.timestamp).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3}),r=p[e.level]??`text-slate-400`,i=m[e.component]??`text-slate-400`;return(0,f.jsxs)(`div`,{className:`flex gap-2 hover:bg-slate-800/30 px-1 rounded`,children:[(0,f.jsx)(`span`,{className:`text-slate-600 shrink-0`,children:n}),(0,f.jsx)(`span`,{className:`w-12 shrink-0 uppercase ${r}`,children:e.level.padEnd(5)}),(0,f.jsxs)(`span`,{className:`w-20 shrink-0 ${i}`,children:[`[`,e.component,`]`]}),(0,f.jsx)(`span`,{className:`text-slate-300 break-all`,children:e.msg})]},t)})})}),(0,f.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-slate-500`,children:[(0,f.jsxs)(`span`,{children:[C.length,` entries `,C.length!==e.length&&`(${e.length} total)`]}),(0,f.jsx)(`span`,{children:o?`Auto-scrolling`:`Paused`})]})]})}function v({active:e,onClick:t,children:n}){return(0,f.jsx)(`button`,{onClick:t,className:`rounded px-2 py-0.5 text-xs transition-colors ${e?`bg-slate-700 text-slate-200`:`text-slate-500 hover:text-slate-300`}`,children:n})}export{_ as Logs};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{Q as t,f as n,h as r,nt as i}from"./vendor-icons-CkI4-NxL.js";import{t as a}from"./vendor-react-DLRtONKt.js";import{r as o}from"./dist-HyCSN_hp.js";import{C as s,f as c,t as l}from"./index-rvaixveh.js";import{t as u}from"./Card-4mOZntHG.js";import{a as d}from"./format-DvtQjPZn.js";import{t as f}from"./EmptyState-BlgMMAr-.js";var p=e(i(),1),m=a();function h(){let e=s(e=>e.roles),i=s(e=>e.fetchRoles),[a,h]=(0,p.useState)(``),[g,_]=(0,p.useState)([]),[v,y]=(0,p.useState)(!1),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(!1),[w,T]=(0,p.useState)(`all`),[E,D]=(0,p.useState)(new Set);(0,p.useEffect)(()=>{i()},[i]),(0,p.useEffect)(()=>{!a&&e.length>0&&h(e[0].id)},[e,a]);let O=(0,p.useCallback)(async()=>{if(a){y(!0);try{_((await o(`/memories/${a}?limit=100`)).memories)}catch{_([])}finally{y(!1)}}},[a]);(0,p.useEffect)(()=>{a&&O()},[a,O]);let k=async()=>{if(!(!b.trim()||!a)){C(!0);try{_((await o(`/memories/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:a,prompt:b.trim(),topK:20})})).memories)}catch{_([])}finally{C(!1)}}},A=()=>{x(``),O()},j=g.filter(e=>w===`high`?e.importance>3:w===`medium`?e.importance===3:w===`low`?e.importance<3:!0),M=e=>e>=4?`text-red-400`:e===3?`text-yellow-400`:`text-slate-500`;return(0,m.jsxs)(`div`,{className:`space-y-4`,children:[(0,m.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,m.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Memories`}),(0,m.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>void O(),children:(0,m.jsx)(r,{size:14})})]}),(0,m.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,m.jsx)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:a,onChange:e=>h(e.target.value),children:e.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))}),(0,m.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,m.jsx)(`input`,{className:`w-64 rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500 focus:outline-none`,value:b,onChange:e=>x(e.target.value),onKeyDown:e=>e.key===`Enter`&&void k(),placeholder:`Search memories...`}),(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:()=>void k(),disabled:S,children:(0,m.jsx)(n,{size:14})}),b&&(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:A,children:`Clear`})]}),(0,m.jsx)(`div`,{className:`flex gap-1`,children:[`all`,`high`,`medium`,`low`].map(e=>(0,m.jsx)(`button`,{className:`rounded px-2 py-1 text-xs transition-colors ${w===e?`bg-blue-600 text-white`:`bg-slate-800 text-slate-400 hover:bg-slate-700`}`,onClick:()=>T(e),children:e},e))})]}),(0,m.jsx)(u,{children:v||S?(0,m.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,m.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):j.length===0?(0,m.jsx)(f,{icon:(0,m.jsx)(t,{size:32}),title:`No memories`,description:b?`No results for this query`:`This agent has no memories yet`}):(0,m.jsxs)(`div`,{className:`space-y-3`,children:[(0,m.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[j.length,` memories`]}),j.map(e=>(0,m.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,m.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,m.jsx)(l,{variant:e.type===`reflection`?`info`:e.type===`thought`?`warning`:`muted`,children:e.type}),(0,m.jsx)(l,{variant:`muted`,children:e.sourceType}),(0,m.jsx)(`span`,{className:`text-xs font-medium ${M(e.importance)}`,children:`*`.repeat(e.importance)}),e.score!=null&&(0,m.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`score: `,e.score.toFixed(3)]})]}),(0,m.jsx)(`p`,{className:`whitespace-pre-wrap text-sm text-slate-300`,children:e.content}),(0,m.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1`,children:e.keywords.map(e=>(0,m.jsx)(`span`,{className:`rounded bg-slate-800 px-1.5 py-0.5 text-[10px] text-slate-500`,children:e},e))}),e.type===`reflection`&&e.evidence&&e.evidence.length>0&&(0,m.jsxs)(`div`,{className:`mt-2`,children:[(0,m.jsxs)(`button`,{className:`text-[10px] text-blue-400 hover:text-blue-300`,onClick:()=>D(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:[E.has(e.id)?`Hide`:`Show`,` evidence (`,e.evidence.length,` memories)`]}),E.has(e.id)&&(0,m.jsx)(`div`,{className:`mt-1.5 space-y-1 border-l-2 border-slate-800 pl-2`,children:e.evidence.map(e=>{let t=g.find(t=>t.id===e);return(0,m.jsx)(`div`,{className:`text-xs text-slate-500`,children:t?t.content.slice(0,120)+(t.content.length>120?`...`:``):(0,m.jsxs)(`span`,{className:`italic`,children:[`Memory `,e.slice(0,8),` (not in current view)`]})},e)})})]}),(0,m.jsxs)(`p`,{className:`mt-1.5 text-[10px] text-slate-600`,children:[d(e.createdAt),` | accessed `,e.retrievedCount,`x | last: `,d(e.lastAccessed)]})]},e.id))]})})]})}export{h as Memories};
@@ -1 +0,0 @@
1
- import"./vendor-icons-CkI4-NxL.js";import{r as e,t}from"./vendor-react-DLRtONKt.js";var n=t();function r(){return(0,n.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-4 text-slate-400`,children:[(0,n.jsx)(`span`,{className:`text-6xl font-bold text-slate-600`,children:`404`}),(0,n.jsx)(`p`,{className:`text-lg`,children:`Page not found`}),(0,n.jsx)(e,{to:`/`,className:`text-blue-400 hover:text-blue-300 underline`,children:`Back to Dashboard`})]})}export{r as default};