adam-agent-server 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/dist/App-RIYRYLKD.js +9 -0
  2. package/dist/adam-tools-YBKSTHVJ.js +1 -0
  3. package/dist/approval-handler-JYIS2PKQ.js +1 -0
  4. package/dist/audit-manager-7M2CDMP5.js +1 -0
  5. package/dist/bree-engine-Y24K4PXN.js +1 -0
  6. package/dist/channels-WMCY4QC3.js +1 -0
  7. package/dist/{channels-NAPXRIOX.js → channels-WZOYE4O4.js} +1 -1
  8. package/dist/chunk-2HN2TSP6.js +5 -0
  9. package/dist/{chunk-ROSOI75V.js → chunk-3RAFA6QK.js} +1 -1
  10. package/dist/{chunk-I5RUEOSQ.js → chunk-4TCP2AT7.js} +1 -1
  11. package/dist/{chunk-42RHY3Q3.js → chunk-6DXNXLYG.js} +1 -1
  12. package/dist/chunk-6HD6NYIB.js +1 -0
  13. package/dist/{chunk-GA7GEIXB.js → chunk-6YURWVQG.js} +1 -1
  14. package/dist/chunk-7IFLU3CY.js +4 -0
  15. package/dist/{chunk-QMKQBU3R.js → chunk-7LBDLAUQ.js} +1 -1
  16. package/dist/{chunk-BONI2HUN.js → chunk-AJVN3KPM.js} +1 -1
  17. package/dist/{chunk-4TBGFHYX.js → chunk-AR2IZMM2.js} +1 -1
  18. package/dist/chunk-B4WHT7DX.js +8 -0
  19. package/dist/{chunk-XFTRKHH2.js → chunk-BIIP363C.js} +1 -1
  20. package/dist/{chunk-KHPXEUSY.js → chunk-CDVIT7L5.js} +1 -1
  21. package/dist/{chunk-BCELBB5Q.js → chunk-EGS6U3V5.js} +2 -2
  22. package/dist/{chunk-NFSXJNPD.js → chunk-EJVUUIAV.js} +1 -1
  23. package/dist/{chunk-X26NKAXY.js → chunk-GMCIKDTC.js} +1 -1
  24. package/dist/{chunk-2C5U3CNX.js → chunk-GUQAIWCQ.js} +1 -1
  25. package/dist/chunk-IHP7JV6J.js +1 -0
  26. package/dist/chunk-JTMFEUDA.js +1 -0
  27. package/dist/chunk-KLQOILIJ.js +21 -0
  28. package/dist/{chunk-CREHL4BN.js → chunk-KVSO3KGZ.js} +1 -1
  29. package/dist/{chunk-YEV5YTS3.js → chunk-MPRAVJUO.js} +1 -1
  30. package/dist/{chunk-6VPL5CXB.js → chunk-OEKM2W3K.js} +1 -1
  31. package/dist/{chunk-TEMWI6U5.js → chunk-OFOVSC72.js} +1 -1
  32. package/dist/chunk-PMHNW5IL.js +49 -0
  33. package/dist/{chunk-35DBEYMG.js → chunk-Q4YE5BU7.js} +1 -1
  34. package/dist/{chunk-PT55643Q.js → chunk-QN6BEJF5.js} +1 -1
  35. package/dist/{chunk-64FIXWFL.js → chunk-SWPXG2CY.js} +1 -1
  36. package/dist/{chunk-CFTWJZVX.js → chunk-U5NRQNBB.js} +14 -14
  37. package/dist/{chunk-QC6QVNKP.js → chunk-UW3OJG7U.js} +3 -3
  38. package/dist/chunk-WVGNP2LQ.js +3 -0
  39. package/dist/cli.js +4 -4
  40. package/dist/{config-N2GMLTPU.js → config-EI3SCA4W.js} +1 -1
  41. package/dist/config-OH6Q2D2Y.js +1 -0
  42. package/dist/{db-S6HDMJ3B.js → db-4NY7ZOS2.js} +1 -1
  43. package/dist/{delivery-log-VAI35G5V.js → delivery-log-SC2ULFCK.js} +1 -1
  44. package/dist/engine-JKSNQQDM.js +1 -0
  45. package/dist/{evolution-audit-KCFDGNSM.js → evolution-audit-KUBXFUHI.js} +1 -1
  46. package/dist/index.js +10 -10
  47. package/dist/{learner-ABYVK33T.js → learner-UYDFNURD.js} +1 -1
  48. package/dist/{memories-3ZAV55YZ.js → memories-FQCRKMK6.js} +1 -1
  49. package/dist/{memory-extractor-BHHKD7X7.js → memory-extractor-FUOJ5D77.js} +2 -2
  50. package/dist/memory-service-ANR67OPY.js +1 -0
  51. package/dist/outbound-gateway-6FQRWYFF.js +1 -0
  52. package/dist/role-presets-LRP6P5O2.js +1 -0
  53. package/dist/{roles-LXRHEVUK.js → roles-3UTFKSHI.js} +1 -1
  54. package/dist/runtime-B2DP3JNB.js +1 -0
  55. package/dist/session-manager-VYKNKQ46.js +1 -0
  56. package/dist/{task-templates-XQNKAA4U.js → task-templates-PSP7GOJJ.js} +1 -1
  57. package/package.json +2 -1
  58. package/web/dist/assets/Card-4mOZntHG.js +1 -0
  59. package/web/dist/assets/ChannelDetail-e6rVX_y8.js +1 -0
  60. package/web/dist/assets/Channels-DJvZPKer.js +12 -0
  61. package/web/dist/assets/Chat-hTZdEwyE.js +1 -0
  62. package/web/dist/assets/Dashboard-B4rL_ePs.js +1 -0
  63. package/web/dist/assets/{EmptyState-DBFJc4PL.js → EmptyState-BlgMMAr-.js} +1 -1
  64. package/web/dist/assets/EnvVarEditor-C8kRWejV.js +1 -0
  65. package/web/dist/assets/Evolution-BGwFCo7X.js +6 -0
  66. package/web/dist/assets/GoalDetail-BH2ku-0t.js +1 -0
  67. package/web/dist/assets/Goals-DynDtpMC.js +1 -0
  68. package/web/dist/assets/Logs-CyJFouE6.js +1 -0
  69. package/web/dist/assets/Memories-ClcFD7OG.js +1 -0
  70. package/web/dist/assets/{NotFound-Cidygwnn.js → NotFound-CSjhzSGa.js} +1 -1
  71. package/web/dist/assets/Plugins-SNOQNNcL.js +1 -0
  72. package/web/dist/assets/RoleDetail-vlTPiYwY.js +33 -0
  73. package/web/dist/assets/Roles-CFcuHIvA.js +1 -0
  74. package/web/dist/assets/Settings-C9Kuz-6D.js +1 -0
  75. package/web/dist/assets/Strategies-DZWlQCHp.js +1 -0
  76. package/web/dist/assets/Switch-DOi0EFHj.js +1 -0
  77. package/web/dist/assets/Table-BxbnOSbq.js +1 -0
  78. package/web/dist/assets/TaskDetail-DjmmnldI.js +2 -0
  79. package/web/dist/assets/Work-CvESHC3Y.js +1 -0
  80. package/web/dist/assets/index-BFmC20R2.js +52 -0
  81. package/web/dist/assets/index-CaocwyO8.css +2 -0
  82. package/web/dist/assets/{vendor-icons-ZPvC5PUS.js → vendor-icons-CkI4-NxL.js} +1 -1
  83. package/web/dist/assets/{vendor-react--nRVf2Ep.js → vendor-react-DLRtONKt.js} +1 -1
  84. package/web/dist/assets/vendor-state-B_-GdGNJ.js +1 -0
  85. package/web/dist/index.html +5 -5
  86. package/dist/App-SCPYTYGQ.js +0 -9
  87. package/dist/adam-tools-FNJJT7AA.js +0 -1
  88. package/dist/approval-handler-UDWAC5MF.js +0 -4
  89. package/dist/audit-manager-SCX53YJT.js +0 -1
  90. package/dist/bree-engine-2DB2QECM.js +0 -1
  91. package/dist/channels-PQCV74ZI.js +0 -1
  92. package/dist/chunk-3TIHZZMK.js +0 -1
  93. package/dist/chunk-7KCBFM2C.js +0 -52
  94. package/dist/chunk-FXFHGIY6.js +0 -8
  95. package/dist/chunk-IZQI6QQ7.js +0 -1
  96. package/dist/chunk-NQHTOFQP.js +0 -1
  97. package/dist/chunk-REKCZ3GY.js +0 -1
  98. package/dist/chunk-U3XVAAXA.js +0 -17
  99. package/dist/config-L4R273R3.js +0 -1
  100. package/dist/engine-E67UAI3G.js +0 -1
  101. package/dist/memory-service-5QHTKIUU.js +0 -1
  102. package/dist/outbound-gateway-ZFKSN2UT.js +0 -1
  103. package/dist/role-presets-OTU2M37Y.js +0 -1
  104. package/dist/runtime-UCOE6LNN.js +0 -1
  105. package/dist/session-manager-RPXFZKMY.js +0 -1
  106. package/web/dist/assets/Card-BecEmnPW.js +0 -1
  107. package/web/dist/assets/ChannelDetail-BajTUEU0.js +0 -1
  108. package/web/dist/assets/Channels-Bhy6rP_t.js +0 -12
  109. package/web/dist/assets/Chat-Dvt_Oo7d.js +0 -1
  110. package/web/dist/assets/Dashboard-DlrAor-C.js +0 -1
  111. package/web/dist/assets/Evolution-Dlsnnr4G.js +0 -6
  112. package/web/dist/assets/GoalDetail-BuUxwYdd.js +0 -1
  113. package/web/dist/assets/Goals-CkPQOev6.js +0 -1
  114. package/web/dist/assets/Logs-D33PqDAd.js +0 -1
  115. package/web/dist/assets/Memories-D31dbUM6.js +0 -1
  116. package/web/dist/assets/Plugins-XlBr07x8.js +0 -1
  117. package/web/dist/assets/RoleDetail-rZFlgXzh.js +0 -33
  118. package/web/dist/assets/Roles-d29AC6Kh.js +0 -1
  119. package/web/dist/assets/Settings-Bjh_RXYf.js +0 -1
  120. package/web/dist/assets/Strategies-Cf4ghknk.js +0 -1
  121. package/web/dist/assets/Switch-CxzUYL49.js +0 -1
  122. package/web/dist/assets/Table-tkJ-cuiE.js +0 -1
  123. package/web/dist/assets/TaskDetail-jMBJbaRU.js +0 -2
  124. package/web/dist/assets/Work-CCLTkitf.js +0 -1
  125. package/web/dist/assets/index-CVubgAlC.css +0 -2
  126. package/web/dist/assets/index-Ds41VvOC.js +0 -52
  127. package/web/dist/assets/vendor-state-CH64feAE.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as ee}from"./chunk-5V36ACKZ.js";import{a as _e,c as Me,d as Le,e as Q,f as Pe,g as xe,h as Ce,i as ct,j as Ee,k as Fe,l as U,n as fe}from"./chunk-6VPL5CXB.js";import{b as ke,c as ue,e as Re}from"./chunk-NFSXJNPD.js";import{b as H}from"./chunk-X26NKAXY.js";import{a as Ge,c as he,e as Ve}from"./chunk-GA7GEIXB.js";import{a as X,b as k,c as Z,d as je,e as Oe}from"./chunk-KHPXEUSY.js";import{a as J,b as h,c as D,d as P}from"./chunk-ROSOI75V.js";import{j as ge}from"./chunk-YEV5YTS3.js";import{d as me}from"./chunk-64FIXWFL.js";import{b as z,e as de,f as K}from"./chunk-U3XVAAXA.js";import{a as pe}from"./chunk-L7JP7DUO.js";import{g as De}from"./chunk-I5RUEOSQ.js";import{a as Ae,b as $,c as Ne,f as $e,g as Ue}from"./chunk-42RHY3Q3.js";import{d as I,g as ve}from"./chunk-REKCZ3GY.js";import{d as Te,e as T,g as A,h as N,i as Se,j as ce,k as Y}from"./chunk-FXFHGIY6.js";import{b,d as le}from"./chunk-CREHL4BN.js";import{c as w,d as Ie,h as E}from"./chunk-INNDBLZE.js";import{f as _}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Lt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";Y();K();import{v4 as O}from"uuid";le();function dt(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 j(e){b().prepare(`
1
+ import{a as ee}from"./chunk-5V36ACKZ.js";import{a as _e,c as Me,d as Le,e as Q,f as Pe,g as xe,h as Ce,i as ct,j as Ee,k as Fe,l as U,n as fe}from"./chunk-OEKM2W3K.js";import{b as ke,c as ue,e as Re}from"./chunk-EJVUUIAV.js";import{b as H}from"./chunk-GMCIKDTC.js";import{a as Ge,c as he,e as Ve}from"./chunk-6YURWVQG.js";import{a as X,b as k,c as Z,d as je,e as Oe}from"./chunk-CDVIT7L5.js";import{a as J,b as h,c as D,d as P}from"./chunk-3RAFA6QK.js";import{j as ge}from"./chunk-MPRAVJUO.js";import{d as me}from"./chunk-SWPXG2CY.js";import{f as z,i as de,j as K}from"./chunk-KLQOILIJ.js";import{a as pe}from"./chunk-L7JP7DUO.js";import{g as De}from"./chunk-4TCP2AT7.js";import{a as Ae,b as $,c as Ne,f as $e,g as Ue}from"./chunk-6DXNXLYG.js";import{d as I,j as ve}from"./chunk-6HD6NYIB.js";import{d as Te,e as T,g as A,h as N,i as Se,j as ce,k as Y}from"./chunk-B4WHT7DX.js";import{b,d as le}from"./chunk-KVSO3KGZ.js";import{c as w,d as Ie,h as E}from"./chunk-INNDBLZE.js";import{f as _}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Lt,tool as p}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";Y();K();import{v4 as O}from"uuid";le();function dt(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 j(e){b().prepare(`
2
2
  INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
3
3
  weight, calibration_factor, created_at)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -65,7 +65,7 @@ Complete tasks with high quality.
65
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
66
 
67
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"}}};E();Ee();import{v4 as y}from"uuid";import{spawnSync as Ze}from"child_process";import{createRequire as It}from"module";import{dirname as Tt,join as et}from"path";import{openSync as St,readFileSync as kt,unlinkSync as Rt}from"fs";var _t=3e4,tt=12e4;function rt(){let t=It(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return et(Tt(t),"cli.js")}function V(e,t){let r=rt(),n=t?.timeout??_t;if(t?.json){let i=et("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),s=St(i,"w");try{let l=Ze("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 kt(i,"utf-8")}finally{try{Rt(i)}catch{}}}let o=Ze("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 nt(){let e=V(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function ye(e,t="user",r){return V(["plugin","install",e,"--scope",t],{cwd:r,timeout:tt})}function we(e,t,r){return V(["plugin","uninstall",e],{cwd:r,timeout:tt})}function ot(e,t){return V(["plugin","enable",e])}function at(e,t){return V(["plugin","disable",e])}function yn(){try{return!!rt()}catch{return!1}}E();import*as it from"crypto";var B=w("api"),W=class{cancelTask(t){let r=h(t);r&&(D(t,{status:"cancelled",completedAt:Date.now()}),pe.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),B.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return B.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=ke(t);if(!i)return B.warn({planId:t},"Plan not found or already resolved"),!1;let s=h(i.taskId);return s?(Re(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&_e({id:it.randomUUID(),roleId:i.roleId,taskPattern:s.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:s.id}),pe.emit({type:"plan_approval_decision",taskId:s.id,planId:t,decision:r,approvalType:n,reason:o}),B.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(B.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as Pt}from"fs";var se=w("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function R(e){let{listChannels:t}=await import("./channels-NAPXRIOX.js"),r=t(),{listSessions:n}=await import("./session-manager-RPXFZKMY.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}):se.warn({channelName:s.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return i}async function xt(e){let{listRoles:t}=await import("./roles-LXRHEVUK.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var Ct={goalId:a.string()},Et={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},Dt={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},L=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()})]),At={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(L).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(L).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()},Nt={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},$t={roleId:a.string(),taskType:a.string(),name:a.string().optional()},Ut={status:a.string().optional(),limit:a.number().optional()},jt={taskId:a.string(),roleId:a.string()},Ot={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},Ft={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).")},Gt={roleId:a.string().optional(),limit:a.number().optional()},Vt={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()},Bt={roleId:a.string(),reason:a.string().optional()},Wt={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(L).optional().describe("Where to deliver goal completion notifications.")},qt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Jt={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Ht={enabled:a.boolean().optional()},Yt={},zt={},Kt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Qt={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Xt={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.")},Zt={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},er={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.")},tr={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},rr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},nr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},or={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ar={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ir={},sr={},lr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},cr={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},dr={taskId:a.string().describe("Task ID to cancel.")},ur={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},pr={roleId:a.string().describe("Role ID to delete.")},mr={},gr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},fr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},hr={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()},br={templateId:a.string().describe("Template ID to delete.")},yr={templateId:a.string().describe("Template ID to run immediately.")},wr={enabled:a.boolean().optional().describe("Filter by enabled status.")},vr={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).")},Ir={ruleId:a.string().describe("Delivery rule ID to delete.")},Tr={roleId:a.string().optional().describe("Role ID to filter strategies by.")},st=[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.",Ct,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.",Et,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(),Z(e.goalId,t)),c({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Dt,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.
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"}}};E();Ee();import{v4 as y}from"uuid";import{spawnSync as Ze}from"child_process";import{createRequire as It}from"module";import{dirname as Tt,join as et}from"path";import{openSync as St,readFileSync as kt,unlinkSync as Rt}from"fs";var _t=3e4,tt=12e4;function rt(){let t=It(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return et(Tt(t),"cli.js")}function V(e,t){let r=rt(),n=t?.timeout??_t;if(t?.json){let i=et("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),s=St(i,"w");try{let l=Ze("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 kt(i,"utf-8")}finally{try{Rt(i)}catch{}}}let o=Ze("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 nt(){let e=V(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function ye(e,t="user",r){return V(["plugin","install",e,"--scope",t],{cwd:r,timeout:tt})}function we(e,t,r){return V(["plugin","uninstall",e],{cwd:r,timeout:tt})}function ot(e,t){return V(["plugin","enable",e])}function at(e,t){return V(["plugin","disable",e])}function yn(){try{return!!rt()}catch{return!1}}E();import*as it from"crypto";var B=w("api"),W=class{cancelTask(t){let r=h(t);r&&(D(t,{status:"cancelled",completedAt:Date.now()}),pe.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),B.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return B.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let i=ke(t);if(!i)return B.warn({planId:t},"Plan not found or already resolved"),!1;let s=h(i.taskId);return s?(Re(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&_e({id:it.randomUUID(),roleId:i.roleId,taskPattern:s.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:i.plan.overallRisk,createdAt:Date.now(),createdByTaskId:s.id}),pe.emit({type:"plan_approval_decision",taskId:s.id,planId:t,decision:r,approvalType:n,reason:o}),B.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(B.warn({planId:t},"Task not found for plan"),!1)}};import{existsSync as Pt}from"fs";var se=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-VYKNKQ46.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}):se.warn({channelName:s.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return i}async function xt(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 Ct={goalId:a.string()},Et={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},Dt={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},L=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()})]),At={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(L).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(L).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()},Nt={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},$t={roleId:a.string(),taskType:a.string(),name:a.string().optional()},Ut={status:a.string().optional(),limit:a.number().optional()},jt={taskId:a.string(),roleId:a.string()},Ot={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},Ft={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).")},Gt={roleId:a.string().optional(),limit:a.number().optional()},Vt={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()},Bt={roleId:a.string(),reason:a.string().optional()},Wt={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(L).optional().describe("Where to deliver goal completion notifications.")},qt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Jt={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Ht={enabled:a.boolean().optional()},Yt={},zt={},Kt={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(L).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(L).optional().describe("Where to send status reports (completion summary).")},Qt={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Xt={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.")},Zt={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},er={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.")},tr={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},rr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},nr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},or={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ar={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},ir={},sr={},lr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},cr={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},dr={taskId:a.string().describe("Task ID to cancel.")},ur={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},pr={roleId:a.string().describe("Role ID to delete.")},mr={},gr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},fr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},hr={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()},br={templateId:a.string().describe("Template ID to delete.")},yr={templateId:a.string().describe("Template ID to run immediately.")},wr={enabled:a.boolean().optional().describe("Filter by enabled status.")},vr={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).")},Ir={ruleId:a.string().describe("Delivery rule ID to delete.")},Tr={roleId:a.string().optional().describe("Role ID to filter strategies by.")},st=[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.",Ct,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.",Et,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(),Z(e.goalId,t)),c({success:!0})}),p("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Dt,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
69
 
70
70
  Goal: ${e.goalDescription}
71
71
 
@@ -80,4 +80,4 @@ Rules:
80
80
  Subtask ${o+1}/${r}`;J({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.",At,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let C=N("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:C})}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[C,S]of Object.entries(i))if(S.some(lt=>o.includes(lt))){s=C;break}let l,d=e.prompt,u=v.selectStrategy(e.roleId,s);u?.promptTemplate&&(d=`${u.promptTemplate}
81
81
 
82
82
  ## Task
83
- ${e.prompt}`,l=u.id);let m=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(m=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:m,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await R(e.deliverTo):void 0,q=e.reportTo?await R(e.reportTo):void 0;J({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:f,reportTo:q,config:g,createdAt:Date.now()});let{serverBus:x}=await import("./server-bus-GEGVMSCA.js");return x.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.",Nt,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=oe(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.",$t,async e=>{let{roleId:t,taskType:r}=e;await ie.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.",Ut,async e=>{let t=e.status;return c(je(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>k(e.goalId)?(Oe(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)?(Z(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.",jt,async e=>{let{taskId:t,roleId:r}=e;if(!h(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(D(t,{roleId:r}),se.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}`})}),...Fe(),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.",Ot,async e=>{if(e.taskId){let r=h(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(P(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Ft,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),A(e.roleId,r),c({success:!0})}),p("view_audit_log","View the evolution audit log for role changes.",Gt,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-KCFDGNSM.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.",Jt,async e=>{let r=N(e.status,e.limit??50,0).map(n=>{let o=fe(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.",Vt,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 Te(r),z(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).",Bt,async e=>T(e.roleId)?(A(e.roleId,{status:"retired"}),se.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.",Wt,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};X(o),We(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.",qt,async e=>{let{createTaskTemplate:t}=await import("./task-templates-XQNKAA4U.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-XQNKAA4U.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(!Pt(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-ZFKSN2UT.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.",Ht,async e=>{let t=me(e.enabled),r=[...ge("active"),...ge("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.",Yt,async()=>{let e=I(),t=P("running"),r=P("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.",Kt,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=N("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;Ae({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-2DB2QECM.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=$(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."});$e(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-2DB2QECM.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.",Qt,async e=>{let t=Me(),r=Q(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(K(),_(de)),{getRole:i}=(Y(),_(ce)),{listInstalledPlugins:s}=(Ee(),_(ct)),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.",Xt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return ye(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.",Zt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),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})}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.",er,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 A(e.roleId,{mcpServers:n}),z(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.",tr,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 A(e.roleId,{mcpServers:r}),z(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.",zt,async()=>{let{listTaskTemplates:e}=await import("./task-templates-XQNKAA4U.js"),t=I(),r=N(void 0,100,0),n=me(),o=e(!0,100,0),i=P("running"),s=P("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=fe(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:Q().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).",rr,async e=>{try{return ot(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).",nr,async e=>{try{return at(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).",or,async e=>{try{return ye(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.",ar,async e=>{try{return we(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).",ir,async()=>{try{let e=nt(),t=Q();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.",sr,async()=>{let e=xe();return c({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",lr,async e=>{let t=Pe(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Le(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.",cr,async e=>{let{getRole:t}=await import("./roles-LXRHEVUK.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=Ce(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.",dr,async e=>{let t=h(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;D(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.",ur,async e=>{let t=H(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.",pr,async e=>T(e.roleId)?(Se(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).",mr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-UCOE6LNN.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.",gr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-UCOE6LNN.js"),{setConfigValue:r}=await import("./config-N2GMLTPU.js"),n=ve(e.updates,r);if(e.updates["logging.level"]&&Ie(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.",fr,async e=>{let t=De(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.).",hr,async e=>{let t=$(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),Ne(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",br,async e=>$(e.templateId)?(Ue(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).",yr,async e=>{let t=$(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.",wr,async e=>{let t=he(e.enabled);return c({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",vr,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 Ge(r),c({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",Ir,async e=>he().find(n=>n.id===e.ruleId)?(Ve(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.",Tr,async e=>{let t;if(e.roleId)t=ze(e.roleId);else{let{getDb:r}=await import("./db-S6HDMJ3B.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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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 Xn(){return st.map(e=>e.name).sort().join(",")}function Zn(){return Lt({name:"adam-tools",version:"1.0.0",tools:st})}export{W as a,xr as b,Cr as c,We as d,rn as e,ze as f,v as g,nt as h,ye as i,we as j,ot as k,at as l,yn as m,Xn as n,Zn as o};
83
+ ${e.prompt}`,l=u.id);let m=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(m=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:m,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await R(e.deliverTo):void 0,q=e.reportTo?await R(e.reportTo):void 0;J({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:f,reportTo:q,config:g,createdAt:Date.now()});let{serverBus:x}=await import("./server-bus-GEGVMSCA.js");return x.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.",Nt,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=oe(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.",$t,async e=>{let{roleId:t,taskType:r}=e;await ie.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.",Ut,async e=>{let t=e.status;return c(je(t,e.limit??10,0))}),p("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>k(e.goalId)?(Oe(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)?(Z(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.",jt,async e=>{let{taskId:t,roleId:r}=e;if(!h(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(D(t,{roleId:r}),se.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}`})}),...Fe(),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.",Ot,async e=>{if(e.taskId){let r=h(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(P(t,e.limit??100,0))}),p("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",Ft,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),A(e.roleId,r),c({success:!0})}),p("view_audit_log","View the evolution audit log for role changes.",Gt,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.",Jt,async e=>{let r=N(e.status,e.limit??50,0).map(n=>{let o=fe(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.",Vt,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 Te(r),z(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).",Bt,async e=>T(e.roleId)?(A(e.roleId,{status:"retired"}),se.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.",Wt,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};X(o),We(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.",qt,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(!Pt(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.",Ht,async e=>{let t=me(e.enabled),r=[...ge("active"),...ge("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.",Yt,async()=>{let e=I(),t=P("running"),r=P("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.",Kt,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=N("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;Ae({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-Y24K4PXN.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=$(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."});$e(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-Y24K4PXN.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.",Qt,async e=>{let t=Me(),r=Q(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(K(),_(de)),{getRole:i}=(Y(),_(ce)),{listInstalledPlugins:s}=(Ee(),_(ct)),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.",Xt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return ye(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.",Zt,async e=>{let{getRole:t}=(Y(),_(ce)),{getRoleWorkspacePath:r}=(K(),_(de)),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})}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.",er,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 A(e.roleId,{mcpServers:n}),z(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.",tr,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 A(e.roleId,{mcpServers:r}),z(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.",zt,async()=>{let{listTaskTemplates:e}=await import("./task-templates-PSP7GOJJ.js"),t=I(),r=N(void 0,100,0),n=me(),o=e(!0,100,0),i=P("running"),s=P("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=fe(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:Q().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).",rr,async e=>{try{return ot(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).",nr,async e=>{try{return at(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).",or,async e=>{try{return ye(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.",ar,async e=>{try{return we(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).",ir,async()=>{try{let e=nt(),t=Q();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.",sr,async()=>{let e=xe();return c({sources:e})}),p("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",lr,async e=>{let t=Pe(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Le(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.",cr,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=Ce(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.",dr,async e=>{let t=h(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;D(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.",ur,async e=>{let t=H(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.",pr,async e=>T(e.roleId)?(Se(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).",mr,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.",gr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-B2DP3JNB.js"),{setConfigValue:r}=await import("./config-EI3SCA4W.js"),n=ve(e.updates,r);if(e.updates["logging.level"]&&Ie(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.",fr,async e=>{let t=De(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.).",hr,async e=>{let t=$(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),Ne(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),p("delete_template","Delete a task template by ID.",br,async e=>$(e.templateId)?(Ue(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).",yr,async e=>{let t=$(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.",wr,async e=>{let t=he(e.enabled);return c({count:t.length,rules:t})}),p("create_delivery_rule","Create a new delivery rule for event-driven result routing.",vr,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 Ge(r),c({success:!0,ruleId:t,rule:r})}),p("delete_delivery_rule","Delete a delivery rule by ID.",Ir,async e=>he().find(n=>n.id===e.ruleId)?(Ve(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.",Tr,async e=>{let t;if(e.roleId)t=ze(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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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=ue(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new W().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 Xn(){return st.map(e=>e.name).sort().join(",")}function Zn(){return Lt({name:"adam-tools",version:"1.0.0",tools:st})}export{W as a,xr as b,Cr as c,We as d,rn as e,ze as f,v as g,nt as h,ye as i,we as j,ot as k,at as l,yn as m,Xn as n,Zn as o};
@@ -0,0 +1,3 @@
1
+ import{b as y}from"./chunk-2HN2TSP6.js";import{b as S}from"./chunk-EGS6U3V5.js";import{f as C}from"./chunk-6YURWVQG.js";import{b as g}from"./chunk-3RAFA6QK.js";import{b as v}from"./chunk-AJVN3KPM.js";import{e as m}from"./chunk-AR2IZMM2.js";import{b as R}from"./chunk-SWPXG2CY.js";import{a as k,b as P,c as o,d as h,e as T,f as x,g as E}from"./chunk-OFOVSC72.js";import{a as f}from"./chunk-L7JP7DUO.js";import{c as w,h as _}from"./chunk-INNDBLZE.js";_();import{v4 as M}from"uuid";var l=w("admin"),I=new Map,u=null,p=null,c=null,D=class{constructor(){f.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),f.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{l.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),l.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=y(r),{sendApprovalToChannel:b}=await import("./approval-handler-JYIS2PKQ.js");await b(i.channelId,i.chatId,n,e,d)}let a=y(r)+`
2
+
3
+ Task: ${e}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=m(e);if(!n)return null;let r=v(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=C(e,n);if(i.length!==0){l.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){l.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:M(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+k,source:"rule"};P(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=S();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=R(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?(h(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful")):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?(h(e.id),l.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful")):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),l.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=I.get(e.id);t||(t=[],I.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=m(e);if(!r)return!1;let t=v(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&(!n.chatId||t.source.chatId===n.chatId):!1}catch{return!1}}async retryPending(){let e=T("rule",50),n=x("rule",50),r=[...e,...n];if(r.length!==0){l.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function $(){return c}function H(){c||(c=new D,u=setInterval(()=>{c?.retryPending().catch(s=>{l.error({error:s},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let s=E();s>0&&l.info({cleaned:s},"Expired delivery log entries cleaned up")}catch(s){l.error({error:s},"Delivery cleanup failed")}},36e5),l.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function J(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,I.clear(),l.info("DeliveryEngine stopped")}export{D as a,$ as b,H as c,J as d};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as G,b as h,c as W,e as V}from"./chunk-VRP4LTHY.js";import{a as z,b as B,e as J,h as q}from"./chunk-7KCBFM2C.js";import"./chunk-42RHY3Q3.js";import{d as _}from"./chunk-REKCZ3GY.js";import{c as R,e as K,g as ue}from"./chunk-QMKQBU3R.js";import{b as H,c as j,d as de}from"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Command as Te}from"commander";import{fork as me}from"child_process";import{readFileSync as M,writeFileSync as ge,existsSync as v,unlinkSync as $,mkdirSync as pe,openSync as fe}from"fs";import{join as D}from"path";import{homedir as he}from"os";var P=D(he(),".adam"),S=D(P,"adam.pid"),k=D(P,"adam.port"),b=D(P,"server.log");function ve(){v(P)||pe(P,{recursive:!0})}function C(){if(!v(S))return null;let e=parseInt(M(S,"utf-8").trim(),10);return isNaN(e)?null:e}function ye(){if(!v(k))return null;let e=parseInt(M(k,"utf-8").trim(),10);return isNaN(e)?null:e}function A(e){try{return process.kill(e,0),!0}catch{return!1}}async function N(){ve();let e=C();if(e&&A(e))throw new Error(`Server already running (PID ${e})`);v(S)&&$(S),v(k)&&$(k);let o=fe(b,"a"),t=D(z,"dist/index.js"),n=me(t,[],{detached:!0,stdio:["ignore",o,o,"ipc"]}),l=await new Promise((i,c)=>{let p=setTimeout(()=>{n.kill(),c(new Error(`Server start timeout. Check logs: ${b}`))},1e4);n.on("message",a=>{if(a&&typeof a=="object"&&a.type==="ready"){clearTimeout(p);let s=a.port;s?i(s):c(new Error("Ready signal received but missing port"))}}),n.on("exit",a=>{clearTimeout(p);let s=v(b)?M(b,"utf-8").split(`
2
+ import{a as G,b as h,c as W,e as V}from"./chunk-VRP4LTHY.js";import{a as B,b as J,d as q}from"./chunk-PMHNW5IL.js";import"./chunk-6DXNXLYG.js";import{b as H}from"./chunk-7IFLU3CY.js";import{d as _}from"./chunk-6HD6NYIB.js";import{c as R,e as z,g as ue}from"./chunk-7LBDLAUQ.js";import{b as j,c as K,d as de}from"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Command as Te}from"commander";import{fork as me}from"child_process";import{readFileSync as M,writeFileSync as ge,existsSync as v,unlinkSync as $,mkdirSync as pe,openSync as fe}from"fs";import{join as D}from"path";import{homedir as he}from"os";var P=D(he(),".adam"),S=D(P,"adam.pid"),k=D(P,"adam.port"),b=D(P,"server.log");function ve(){v(P)||pe(P,{recursive:!0})}function C(){if(!v(S))return null;let e=parseInt(M(S,"utf-8").trim(),10);return isNaN(e)?null:e}function ye(){if(!v(k))return null;let e=parseInt(M(k,"utf-8").trim(),10);return isNaN(e)?null:e}function A(e){try{return process.kill(e,0),!0}catch{return!1}}async function N(){ve();let e=C();if(e&&A(e))throw new Error(`Server already running (PID ${e})`);v(S)&&$(S),v(k)&&$(k);let o=fe(b,"a"),t=D(B,"dist/index.js"),n=me(t,[],{detached:!0,stdio:["ignore",o,o,"ipc"]}),l=await new Promise((i,c)=>{let p=setTimeout(()=>{n.kill(),c(new Error(`Server start timeout. Check logs: ${b}`))},1e4);n.on("message",a=>{if(a&&typeof a=="object"&&a.type==="ready"){clearTimeout(p);let s=a.port;s?i(s):c(new Error("Ready signal received but missing port"))}}),n.on("exit",a=>{clearTimeout(p);let s=v(b)?M(b,"utf-8").split(`
3
3
  `).slice(-10).join(`
4
4
  `):"";c(new Error(`Server exited with code ${a}.
5
5
  ${s?`Last log lines:
@@ -9,9 +9,9 @@ Task cancelled.`)),process.exit(130)};process.on("SIGINT",l);let i=new V(n);awai
9
9
  `);f.length>5?console.log(d.green(`[result] (${f.length} lines) \u25B8 truncated`)):console.log(d.green(`[result] ${m}`))}}),i.on("error",s=>{let r=s;o.json?c.push({type:"error",...r}):console.error(d.red(`
10
10
  [error] ${r.error??"unknown error"}`))}),i.on("approval_needed",s=>{let r=s;if(o.approval===!1){h(`/tasks/${n}/approve`,{method:"POST",body:{approvalId:r.approvalId,reason:"auto-approved via --no-approval"}}).catch(()=>{});return}if(o.json){c.push({type:"approval_needed",...r}),h(`/tasks/${n}/approve`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{});return}console.log(d.yellow(`
11
11
  \u26A0 Approval needed: ${r.toolName}`)),console.log(d.yellow(` Pattern: ${r.matchedPattern}`)),console.log(d.yellow(` Input: ${JSON.stringify(r.toolInput)}`));let m=Z.createInterface({input:process.stdin,output:process.stdout});m.question(d.yellow(" [a]pprove / [r]eject: "),f=>{m.close();let x=f.toLowerCase().startsWith("a")?"approve":"reject";h(`/tasks/${n}/${x}`,{method:"POST",body:{approvalId:r.approvalId}}).catch(()=>{})})}),i.on("complete",s=>{let r=s;o.json?console.log(JSON.stringify({taskId:n,status:"completed",events:c,result:r})):(console.log(d.dim(`
12
- \u2500\u2500\u2500 Task complete \u2500\u2500\u2500`)),r.costUsd!==void 0&&console.log(d.dim(`Cost: $${r.costUsd.toFixed(4)}`)),r.numTurns!==void 0&&console.log(d.dim(`Turns: ${r.numTurns}`))),i.close(),a()}),i.on("*",s=>{s.type})});let p=await h(`/tasks/${n}`);(p.task.status==="failed"||p.task.status==="cancelled")&&process.exit(1),process.exit(0)}catch(t){o.json?console.log(JSON.stringify({error:t.message})):console.error(d.red(t.message)),process.exit(1)}}import u from"chalk";var Se={pending:u.gray,queued:u.gray,running:u.yellow,paused:u.yellow,completed:u.green,failed:u.red,cancelled:u.gray};function X(e){return(Se[e]??u.white)(e)}function ee(e,o){return e.length<=o?e:e.slice(0,o-3)+"..."}function oe(e){if(e<1e3)return`${e}ms`;let o=Math.floor(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return`${t}m ${n}s`}async function te(e){try{let o=new URLSearchParams;e.status&&o.set("status",e.status),e.limit&&o.set("limit",e.limit);let t=o.toString(),{tasks:n}=await h(`/tasks${t?`?${t}`:""}`);if(n.length===0){console.log(u.dim("No tasks found"));return}console.log(u.bold(T("ID",10)+T("STATUS",12)+T("PROMPT",40)+T("DURATION",10)+"COST"));for(let l of n){let i=l.totalDurationMs?oe(l.totalDurationMs):"\u2014",c=l.costUsd!==void 0?`$${l.costUsd.toFixed(4)}`:"\u2014";console.log(T(l.id.slice(0,8),10)+T(X(l.status),22)+T(ee(l.prompt,38),40)+T(i,10)+c)}}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function re(e){try{let{task:o}=await h(`/tasks/${e}`);console.log(u.bold("Task Details")),console.log(` ID: ${o.id}`),console.log(` Status: ${X(o.status)}`),console.log(` Prompt: ${o.prompt}`),console.log(` Created: ${new Date(o.createdAt).toLocaleString()}`),o.startedAt&&console.log(` Started: ${new Date(o.startedAt).toLocaleString()}`),o.completedAt&&console.log(` Finished: ${new Date(o.completedAt).toLocaleString()}`),o.totalDurationMs&&console.log(` Duration: ${oe(o.totalDurationMs)}`),o.costUsd!==void 0&&console.log(` Cost: $${o.costUsd.toFixed(4)}`),o.result&&console.log(` Result: ${ee(o.result,200)}`),o.error&&console.log(` Error: ${u.red(o.error)}`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function ne(e){try{await h(`/tasks/${e}/cancel`,{method:"POST"}),console.log(`Task ${e} cancelled`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}function T(e,o){return e.length>=o?e:e+" ".repeat(o-e.length)}de();ue();import O from"chalk";async function ie(e){try{let o=H();if(e.json){let t=R();console.log(JSON.stringify(t,null,2))}else{let t=R(),n=J(),l=K();console.log(O.bold(`Adam Configuration
12
+ \u2500\u2500\u2500 Task complete \u2500\u2500\u2500`)),r.costUsd!==void 0&&console.log(d.dim(`Cost: $${r.costUsd.toFixed(4)}`)),r.numTurns!==void 0&&console.log(d.dim(`Turns: ${r.numTurns}`))),i.close(),a()}),i.on("*",s=>{s.type})});let p=await h(`/tasks/${n}`);(p.task.status==="failed"||p.task.status==="cancelled")&&process.exit(1),process.exit(0)}catch(t){o.json?console.log(JSON.stringify({error:t.message})):console.error(d.red(t.message)),process.exit(1)}}import u from"chalk";var Se={pending:u.gray,queued:u.gray,running:u.yellow,paused:u.yellow,completed:u.green,failed:u.red,cancelled:u.gray};function X(e){return(Se[e]??u.white)(e)}function ee(e,o){return e.length<=o?e:e.slice(0,o-3)+"..."}function oe(e){if(e<1e3)return`${e}ms`;let o=Math.floor(e/1e3);if(o<60)return`${o}s`;let t=Math.floor(o/60),n=o%60;return`${t}m ${n}s`}async function te(e){try{let o=new URLSearchParams;e.status&&o.set("status",e.status),e.limit&&o.set("limit",e.limit);let t=o.toString(),{tasks:n}=await h(`/tasks${t?`?${t}`:""}`);if(n.length===0){console.log(u.dim("No tasks found"));return}console.log(u.bold(T("ID",10)+T("STATUS",12)+T("PROMPT",40)+T("DURATION",10)+"COST"));for(let l of n){let i=l.totalDurationMs?oe(l.totalDurationMs):"\u2014",c=l.costUsd!==void 0?`$${l.costUsd.toFixed(4)}`:"\u2014";console.log(T(l.id.slice(0,8),10)+T(X(l.status),22)+T(ee(l.prompt,38),40)+T(i,10)+c)}}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function re(e){try{let{task:o}=await h(`/tasks/${e}`);console.log(u.bold("Task Details")),console.log(` ID: ${o.id}`),console.log(` Status: ${X(o.status)}`),console.log(` Prompt: ${o.prompt}`),console.log(` Created: ${new Date(o.createdAt).toLocaleString()}`),o.startedAt&&console.log(` Started: ${new Date(o.startedAt).toLocaleString()}`),o.completedAt&&console.log(` Finished: ${new Date(o.completedAt).toLocaleString()}`),o.totalDurationMs&&console.log(` Duration: ${oe(o.totalDurationMs)}`),o.costUsd!==void 0&&console.log(` Cost: $${o.costUsd.toFixed(4)}`),o.result&&console.log(` Result: ${ee(o.result,200)}`),o.error&&console.log(` Error: ${u.red(o.error)}`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}async function ne(e){try{await h(`/tasks/${e}/cancel`,{method:"POST"}),console.log(`Task ${e} cancelled`)}catch(o){console.error(u.red(o.message)),process.exit(1)}}function T(e,o){return e.length>=o?e:e+" ".repeat(o-e.length)}de();ue();import O from"chalk";async function ie(e){try{let o=j();if(e.json){let t=R();console.log(JSON.stringify(t,null,2))}else{let t=R(),n=H(),l=z();console.log(O.bold(`Adam Configuration
13
13
  `)),l&&console.log(O.yellow(`No configuration saved. Use Settings UI or create ~/.adam/.env
14
14
  `));let i={Anthropic:[["anthropic.apiKey",t["anthropic.apiKey"]],["anthropic.baseUrl",t["anthropic.baseUrl"]],["anthropic.model",t["anthropic.model"]],["anthropic.defaultOpusModel",t["anthropic.defaultOpusModel"]],["anthropic.defaultSonnetModel",t["anthropic.defaultSonnetModel"]],["anthropic.defaultHaikuModel",t["anthropic.defaultHaikuModel"]],["anthropic.smallFastModel",t["anthropic.smallFastModel"]]],Defaults:[["defaults.model",t["defaults.model"]],["defaults.effort",t["defaults.effort"]],["defaults.maxTurns",t["defaults.maxTurns"]],["defaults.maxBudgetUsd",t["defaults.maxBudgetUsd"]],["defaults.timeout",t["defaults.timeout"]]],Server:[["server.port",t["server.port"]],["server.host",t["server.host"]],["server.apiKey",t["server.apiKey"]],["server.timezone",t["server.timezone"]]],Logging:[["logging.level",t["logging.level"]]],Evolution:[["roles.evolution.triggerEvery",t["roles.evolution.triggerEvery"]],["roles.evolution.reflectionThreshold",t["roles.evolution.reflectionThreshold"]]],Chat:[["chat.sessionTimeoutMinutes",t["chat.sessionTimeoutMinutes"]],["chat.maxSessionTurns",t["chat.maxSessionTurns"]],["chat.autoTitle",t["chat.autoTitle"]],["chat.archiveExtractMemory",t["chat.archiveExtractMemory"]]]},c={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold"};for(let[p,a]of Object.entries(i)){let s=a.filter(([,r])=>r!=null&&r!=="");if(s.length!==0){console.log(O.cyan(`${p}:`));for(let[r,m]of s){let f=c[r]??r,L=r.includes("apiKey")||r.includes("token")||r.includes("secret")?se(String(m)):String(m);console.log(` ${f}: ${L}`)}console.log("")}}if(n){console.log(O.bold(`.env File Values:
15
- `));let p=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_SMALL_FAST_MODEL"];for(let a of p)if(a in n){let s=a.includes("API_KEY");console.log(` ${a}: ${s?se(n[a]):n[a]}`)}console.log("")}}}finally{j()}}function se(e){return!e||e.length<8?"****":e.slice(0,4)+"****"}import w from"chalk";async function ae(e){try{let o=e.limit??"20",t=await h(`/evolution-audit?limit=${o}`);if(t.length===0){console.log(w.dim("No evolution records yet"));return}console.log(w.bold(`Evolution Audit Log (${t.length} records)
15
+ `));let p=["ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_SMALL_FAST_MODEL"];for(let a of p)if(a in n){let s=a.includes("API_KEY");console.log(` ${a}: ${s?se(n[a]):n[a]}`)}console.log("")}}}finally{K()}}function se(e){return!e||e.length<8?"****":e.slice(0,4)+"****"}import w from"chalk";async function ae(e){try{let o=e.limit??"20",t=await h(`/evolution-audit?limit=${o}`);if(t.length===0){console.log(w.dim("No evolution records yet"));return}console.log(w.bold(`Evolution Audit Log (${t.length} records)
16
16
  `));for(let n of t){let l=new Date(n.timestamp).toLocaleString();console.log(w.bold(`[${l}]`)+(n.triggerTaskId?w.dim(` task: ${n.triggerTaskId.slice(0,8)}`):"")),console.log(w.dim(" Diff:"));for(let i of n.diff.split(`
17
- `))i.startsWith("+")?console.log(w.green(` ${i}`)):i.startsWith("-")?console.log(w.red(` ${i}`)):console.log(w.dim(` ${i}`));console.log()}}catch(o){console.error(w.red(o.message)),process.exit(1)}}import g from"chalk";import{WebSocket as ke}from"ws";function we(){try{let e=_().server?.timezone;return e==="system"||!e?void 0:e}catch{return}}function le(e){let o=we();return new Date(e).toLocaleTimeString(void 0,o?{timeZone:o}:void 0)}async function ce(e){let o=I(),t=e.port?Number(e.port):o.port??7100,n=G(),l=new URL(`ws://localhost:${t}/events`);n&&l.searchParams.set("api_key",n);let i=l.toString(),c=e.component,p=e.level;function a(){let r=new ke(i);r.on("open",()=>{console.log(g.dim(`Connected to ${i}`)),e.follow&&console.log(g.dim("Following logs... (Ctrl+C to exit)"))}),r.on("message",m=>{try{let f=JSON.parse(m.toString());if(f.type==="log_event"&&f.msg){if(c&&f.component!==c||p&&f.level!==p)return;s(f)}}catch{}}),r.on("error",m=>{console.error(g.red(`WebSocket error: ${m.message}`))}),r.on("close",()=>{e.follow&&(console.log(g.yellow("Connection closed, reconnecting...")),setTimeout(a,1e3))})}function s(r){let m=le(r.timestamp),x={debug:g.gray,info:g.blue,warn:g.yellow,error:g.red,fatal:g.bgRed.white}[r.level]||g.white,L=g.cyan(`[${r.component}]`);console.log(`${g.dim(m)} ${x(r.level.toUpperCase().padEnd(5))} ${L} ${r.msg}`),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&console.log(g.dim(" ")+g.dim(JSON.stringify(r.metadata)))}a(),await new Promise(r=>{process.on("SIGINT",()=>r()),process.on("SIGTERM",()=>r()),e.follow||setTimeout(r,3e3)})}var y=new Te;y.name("adam").description("Adam Agent Server CLI").version(B());var E=y.command("server").description("Server management");E.command("start").description("Start the server daemon").action(async()=>{try{let{pid:e,port:o}=await N();console.log(`Server started (PID ${e}, port ${o})`)}catch(e){console.error("Failed to start server:",e.message),process.exit(1)}});E.command("stop").description("Stop the server daemon").action(async()=>{try{await U(),console.log("Server stopped")}catch(e){console.error("Failed to stop server:",e.message),process.exit(1)}});E.command("restart").description("Restart the server daemon").action(async()=>{try{I().running&&(await U(),console.log("Server stopped"));let{pid:o,port:t}=await N();console.log(`Server restarted (PID ${o}, port ${t})`)}catch(e){console.error("Failed to restart server:",e.message),process.exit(1)}});E.command("status").description("Show server status").action(()=>{let e=I();e.running?console.log(`Server is running (PID ${e.pid}, port ${e.port})`):e.pid?console.log("Server not running (stale PID file)"):console.log("Server not running")});E.command("logs").description("Show server logs").option("-f, --follow","Follow log output").action(async e=>{let o=Y();if(!$e(o)){console.log("No log file found");return}if(e.follow){let t=Ie(o,{encoding:"utf-8"});for await(let n of t)process.stdout.write(n)}else console.log(be(o,"utf-8"))});y.command("run <prompt>").description("Submit a task and stream output").option("--model <model>","Model to use").option("--timeout <seconds>","Task timeout",parseInt).option("--budget <usd>","Max budget in USD",parseFloat).option("--template <name>","Task template to use").option("--workspace <path>","Workspace directory").option("--no-approval","Auto-approve all approval requests").option("--json","Output as JSON").option("--server <url>","Server URL").action(Q);var F=y.command("tasks").description("Task management");F.command("list").description("List recent tasks").option("-s, --status <status>","Filter by status").option("-l, --limit <number>","Limit results","20").action(te);F.command("show <id>").description("Show task details").action(re);F.command("cancel <id>").description("Cancel a running task").action(ne);y.command("config").description("Display current configuration").option("--json","Output as JSON").action(ie);y.command("evolution").description("Show self-evolution audit log").option("-l, --limit <number>","Limit results","20").action(ae);y.command("logs").description("Stream server logs in real-time via WebSocket").option("-f, --follow","Follow logs continuously").option("-c, --component <component>","Filter by component (manager, worker, scheduler, api, ws)").option("-l, --level <level>","Filter by level (debug, info, warn, error)").option("-p, --port <port>","Server port").action(ce);y.command("register-ai-digest").description("Register the AI Hourly Digest task template (cron: every hour)").action(()=>{try{q(),console.log("AI Digest template registered successfully")}catch(e){console.error("Failed to register AI Digest template:",e.message),process.exit(1)}});y.action(async()=>{try{await W()}catch{I().running?console.error("Server is running but not responding. Check: adam server logs"):console.error("Server not running. Run: adam server start"),process.exit(1)}let e=(await import("./App-SCPYTYGQ.js")).default,{waitUntilExit:o}=De(Pe.createElement(e));await o()});y.parse();
17
+ `))i.startsWith("+")?console.log(w.green(` ${i}`)):i.startsWith("-")?console.log(w.red(` ${i}`)):console.log(w.dim(` ${i}`));console.log()}}catch(o){console.error(w.red(o.message)),process.exit(1)}}import g from"chalk";import{WebSocket as ke}from"ws";function we(){try{let e=_().server?.timezone;return e==="system"||!e?void 0:e}catch{return}}function le(e){let o=we();return new Date(e).toLocaleTimeString(void 0,o?{timeZone:o}:void 0)}async function ce(e){let o=I(),t=e.port?Number(e.port):o.port??7100,n=G(),l=new URL(`ws://localhost:${t}/events`);n&&l.searchParams.set("api_key",n);let i=l.toString(),c=e.component,p=e.level;function a(){let r=new ke(i);r.on("open",()=>{console.log(g.dim(`Connected to ${i}`)),e.follow&&console.log(g.dim("Following logs... (Ctrl+C to exit)"))}),r.on("message",m=>{try{let f=JSON.parse(m.toString());if(f.type==="log_event"&&f.msg){if(c&&f.component!==c||p&&f.level!==p)return;s(f)}}catch{}}),r.on("error",m=>{console.error(g.red(`WebSocket error: ${m.message}`))}),r.on("close",()=>{e.follow&&(console.log(g.yellow("Connection closed, reconnecting...")),setTimeout(a,1e3))})}function s(r){let m=le(r.timestamp),x={debug:g.gray,info:g.blue,warn:g.yellow,error:g.red,fatal:g.bgRed.white}[r.level]||g.white,L=g.cyan(`[${r.component}]`);console.log(`${g.dim(m)} ${x(r.level.toUpperCase().padEnd(5))} ${L} ${r.msg}`),r.metadata&&typeof r.metadata=="object"&&Object.keys(r.metadata).length>0&&console.log(g.dim(" ")+g.dim(JSON.stringify(r.metadata)))}a(),await new Promise(r=>{process.on("SIGINT",()=>r()),process.on("SIGTERM",()=>r()),e.follow||setTimeout(r,3e3)})}var y=new Te;y.name("adam").description("Adam Agent Server CLI").version(J());var E=y.command("server").description("Server management");E.command("start").description("Start the server daemon").action(async()=>{try{let{pid:e,port:o}=await N();console.log(`Server started (PID ${e}, port ${o})`)}catch(e){console.error("Failed to start server:",e.message),process.exit(1)}});E.command("stop").description("Stop the server daemon").action(async()=>{try{await U(),console.log("Server stopped")}catch(e){console.error("Failed to stop server:",e.message),process.exit(1)}});E.command("restart").description("Restart the server daemon").action(async()=>{try{I().running&&(await U(),console.log("Server stopped"));let{pid:o,port:t}=await N();console.log(`Server restarted (PID ${o}, port ${t})`)}catch(e){console.error("Failed to restart server:",e.message),process.exit(1)}});E.command("status").description("Show server status").action(()=>{let e=I();e.running?console.log(`Server is running (PID ${e.pid}, port ${e.port})`):e.pid?console.log("Server not running (stale PID file)"):console.log("Server not running")});E.command("logs").description("Show server logs").option("-f, --follow","Follow log output").action(async e=>{let o=Y();if(!$e(o)){console.log("No log file found");return}if(e.follow){let t=Ie(o,{encoding:"utf-8"});for await(let n of t)process.stdout.write(n)}else console.log(be(o,"utf-8"))});y.command("run <prompt>").description("Submit a task and stream output").option("--model <model>","Model to use").option("--timeout <seconds>","Task timeout",parseInt).option("--budget <usd>","Max budget in USD",parseFloat).option("--template <name>","Task template to use").option("--workspace <path>","Workspace directory").option("--no-approval","Auto-approve all approval requests").option("--json","Output as JSON").option("--server <url>","Server URL").action(Q);var F=y.command("tasks").description("Task management");F.command("list").description("List recent tasks").option("-s, --status <status>","Filter by status").option("-l, --limit <number>","Limit results","20").action(te);F.command("show <id>").description("Show task details").action(re);F.command("cancel <id>").description("Cancel a running task").action(ne);y.command("config").description("Display current configuration").option("--json","Output as JSON").action(ie);y.command("evolution").description("Show self-evolution audit log").option("-l, --limit <number>","Limit results","20").action(ae);y.command("logs").description("Stream server logs in real-time via WebSocket").option("-f, --follow","Follow logs continuously").option("-c, --component <component>","Filter by component (manager, worker, scheduler, api, ws)").option("-l, --level <level>","Filter by level (debug, info, warn, error)").option("-p, --port <port>","Server port").action(ce);y.command("register-ai-digest").description("Register the AI Hourly Digest task template (cron: every hour)").action(()=>{try{q(),console.log("AI Digest template registered successfully")}catch(e){console.error("Failed to register AI Digest template:",e.message),process.exit(1)}});y.action(async()=>{try{await W()}catch{I().running?console.error("Server is running but not responding. Check: adam server logs"):console.error("Server not running. Run: adam server start"),process.exit(1)}let e=(await import("./App-RIYRYLKD.js")).default,{waitUntilExit:o}=De(Pe.createElement(e));await o()});y.parse();
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-QMKQBU3R.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";g();export{f as deleteConfigValue,c as getAllConfig,a as getConfigValue,e as isConfigEmpty,d as seedConfig,b as setConfigValue};
1
+ import{a,b,c,d,e,f,g}from"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";g();export{f as deleteConfigValue,c as getAllConfig,a as getConfigValue,e as isConfigEmpty,d as seedConfig,b as setConfigValue};
@@ -0,0 +1 @@
1
+ import{a as b,b as c,d,e}from"./chunk-JTMFEUDA.js";import{a}from"./chunk-6KLG4APZ.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 +1 @@
1
- import{a,b,c,d}from"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
1
+ import{a,b,c,d}from"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";d();export{c as closeDb,b as getDb,a as runMigrations};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunk-TEMWI6U5.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as TTL_MS,g as cleanupExpired,b as createDeliveryLog,i as getDeliveryLogByRule,h as getDeliveryLogByTask,f as getFailedDeliveries,e as getPendingDeliveries,d as markDelivered,c as updateDeliveryLogStatus};
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-OFOVSC72.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as TTL_MS,g as cleanupExpired,b as createDeliveryLog,i as getDeliveryLogByRule,h as getDeliveryLogByTask,f as getFailedDeliveries,e as getPendingDeliveries,d as markDelivered,c as updateDeliveryLogStatus};
@@ -0,0 +1 @@
1
+ import{a,b,c,d}from"./chunk-WVGNP2LQ.js";import"./chunk-2HN2TSP6.js";import"./chunk-EGS6U3V5.js";import"./chunk-6YURWVQG.js";import"./chunk-3RAFA6QK.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 +1 @@
1
- import{a,b,c,d,e}from"./chunk-PT55643Q.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};
1
+ import{a,b,c,d,e}from"./chunk-QN6BEJF5.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};