adam-agent-server 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +11 -19
  2. package/dist/App-G2WZKRUH.js +9 -0
  3. package/dist/adam-tools-Q4BRKX3U.js +1 -0
  4. package/dist/approval-handler-D3J6NCMM.js +4 -0
  5. package/dist/bree-engine-SQMSKGAP.js +1 -0
  6. package/dist/channels-VEUBY2NZ.js +1 -0
  7. package/dist/channels-WFZAONF3.js +1 -0
  8. package/dist/{chunk-5GMYXCL3.js → chunk-2EP27EGS.js} +1 -1
  9. package/dist/chunk-2GXYBWLS.js +10 -0
  10. package/dist/chunk-2VKE7ONM.js +86 -0
  11. package/dist/{chunk-HMXDNPFE.js → chunk-5ASEAZCR.js} +1 -1
  12. package/dist/chunk-5JLMSNIW.js +1 -0
  13. package/dist/{chunk-MMIO6BCA.js → chunk-742NWPTQ.js} +3 -3
  14. package/dist/chunk-7SPKRIMZ.js +15 -0
  15. package/dist/chunk-AXMXXUPO.js +5 -0
  16. package/dist/{chunk-5AKFAMQL.js → chunk-B6S2AEOD.js} +1 -1
  17. package/dist/chunk-DT2LX4XI.js +49 -0
  18. package/dist/{chunk-VURJZLM6.js → chunk-EALDBELJ.js} +6 -3
  19. package/dist/{chunk-ZN5Q3YET.js → chunk-ETQ7KC73.js} +1 -1
  20. package/dist/chunk-FDWW245P.js +5 -0
  21. package/dist/chunk-FUGJMHY4.js +1 -0
  22. package/dist/chunk-FYDFMYUP.js +1 -0
  23. package/dist/chunk-HAWA62R2.js +26 -0
  24. package/dist/chunk-IXF3XBGX.js +5 -0
  25. package/dist/chunk-JXD6ZPV7.js +2 -0
  26. package/dist/chunk-KICPHTI2.js +5 -0
  27. package/dist/chunk-L7426WNY.js +7 -0
  28. package/dist/{chunk-WGRTN6TX.js → chunk-L7JP7DUO.js} +1 -1
  29. package/dist/chunk-NICRQZ7T.js +1 -0
  30. package/dist/{chunk-3HM54J2N.js → chunk-NSJAV7IH.js} +1 -1
  31. package/dist/{chunk-W6JITSZF.js → chunk-PCSZW2PE.js} +28 -11
  32. package/dist/{chunk-EJJDJY34.js → chunk-PQ7KPALO.js} +1 -1
  33. package/dist/{chunk-F2IS5LWD.js → chunk-SFUS33SO.js} +1 -1
  34. package/dist/chunk-T25NLVMY.js +1 -0
  35. package/dist/chunk-TN6H2WM2.js +19 -0
  36. package/dist/chunk-U36NBCR3.js +17 -0
  37. package/dist/chunk-UOTDT2KY.js +3 -0
  38. package/dist/chunk-VF6GJGD6.js +6 -0
  39. package/dist/chunk-WXN3PSVX.js +6 -0
  40. package/dist/chunk-WZOMGJSY.js +1 -0
  41. package/dist/{chunk-62PXAOD6.js → chunk-XNWZZYAV.js} +1 -1
  42. package/dist/cli.js +15 -13
  43. package/dist/config-WHXCZCI4.js +1 -0
  44. package/dist/config-Y4QWELO3.js +1 -0
  45. package/dist/{db-ZDEA7EUY.js → db-PNZ3UJOE.js} +1 -1
  46. package/dist/delivery-log-VYTYUFCK.js +1 -0
  47. package/dist/engine-V5MOGOLN.js +1 -0
  48. package/dist/{evolution-audit-MDA2ZVJW.js → evolution-audit-B7WKMOVR.js} +1 -1
  49. package/dist/{external-api-T7FFXVHL.js → external-api-XGEOKAWR.js} +1 -1
  50. package/dist/index.js +41 -63
  51. package/dist/learner-VMD5NQCD.js +1 -0
  52. package/dist/memories-EFQ4SFZG.js +1 -0
  53. package/dist/memory-extractor-GOISDQTO.js +6 -0
  54. package/dist/memory-service-BKLZIRK6.js +1 -0
  55. package/dist/monitor-K7CGTLA6.js +1 -0
  56. package/dist/outbound-gateway-FIPC4BZO.js +1 -0
  57. package/dist/role-presets-FN2RWUCP.js +1 -0
  58. package/dist/{roles-CMV5FMIA.js → roles-SG2YAR64.js} +1 -1
  59. package/dist/runtime-6UTYEONR.js +1 -0
  60. package/dist/server-bus-GEGVMSCA.js +1 -0
  61. package/dist/session-manager-45LFTPBA.js +1 -0
  62. package/dist/{task-templates-AKQB7RRB.js → task-templates-7LSQ6OST.js} +1 -1
  63. package/dist/token-estimator-HMPVGDCN.js +1 -0
  64. package/package.json +2 -2
  65. package/web/dist/assets/{Card-BpwkRtmi.js → Card-BecEmnPW.js} +1 -1
  66. package/web/dist/assets/{ChannelDetail-050qK78l.js → ChannelDetail-dZfZlLgQ.js} +1 -1
  67. package/web/dist/assets/{Channels-DA4gN6nU.js → Channels-Cw04c7YJ.js} +1 -1
  68. package/web/dist/assets/{Chat-LzhfKGQ5.js → Chat-D4PHqHPE.js} +1 -1
  69. package/web/dist/assets/Dashboard-BFewwmAg.js +1 -0
  70. package/web/dist/assets/{EmptyState-B08f3BH6.js → EmptyState-DBFJc4PL.js} +1 -1
  71. package/web/dist/assets/{Evolution-BwsOuVbZ.js → Evolution-DY1OC6Oc.js} +4 -1
  72. package/web/dist/assets/{GoalDetail-Zo16ZrYD.js → GoalDetail-DZIEpHs2.js} +1 -1
  73. package/web/dist/assets/Goals-COCCVLnp.js +1 -0
  74. package/web/dist/assets/{Logs-CYfQ9k_6.js → Logs-DsDeimLt.js} +1 -1
  75. package/web/dist/assets/Memories-D5IEEI1u.js +1 -0
  76. package/web/dist/assets/NotFound-Cidygwnn.js +1 -0
  77. package/web/dist/assets/{Plugins-DHgIfely.js → Plugins-DUwZVjPc.js} +1 -1
  78. package/web/dist/assets/RoleDetail-B-GKMfMG.js +33 -0
  79. package/web/dist/assets/{Roles-DGpN5Vm6.js → Roles-JeVjD0Ew.js} +1 -1
  80. package/web/dist/assets/Settings-CvEyZp5t.js +1 -0
  81. package/web/dist/assets/{Strategies-DBp2jYdi.js → Strategies-KAmpqrcQ.js} +1 -1
  82. package/web/dist/assets/{Switch-yk5-dsti.js → Switch-Jpdn6Yux.js} +1 -1
  83. package/web/dist/assets/{Table-DWR4p9xA.js → Table-tkJ-cuiE.js} +1 -1
  84. package/web/dist/assets/TaskDetail-C4NpqwNT.js +2 -0
  85. package/web/dist/assets/Work-DhaxNYnd.js +1 -0
  86. package/web/dist/assets/dist-HyCSN_hp.js +1 -0
  87. package/web/dist/assets/index-CfKqiQIe.js +52 -0
  88. package/web/dist/assets/index-LDFr0VVR.css +2 -0
  89. package/web/dist/assets/rolldown-runtime-Dw2cE7zH.js +1 -0
  90. package/web/dist/assets/vendor-icons-ZPvC5PUS.js +1 -0
  91. package/web/dist/assets/vendor-react--nRVf2Ep.js +12 -0
  92. package/web/dist/assets/{vendor-state-CRsbPXtF.js → vendor-state-CH64feAE.js} +1 -1
  93. package/web/dist/index.html +7 -7
  94. package/dist/App-23CRAK2P.js +0 -9
  95. package/dist/adam-tools-MKUMZWCR.js +0 -1
  96. package/dist/approval-handler-SBFVVFGH.js +0 -4
  97. package/dist/channels-CNLMTKHM.js +0 -1
  98. package/dist/channels-VNG7U6UQ.js +0 -1
  99. package/dist/chunk-37OAKNKA.js +0 -15
  100. package/dist/chunk-3OYRYMJW.js +0 -11
  101. package/dist/chunk-5BAD3NCT.js +0 -1
  102. package/dist/chunk-B3CVXD44.js +0 -104
  103. package/dist/chunk-CV3ROBUM.js +0 -1
  104. package/dist/chunk-FUBKGVWI.js +0 -8
  105. package/dist/chunk-J5YZQQTS.js +0 -3
  106. package/dist/chunk-Q3N5LVPZ.js +0 -5
  107. package/dist/chunk-QOPUUA7O.js +0 -1
  108. package/dist/chunk-TGQYM4TH.js +0 -6
  109. package/dist/chunk-TYR3QUCL.js +0 -23
  110. package/dist/config-42ZJPZDM.js +0 -1
  111. package/dist/delivery-log-7DQ36UGP.js +0 -1
  112. package/dist/engine-7VBPXTGK.js +0 -1
  113. package/dist/memories-BUNOVQVG.js +0 -1
  114. package/dist/role-presets-2X3VW75D.js +0 -1
  115. package/dist/runtime-772O2XKZ.js +0 -1
  116. package/dist/server-bus-N5LCY73J.js +0 -1
  117. package/dist/session-manager-KO4CR3W6.js +0 -1
  118. package/web/dist/assets/Dashboard-Bh32YC_E.js +0 -1
  119. package/web/dist/assets/Goals-BmfVadFN.js +0 -1
  120. package/web/dist/assets/Memories-CgSb60RC.js +0 -1
  121. package/web/dist/assets/RoleDetail-CNJkMSuz.js +0 -1
  122. package/web/dist/assets/Settings-PjFyeX8n.js +0 -1
  123. package/web/dist/assets/TaskDetail-DMg-JAbC.js +0 -2
  124. package/web/dist/assets/Work-BYgMw2qj.js +0 -1
  125. package/web/dist/assets/dist-jv3vbjrx.js +0 -1
  126. package/web/dist/assets/index-CWY8H-cU.js +0 -52
  127. package/web/dist/assets/index-OXMtvYRJ.css +0 -2
  128. package/web/dist/assets/rolldown-runtime-DF2fYuay.js +0 -1
  129. package/web/dist/assets/vendor-icons-DqHipOFA.js +0 -1
  130. package/web/dist/assets/vendor-react-C2hDj0vl.js +0 -11
package/dist/index.js CHANGED
@@ -1,53 +1,9 @@
1
- import{a as Js,b as Qs,d as Ys}from"./chunk-5GMYXCL3.js";import{A as Pt,B as Ns,C as Ls,D as qs,E as Bs,F as Us,G as Ws,H as He,J as Ct,a as gt,b as ft,c as rs,d as ns,e as as,f as os,g as is,h as wt,i as us,j as fe,k as ms,l as gs,m as fs,n as Ue,o as St,p as bs,q as vs,r as ks,s as re,t as Ge,u as Ts,v as ws,w as Os,x as Fs,y as Ms,z as js}from"./chunk-B3CVXD44.js";import{d as Zs,e as er}from"./chunk-J5YZQQTS.js";import{a as ae,b as A,c as $,d as N,e as Xt,f as Gs,g as ze,h as Vs,i as $s,j as Hs}from"./chunk-3OYRYMJW.js";import{h as Xs}from"./chunk-Q3N5LVPZ.js";import{b as Ss,d as Ve,f as ye}from"./chunk-EJJDJY34.js";import{b as ds,d as $e,e as Ps,f as H,g as Cs,h as _s,i as As,j as Se,k as Z,l as Es,p as xs,q as Ds}from"./chunk-QOPUUA7O.js";import{b as ls,c as ps}from"./chunk-HMXDNPFE.js";import{a as X,b as Tt,d as cs}from"./chunk-MMIO6BCA.js";import{a as g}from"./chunk-WGRTN6TX.js";import{e as ys,n as hs}from"./chunk-TYR3QUCL.js";import{b as zs,c as Ks}from"./chunk-5AKFAMQL.js";import{a as ss,b as tr,c as sr,d as rr}from"./chunk-VURJZLM6.js";import{a as We,b as U,c as Rs,d as we,g as Is}from"./chunk-TGQYM4TH.js";import{a as Jt,b as ge}from"./chunk-CV3ROBUM.js";import{a as Kt}from"./chunk-ZN5Q3YET.js";import{a as qe,b as pt,c as Qt,d as Y,e as Yt,f as ut}from"./chunk-5BAD3NCT.js";import"./chunk-37OAKNKA.js";import{a as se,b as Te,c as Rt,d as It,f as kt}from"./chunk-FUBKGVWI.js";import{a as Zt,b as es,c as on,e as yt,f as B,g as ht,h as bt,i as oe,j as vt,l as ie}from"./chunk-62PXAOD6.js";import{b as j,c as mt,d as ke}from"./chunk-W6JITSZF.js";import{b as zt,c as q,f as me}from"./chunk-F2IS5LWD.js";import{a as ts,c as E,d as Be}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{writeFileSync as sn,mkdirSync as rn,unlinkSync as Ea}from"fs";import{join as ot}from"path";me();import{readFileSync as dn,existsSync as cn}from"fs";import{resolve as _t}from"path";function nr(o=q){let e=[],t=[],s=process.env.ADAM_ENV_FILE;s&&t.push(_t(o,s)),t.push(_t(o,".env.local")),t.push(_t(o,".env"));for(let r of t){if(!cn(r))continue;ln(r)>0&&e.push(r)}return e}function ln(o){let t=dn(o,"utf-8").split(`
2
- `),s=0;for(let r of t){let n=r.trim();if(!n||n.startsWith("#"))continue;n.startsWith("export ")&&(n=n.slice(7).trim());let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim();if(!i)continue;let d=n.slice(a+1).trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),d=d.replace(/\$\{(\w+)\}|\$(\w+)/g,(c,l,b)=>{let u=l??b;return process.env[u]??""}),(i.startsWith("ANTHROPIC_")||process.env[i]===void 0)&&(process.env[i]=d,s++)}return s}ke();ie();kt();import{existsSync as ar}from"fs";import pn from"path";import un from"fastify";import mn from"@fastify/cors";import gn from"@fastify/static";import fn from"@fastify/websocket";import yn from"@fastify/swagger";import hn from"@fastify/swagger-ui";import{timingSafeEqual as bn}from"crypto";function ir(o,e){let t=un({logger:!1});if(t.register(yn,{openapi:{info:{title:"Adam API",description:"Agent orchestration server built on Claude Agent SDK. Multi-agent system with parallel task execution, intelligent agent routing, self-evolving personas, and REST/WebSocket API.",version:"2.0.0"},servers:[{url:"http://localhost:7100"}],tags:[{name:"Tasks",description:"Task lifecycle management"},{name:"Roles",description:"Role CRUD and workspace management"},{name:"Skills",description:"Skill CRUD and permissions"},{name:"Memories",description:"Agent memory search and retrieval"},{name:"Goals",description:"Goal-driven task management"},{name:"Strategies",description:"Thompson Sampling strategy engine"},{name:"Templates",description:"Task template CRUD and triggers"},{name:"Webhooks",description:"External system integration"},{name:"Config",description:"Runtime configuration management"},{name:"Evolution",description:"Agent evolution audit log"},{name:"Health",description:"Server health checks"}],components:{securitySchemes:{apiKey:{type:"apiKey",in:"header",name:"x-api-key",description:"API key for webhook endpoints"}}}}}),t.register(hn,{routePrefix:"/docs"}),t.register(mn,{origin:!0}),t.register(fn,{options:{maxPayload:1024*1024*16}}),e){let r=Buffer.from(e);t.addHook("onRequest",async(n,a)=>{let i=n.url;if(i==="/healthz"||i==="/readyz"||i.startsWith("/docs")||i.startsWith("/ui"))return;let d=n.headers["x-api-key"];if(d&&or(d,r))return;let c=n.query,l=c.api_key||c["x-api-key"];if(!(l&&or(l,r)))return a.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"})})}let s=pn.join(ss,"web/dist");return ar(s)&&(t.register(gn,{root:s,prefix:"/ui/",wildcard:!1}),t.get("/ui",async(r,n)=>n.sendFile("index.html",s)),t.get("/ui/*",async(r,n)=>n.sendFile("index.html",s))),t.setErrorHandler((r,n,a)=>{if(r.validation){let d=r.validation.map(c=>{let l=c.instancePath||c.params?.missingProperty||"";return l?`${l}: ${c.message}`:c.message});return a.status(400).send({code:"VALIDATION_ERROR",message:d.join("; ")})}let i=r.statusCode??500;return a.status(i).send({code:"INTERNAL_ERROR",message:r.message})}),t.setNotFoundHandler((r,n)=>r.url.startsWith("/ui")&&ar(s)?n.sendFile("index.html",s):n.status(404).send({code:"NOT_FOUND",message:"Route not found"})),t}function or(o,e){try{let t=Buffer.from(o);return t.length!==e.length?!1:bn(t,e)}catch{return!1}}import{z as p}from"zod/v4";import{v4 as Pn}from"uuid";var vn=o=>({...o,nullable:!0}),S={type:"object",properties:{code:{type:"string"},message:{type:"string"}}},Rn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}},In={type:"object",additionalProperties:!0,properties:{type:{type:"string"},cron:{type:"string"},event:{type:"string"}}},dr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},trigger:In,steps:{type:"array",items:Rn},agentPreference:{type:"string"},config:{type:"object",additionalProperties:!0},tags:{type:"array",items:{type:"string"}},enabled:{type:"boolean"},createdAt:{type:"number"},updatedAt:{type:"number"}}},kn={type:"object",properties:{input:{type:"number"},output:{type:"number"}}},cr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},parentId:{type:"string"},status:{type:"string"},prompt:{type:"string"},originalPrompt:{type:"string"},config:{type:"object",additionalProperties:!0},result:{type:"string"},error:{type:"string"},sdkSessionId:{type:"string"},roleId:{type:"string"},templateId:{type:"string"},createdAt:{type:"number"},startedAt:{type:"number"},completedAt:{type:"number"},costUsd:{type:"number"},tokenUsage:kn,numTurns:{type:"number"},totalDurationMs:{type:"number"}}},Tn={type:"object",additionalProperties:!0,properties:{model:{type:"string"},effort:{type:"string"},maxTurns:{type:"number"}}},Ke={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},source:{type:"string"},traits:{type:"array",items:{type:"string"}},background:{type:"string"},preferences:Tn,learnedRules:{type:"array",items:{type:"string"}},memoryStreamId:{type:"string"},status:{type:"string"},createdAt:{type:"number"},lastActiveAt:{type:"number"},taskCount:{type:"number"},performanceScore:{type:"number"},role:{type:"string"},toolProfile:{type:"array",items:{type:"string"}},evaluationCriteria:{type:"object",additionalProperties:{type:"number"}},strategyPoolId:{type:"string"}}},lr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},roleId:{type:"string"},type:{type:"string"},content:{type:"string"},keywords:{type:"array",items:{type:"string"}},importance:{type:"number"},sourceType:{type:"string"},sourceTaskId:{type:"string"},evidence:{type:"array",items:{type:"string"}},createdAt:{type:"number"},lastAccessed:{type:"number"},retrievedCount:{type:"number"},score:{type:"number"}}},wn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},role:{type:"string"},taskType:{type:"string"},name:{type:"string"},promptTemplate:{type:"string"},alpha:{type:"number"},beta:{type:"number"},totalTrials:{type:"number"},avgReward:{type:"number"},toolProfile:{type:"array",items:{type:"string"}},createdAt:{type:"number"},updatedAt:{type:"number"}}},At={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},role:{type:"string"},metricType:{type:"string"},targetValue:{type:"number"},currentValue:{type:"number"},deadline:{type:"number"},budgetUsd:{type:"number"},status:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Sn={type:"object",additionalProperties:!0,properties:{name:{type:"string"},displayName:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}},trigger:{type:"string"}}},R={templateCreated:{201:{type:"object",properties:{templateId:{type:"string"}}}},templateList:{200:{type:"object",properties:{templates:{type:"array",items:dr}}}},templateDetail:{200:{type:"object",properties:{template:dr}},404:S},templateUpdated:{200:{type:"object",properties:{templateId:{type:"string"}}},404:S},templateDeleted:{200:{type:"object",properties:{templateId:{type:"string"},deleted:{type:"boolean"}}},404:S},templateRun:{200:{type:"object",properties:{executionId:{type:"string"},status:{type:"string"}}},404:S},taskCreated:{201:{type:"object",properties:{taskId:{type:"string"}}},400:S},taskList:{200:{type:"object",properties:{tasks:{type:"array",items:cr}}}},taskDetail:{200:{type:"object",properties:{task:cr}},404:S},taskAction:{200:{type:"object",additionalProperties:!0,properties:{taskId:{type:"string"}}},400:S,404:S},approvalAction:{200:{type:"object",properties:{approvalId:{type:"string"},decision:{type:"string"}}},404:S},agentList:{200:{type:"object",properties:{roles:{type:"array",items:Ke}}}},agentDetail:{200:{type:"object",properties:{agent:Ke}},404:S},agentCreated:{201:{type:"object",properties:{agent:Ke}}},agentUpdated:{200:{type:"object",properties:{agent:Ke}},404:S},agentDeleted:{200:{type:"object",properties:{agentId:{type:"string"},deleted:{type:"boolean"}}},400:S,404:S},agentPersona:{200:{type:"object",properties:{persona:vn({type:"string"})}},404:S},memoryList:{200:{type:"object",properties:{memories:{type:"array",items:lr},count:{type:"number"}}},404:S},memoryQuery:{200:{type:"object",properties:{memories:{type:"array",items:lr},count:{type:"number"}}},404:S},strategyList:{200:{type:"object",properties:{strategies:{type:"array",items:wn}}}},strategyProbabilities:{200:{type:"object",additionalProperties:!0,properties:{role:{type:"string"},taskType:{type:"string"},stats:{type:"object",additionalProperties:!0},probabilities:{type:"object",additionalProperties:{type:"number"}}}}},goalList:{200:{type:"object",properties:{goals:{type:"array",items:At}}}},goalDetail:{200:{type:"object",properties:{goal:At}},404:S},goalCreated:{201:{type:"object",properties:{goal:At}},400:{...S,additionalProperties:!0,properties:{...S.properties,errors:{type:"array",items:{type:"string"}},warnings:{type:"array",items:{type:"string"}}}}},webhookTriggered:{202:{type:"object",properties:{code:{type:"string"},message:{type:"string"},executionId:{type:"string"},templateId:{type:"string"}}},401:S,404:S,409:S,500:S},webhookList:{200:{type:"object",properties:{webhooks:{type:"array",items:Sn},auth:{type:"string"}}}},configGet:{200:{type:"object",additionalProperties:!0,properties:{config:{type:"object",additionalProperties:{type:"object",additionalProperties:!0,properties:{value:{},mutable:{type:"boolean"}}}},mutable:{type:"array",items:{type:"string"}},restartRequired:{type:"array",items:{type:"string"}}}}},configPatch:{200:{type:"object",additionalProperties:!0,properties:{success:{type:"boolean"},updated:{type:"array",items:{type:"string"}},errors:{type:"array",items:{type:"string"}},message:{type:"string"}}}},healthz:{200:{type:"object",properties:{status:{type:"string"}}}},readyz:{200:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}},503:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}}}};var pr=p.union([p.object({type:p.literal("session"),sessionId:p.string()}),p.object({type:p.literal("channel"),channelId:p.string(),chatId:p.string().optional()})]),Cn=p.object({prompt:p.string().min(1,"prompt is required"),skillId:p.string().optional(),deliverTo:p.array(pr).optional(),reportTo:p.array(pr).optional(),config:p.object({allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),maxTurns:p.number().optional(),maxBudgetUsd:p.number().optional(),mcpServers:p.record(p.string(),p.unknown()).optional(),model:p.string().optional(),effort:p.enum(["low","medium","high","max"]).optional(),settingSources:p.array(p.string()).optional(),workspacePath:p.string().optional(),timeout:p.number().optional(),approvalRequired:p.array(p.string()).optional(),approvalTimeout:p.number().optional(),fileAccess:p.object({allowedPaths:p.array(p.string()),deniedPaths:p.array(p.string())}).optional(),env:p.record(p.string(),p.string()).optional(),plugins:p.array(p.string()).optional()}).optional()}),he=p.object({id:p.string().uuid()}),_n=["pending","queued","running","paused","completed","failed","cancelled"],An=p.object({status:p.enum(_n).optional(),skillId:p.string().optional(),limit:p.coerce.number().min(1).max(100).default(100),offset:p.coerce.number().min(0).default(0)});async function ur(o){let e=new is;o.post("/tasks",{schema:{tags:["Tasks"],summary:"Create a task",description:"Create a new task with a prompt and optional agent/config overrides. The task enters 'pending' status and is picked up by the scheduler.",body:{type:"object",required:["prompt"],properties:{prompt:{type:"string",minLength:1,description:"Task prompt"},skillId:{type:"string",description:"Optional agent to assign"},config:{type:"object",description:"Optional task configuration overrides",properties:{model:{type:"string"},maxTurns:{type:"integer"},maxBudgetUsd:{type:"number"},timeout:{type:"integer"},effort:{type:"string",enum:["low","medium","high","max"]}}}}},response:R.taskCreated}},async(n,a)=>{let i=Cn.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{prompt:d,skillId:c,config:l,deliverTo:b,reportTo:u}=i.data,y=ge(),w={timeout:l?.timeout??y.timeout,approvalRequired:l?.approvalRequired??y.approvalRequired,approvalTimeout:l?.approvalTimeout??y.approvalTimeout,fileAccess:l?.fileAccess??y.fileAccess,allowedTools:l?.allowedTools??y.allowedTools,disallowedTools:l?.disallowedTools??y.disallowedTools,maxTurns:l?.maxTurns??y.maxTurns,maxBudgetUsd:l?.maxBudgetUsd??y.maxBudgetUsd,mcpServers:l?.mcpServers,model:l?.model||y.model||void 0,effort:l?.effort??y.effort,settingSources:l?.settingSources??y.settingSources,workspacePath:l?.workspacePath,env:l?.env??y.env,claudeCodePath:y.claudeCodePath,plugins:l?.plugins},v={id:Pn(),status:"pending",prompt:d,roleId:c??void 0,config:w,deliverTo:b,reportTo:u,createdAt:Date.now()};return ae(v),g.emit({type:"task_created",taskId:v.id}),a.status(201).send({taskId:v.id})}),o.get("/tasks",{schema:{tags:["Tasks"],summary:"List tasks",description:"List tasks with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["pending","queued","running","paused","completed","failed","cancelled"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}},response:R.taskList}},async(n,a)=>{let i=An.safeParse(n.query);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{status:d,skillId:c,limit:l,offset:b}=i.data;return{tasks:N(d,l,b,c)}}),o.get("/tasks/:id",{schema:{tags:["Tasks"],summary:"Get task by ID",description:"Retrieve a single task by its UUID.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskDetail}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=A(i.data.id);return d?{task:d}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"})}),o.post("/tasks/:id/cancel",{schema:{tags:["Tasks"],summary:"Cancel a task",description:"Cancel a running, queued, pending, or paused task. Returns 400 if the task is in a terminal state.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=A(i.data.id);return d?d.status!=="running"&&d.status!=="queued"&&d.status!=="pending"&&d.status!=="paused"?a.status(400).send({code:"INVALID_STATE",message:`Cannot cancel task in status: ${d.status}`}):(e.cancelTask(d.id),{taskId:d.id,status:"cancelled"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"})});let t=p.object({taskIds:p.array(p.string()).min(1).max(500)});o.post("/tasks/batch-cancel",{schema:{tags:["Tasks"],summary:"Batch cancel tasks",description:"Cancel multiple tasks at once. Skips tasks that are already in terminal state. Returns count of cancelled tasks.",body:{type:"object",required:["taskIds"],properties:{taskIds:{type:"array",items:{type:"string"},minItems:1,maxItems:500}}}}},async(n,a)=>{let i=t.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=new Set(["pending","queued","running","paused"]),c=0,l=[];for(let b of i.data.taskIds){let u=A(b);if(!u){l.push({taskId:b,reason:"not found"});continue}if(!d.has(u.status)){l.push({taskId:b,reason:`already ${u.status}`});continue}e.cancelTask(b),c++}return{cancelled:c,total:i.data.taskIds.length,errors:l.length>0?l:void 0}}),o.get("/tasks/:id/logs",{schema:{tags:["Tasks"],summary:"Get task step logs",description:"Returns execution step logs for a task (reasoning, tool calls, results).",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(n,a)=>{let i=A(n.params.id);if(!i)return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:d=50,offset:c=0}=n.query;return{logs:ft(i.id,d,c)}});let s=p.object({approvalId:p.string().uuid(),reason:p.string().optional()});o.post("/tasks/:id/approve",{schema:{tags:["Tasks"],summary:"Approve a pending approval",description:"Approve a tool-use approval request for a paused task. The skill agent resumes execution with the approved tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=s.safeParse(n.body);return d.success?A(i.data.id)?e.resolveApproval(d.data.approvalId,"allow",d.data.reason)?{approvalId:d.data.approvalId,decision:"allow"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)})}),o.post("/tasks/:id/reject",{schema:{tags:["Tasks"],summary:"Reject a pending approval",description:"Reject a tool-use approval request for a paused task. The skill agent skips the denied tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=s.safeParse(n.body);return d.success?A(i.data.id)?e.resolveApproval(d.data.approvalId,"deny",d.data.reason)?{approvalId:d.data.approvalId,decision:"deny"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)})});let r=p.object({planId:p.string(),decision:p.enum(["allow","deny"]),approvalType:p.enum(["once","permanent"]).optional(),reason:p.string().optional()});o.post("/tasks/:id/approve-plan",{schema:{tags:["Tasks"],summary:"Approve or deny an execution plan",description:"Respond to a plan approval request. Allow once (single task), allow permanent (create rule for similar tasks), or deny.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["planId","decision"],properties:{planId:{type:"string"},decision:{type:"string",enum:["allow","deny"]},approvalType:{type:"string",enum:["once","permanent"]},reason:{type:"string"}}}}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=r.safeParse(n.body);if(!d.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)});if(!A(i.data.id))return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{planId:l,decision:b,approvalType:u,reason:y}=d.data;return e.resolvePlanApproval(l,b,u,y)?{planId:l,decision:b,approvalType:u}:a.status(404).send({code:"NOT_FOUND",message:"Plan approval not found or already resolved"})}),o.get("/tasks/:id/plan",{schema:{tags:["Tasks"],summary:"Get execution plans for a task",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(n,a)=>{let i=he.safeParse(n.params);return i.success?A(i.data.id)?{plans:ns(i.data.id)}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)})})}ke();ie();async function mr(o,e){o.get("/healthz",{schema:{tags:["Health"],summary:"Health check",description:"Basic liveness probe. Returns 200 if the server process is running.",response:R.healthz}},async(t,s)=>({status:"ok"})),o.get("/readyz",{schema:{tags:["Health"],summary:"Readiness check",description:"Readiness probe that checks database, roles, config, embedding model, and task hub. Returns 503 if any check fails.",response:R.readyz}},async(t,s)=>{let r={database:!1,manager:!1,config:!1};try{j().prepare("SELECT 1").get(),r.database=!0}catch{r.database=!1}r.manager=!0,r.config=!!e.server;try{let a=oe(void 0,1,0);r.agents=a.length>0}catch{r.agents=!1}return r.embedding=ds(),r.taskHub=!0,Object.values(r).every(a=>a)?{status:"ready",checks:r}:s.status(503).send({status:"not_ready",checks:r})}),o.get("/stats",{schema:{tags:["Health"],summary:"Runtime statistics",description:"Returns execution pool status, active/pending task counts, and cost summary."}},async(t,s)=>{let n=Y().execution?.maxConcurrent??5,a=N("running"),i=N("pending");return{executionPool:{active:a.length,max:n,queued:i.length}}})}import{timingSafeEqual as fr}from"crypto";import{z as yr}from"zod/v4";var Et=class{connections=new Map;eventBuffers=new Map;eventIndices=new Map;addConnection(e,t){this.connections.has(e)||this.connections.set(e,new Set),this.connections.get(e).add(t);let s=this.getBufferedEvents(e);for(let r of s)t.readyState===1&&t.send(JSON.stringify(r));t.on("close",()=>{this.removeConnection(e,t)})}removeConnection(e,t){let s=this.connections.get(e);s&&(s.delete(t),s.size===0&&this.connections.delete(e))}broadcast(e,t){this.addToBuffer(e,t);let s=this.connections.get(e);if(!s||s.size===0)return;let r=JSON.stringify(t);for(let n of s)n.readyState===1&&n.send(r)}addToBuffer(e,t){let s=this.eventBuffers.get(e);s||(s=[],this.eventBuffers.set(e,s)),s.push(t),s.length>100&&s.shift(),this.eventIndices.set(e,t.index)}getBufferedEvents(e){return this.eventBuffers.get(e)??[]}getNextIndex(e){let s=(this.eventIndices.get(e)??0)+1;return this.eventIndices.set(e,s),s}},gr=new Et;var En=yr.object({id:yr.string().uuid()});async function hr(o,e){o.get("/tasks/:id/stream",{websocket:!0},(t,s)=>{if(e&&!xn(s,e)){t.close(4401,"Unauthorized");return}let r=En.safeParse(s.params);if(!r.success){t.close(1008,"Invalid task ID");return}let{id:n}=r.data;if(!A(n)){t.close(1008,"Task not found");return}gr.addConnection(n,t)})}function xn(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&fr(n,a))return!0}catch{}let s=o.query,r=s.api_key||s["x-api-key"];if(r)try{let n=Buffer.from(r),a=Buffer.from(e);if(n.length===a.length&&fr(n,a))return!0}catch{}return!1}import{timingSafeEqual as br}from"crypto";var Dn=E("ws"),Je=new Set;function vr(o,e){o.get("/events",{websocket:!0},(t,s)=>{if(e&&!On(s,e)){t.close(4401,"Unauthorized");return}Je.add(t),t.on("close",()=>{Je.delete(t)}),t.on("error",r=>{Dn.error({error:r},"WebSocket error"),Je.delete(t)})}),g.on("task_status_change",t=>{z(t)}),g.on("approval_request",t=>{z(t)}),g.on("stats_update",t=>{z(t)}),g.on("log_event",t=>{z(t)}),g.on("config_changed",t=>{z(t)}),g.on("plan_approval_request",t=>{(()=>{try{let r=cs(t.taskId);if(!r)return!1;let n=ls(r.sessionId);return n?n.source.type==="channel"&&!!n.source.channelId:!1}catch{return!1}})()||z(t)}),g.on("plan_approval_decision",t=>{z(t)}),g.on("task_created",t=>{z(t)}),g.on("execution_slot_change",t=>{z(t)}),g.on("execution_task_start",t=>{z(t)}),g.on("execution_task_end",t=>{z(t)})}function z(o){let e=JSON.stringify(o);for(let t of Je)t.readyState===1&&t.send(e)}function On(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&br(n,a))return!0}catch{}let s=o.query,r=s.api_key||s["x-api-key"];if(r)try{let n=Buffer.from(r),a=Buffer.from(e);if(n.length===a.length&&br(n,a))return!0}catch{}return!1}ke();function Fn(o){return{id:o.id,sdkSessionId:o.sdk_session_id??void 0,userTaskSessionId:o.user_task_session_id??void 0,workspacePath:o.workspace_path??void 0,toolsFingerprint:o.tools_fingerprint??void 0,createdAt:o.created_at,lastActiveAt:o.last_active_at??void 0}}function xt(){let o=j(),e=o.prepare("SELECT * FROM server_state WHERE id = 1").get();if(e)return Fn(e);let t=Date.now();return o.prepare("INSERT INTO server_state (id, created_at) VALUES (1, ?)").run(t),{id:1,createdAt:t}}function Pe(o){let e=j(),t=[],s=[];"sdkSessionId"in o&&(t.push("sdk_session_id = ?"),s.push(o.sdkSessionId??null)),"userTaskSessionId"in o&&(t.push("user_task_session_id = ?"),s.push(o.userTaskSessionId??null)),"workspacePath"in o&&(t.push("workspace_path = ?"),s.push(o.workspacePath??null)),"lastActiveAt"in o&&(t.push("last_active_at = ?"),s.push(o.lastActiveAt??null)),"toolsFingerprint"in o&&(t.push("tools_fingerprint = ?"),s.push(o.toolsFingerprint??null)),t.length!==0&&(xt(),s.push(1),e.prepare(`UPDATE server_state SET ${t.join(", ")} WHERE id = ?`).run(...s))}function Dt(o){Pe({sdkSessionId:o,lastActiveAt:Date.now()})}function Rr(){Pe({sdkSessionId:void 0,lastActiveAt:Date.now()})}function Ir(o){Pe({workspacePath:o})}ie();kt();St();import{z as m}from"zod/v4";import{v4 as kr}from"uuid";import{rmSync as Mn,existsSync as Ot}from"fs";var Tr=m.object({model:m.string().optional(),effort:m.enum(["low","medium","high","max"]).optional(),maxTurns:m.number().optional()}),wr=m.object({path:m.string(),inheritPlugins:m.boolean().optional(),inheritMcp:m.boolean().optional(),inheritPermissions:m.boolean().optional()}),jn=m.object({name:m.string().min(1,"name is required"),cagPrompt:m.string().optional(),learnedRules:m.array(m.string()).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),evaluationCriteria:m.record(m.string(),m.number()).optional(),executionMode:m.enum(["isolated","inline"]).optional(),model:m.string().optional(),maxBudgetUsd:m.number().optional(),approvalRequired:m.array(m.string()).optional(),preferences:Tr.optional(),additionalDirectories:m.array(wr).optional(),allowedChannels:m.array(m.string()).optional(),inheritUserSettings:m.boolean().optional()}),Nn=m.object({name:m.string().min(1).optional(),cagPrompt:m.string().optional(),learnedRules:m.array(m.string()).optional(),status:m.enum(["active","inactive","retired"]).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),evaluationCriteria:m.record(m.string(),m.number()).optional(),executionMode:m.enum(["isolated","inline"]).optional(),model:m.string().optional(),maxBudgetUsd:m.number().optional(),approvalRequired:m.array(m.string()).optional(),preferences:Tr.optional(),additionalDirectories:m.array(wr).optional(),allowedChannels:m.array(m.string()).nullable().optional(),inheritUserSettings:m.boolean().optional()}),Qe=m.object({id:m.string().min(1)}),Ln=m.object({status:m.enum(["active","inactive","retired"]).optional(),limit:m.coerce.number().min(1).max(100).default(100),offset:m.coerce.number().min(0).default(0)}),qn=m.object({path:m.string().min(1)});async function Sr(o){o.get("/roles",{schema:{tags:["Roles"],summary:"List all roles",description:"List all roles with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["active","inactive","retired"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(e,t)=>{let s=Ln.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let{status:r,limit:n,offset:a}=s.data;return{roles:oe(r,n,a).map(d=>({...d,workspacePath:se(d.name)}))}}),o.post("/roles",{schema:{tags:["Roles"],summary:"Create a role",description:"Create a new role with a name, CAG prompt, and optional preferences.",body:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let s=jn.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let{name:r,cagPrompt:n,learnedRules:a,allowedTools:i,disallowedTools:d,evaluationCriteria:c,executionMode:l,model:b,maxBudgetUsd:u,approvalRequired:y,preferences:w,additionalDirectories:v,allowedChannels:W,inheritUserSettings:T}=s.data;if(ht(r))return t.status(409).send({code:"CONFLICT",message:`Role with name '${r}' already exists`});let Q={id:`role-${kr().slice(0,8)}`,name:r,cagPrompt:n??"",learnedRules:a??[],memoryStreamId:`mem-${kr().slice(0,8)}`,status:"active",preferences:w??{},allowedTools:i,disallowedTools:d,evaluationCriteria:c,executionMode:l,model:b,maxBudgetUsd:u,approvalRequired:y,additionalDirectories:v,allowedChannels:W,inheritUserSettings:T,createdAt:Date.now()};return yt(Q),Te(Q),t.status(201).send({role:Q})}),o.get("/roles/:id",{schema:{tags:["Roles"],summary:"Get role by ID",description:"Retrieve a single role with its project-scope plugins.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=B(s.data.id);if(!r)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=se(r.name),a=fe({scope:"project",projectPath:n});return{role:r,projectPlugins:a,workspacePath:n}}),o.patch("/roles/:id",{schema:{tags:["Roles"],summary:"Update a role",description:"Partially update a role's CAG prompt, learned rules, status, or preferences.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},learnedRules:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","inactive","retired"]},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=Nn.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(r.error)});if(!B(s.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let{allowedChannels:a,...i}=r.data,d={...i,updatedAt:Date.now()};if(a!==void 0&&(d.allowedChannels=a??void 0),bt(s.data.id,d),r.data.cagPrompt!==void 0||r.data.learnedRules!==void 0){let l=B(s.data.id);if(l){let b=se(l.name);Ot(b)&&Rt(b,l)}}let c=B(s.data.id);if(c&&(r.data.allowedTools!==void 0||r.data.disallowedTools!==void 0)){let l=se(c.name);Ot(l)&&It(c.id,c.allowedTools,l)}return{role:c}}),o.delete("/roles/:id",{schema:{tags:["Roles"],summary:"Delete a role",description:"Delete a role and its workspace.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=B(s.data.id);if(!r)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=se(r.name);if(Ot(n))try{Mn(n,{recursive:!0,force:!0})}catch{}return vt(s.data.id),{roleId:s.data.id,deleted:!0}}),o.post("/roles/:id/scan-directory",{schema:{tags:["Roles"],summary:"Scan directory for plugin/permission configuration",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=qn.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(r.error)});if(!B(s.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=Ue(r.data.path);return{path:r.data.path,enabledPlugins:a.enabledPlugins,mcpServers:a.mcpServers,allowedTools:a.allowedTools,disallowedTools:a.disallowedTools}})}me();import{z as Pr}from"zod/v4";import{readdirSync as Bn,existsSync as Un}from"fs";import{join as Ft,resolve as Cr,sep as Ar}from"path";import{homedir as Wn}from"os";var Gn=20,Vn=Pr.object({prefix:Pr.string()});function Er(o){return o.startsWith("~/")?Ft(Wn(),o.slice(2)):o}function _r(o){let e=Cr(o);for(let t of zt){let s=Er(t),r=Cr(s);if(e===r||e.startsWith(r+Ar))return!0}return!1}async function xr(o){o.get("/fs/suggest-dirs",{schema:{tags:["FS"],summary:"Suggest directory completions",description:"Return directory suggestions matching a given path prefix.",querystring:{type:"object",required:["prefix"],properties:{prefix:{type:"string"}}}}},async(e,t)=>{let s=Vn.safeParse(e.query);if(!s.success)return{suggestions:[]};let{prefix:r}=s.data;if(!r.startsWith("/")&&!r.startsWith("~/"))return{suggestions:[]};if(_r(r))return{suggestions:[]};let n=Er(r),a,i;if(r.endsWith("/"))a=n,i="";else{let v=Math.max(n.lastIndexOf("/"),n.lastIndexOf(Ar));if(v<0)return{suggestions:[]};a=n.slice(0,v+1),i=n.slice(v+1)}if(!Un(a))return{suggestions:[]};let d;try{d=Bn(a,{withFileTypes:!0}).filter(v=>v.isDirectory()).map(v=>v.name)}catch{return{suggestions:[]}}let c=i.toLowerCase(),l=d.filter(v=>v.toLowerCase().startsWith(c)),y=(i.startsWith(".")?l:l.filter(v=>!v.startsWith("."))).filter(v=>!_r(Ft(a,v)));return y.sort((v,W)=>v.localeCompare(W,void 0,{sensitivity:"base"})),{suggestions:y.slice(0,Gn).map(v=>Ft(a,v))}})}import{z as K}from"zod/v4";ie();var $n=K.object({roleId:K.string().min(1)}),Hn=K.object({roleId:K.string().min(1),prompt:K.string().min(1),topK:K.number().min(1).max(50).default(10)}),zn=K.object({limit:K.coerce.number().min(1).max(200).default(50),offset:K.coerce.number().min(0).default(0)});function Dr(o){return B(o)!==void 0}async function Or(o){o.get("/memories/:roleId",{schema:{tags:["Memories"],summary:"List role memories",description:"List all memories for a specific role with pagination. Embeddings are stripped from the response.",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}},response:R.memoryList}},async(e,t)=>{let s=$n.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:K.prettifyError(s.error)});let r=s.data.roleId;if(!Dr(r))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let n=zn.safeParse(e.query),{limit:a,offset:i}=n.success?n.data:{limit:50,offset:0},c=ys(r,a,i).map(({embedding:l,...b})=>b);return{memories:c,count:c.length}}),o.post("/memories/query",{schema:{tags:["Memories"],summary:"Query role memories",description:"Query a role's memories using hybrid search (FTS5 + vector similarity) with Smallville-style scoring (recency, importance, relevance).",body:{type:"object",required:["roleId","prompt"],properties:{roleId:{type:"string",minLength:1,description:"The role whose memories to query"},prompt:{type:"string",minLength:1,description:"The search query"},topK:{type:"integer",minimum:1,maximum:50,default:10,description:"Number of results to return"}}},response:R.memoryQuery}},async(e,t)=>{let s=Hn.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:K.prettifyError(s.error)});let{roleId:r,prompt:n,topK:a}=s.data;if(!Dr(r))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let d=(await bs(r,n,{topK:a})).map(({embedding:c,...l})=>l);return{memories:d,count:d.length}})}ie();import{v4 as be}from"uuid";import{CronExpressionParser as Jn}from"cron-parser";import{v4 as Kn}from"uuid";var Ce=E("scheduler"),Ye=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let s=ge(),r=e.config?.fileAccess,n={timeout:e.config?.timeout??s.timeout,approvalRequired:s.approvalRequired,approvalTimeout:s.approvalTimeout,fileAccess:{allowedPaths:[...s.fileAccess.allowedPaths,...r?.allowedPaths??[]],deniedPaths:[...s.fileAccess.deniedPaths,...r?.deniedPaths??[]]},plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??s.model,maxTurns:e.config?.maxTurns??s.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??s.maxBudgetUsd,env:{...s.env,...e.config?.env},claudeCodePath:s.claudeCodePath},a={templateId:e.id,executionId:t,stepResults:new Map,config:n},i=this.sortSteps(e.steps);for(let d of i){try{await this.executeStep(d,a)}catch(l){Ce.error({stepId:d.id,error:l},"Workflow step failed");break}if(a.stepResults.get(d.id)?.status==="failed"){Ce.warn({stepId:d.id},"Workflow step failed, workflow aborted");break}}Ce.info({executionId:t,completedSteps:a.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,s=[],r=new Map(e.map(a=>[a.id,a])),n=a=>{if(!t.has(a.id)){if(t.add(a.id),a.dependsOn)for(let i of a.dependsOn){let d=r.get(i);d&&n(d)}s.push(a)}};for(let a of e)n(a);return s}async executeStep(e,t){let s=this.resolveVariables(e.prompt,t.stepResults),r=Kn();ae({id:r,status:"pending",prompt:s,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId}),Ce.debug({stepId:e.id,taskId:r},"Created workflow step as task"),g.emit({type:"task_created",taskId:r});let n=await this.executeWithRetry(r,e.id),a=A(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:n==="completed"?"completed":"failed",result:a?.result,error:a?.error})}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(s,r)=>t.get(r)?.result??`[no result from ${r}]`)}async executeWithRetry(e,t){let s=0;for(;s<this.maxRetries;){if(s++,await this.waitForTaskCompletion(e)==="completed")return"completed";if(s<this.maxRetries){let n=this.baseDelayMs*Math.pow(2,s-1);Ce.info({stepId:t,attempt:s,maxRetries:this.maxRetries,delayMs:n},"Workflow step failed, retrying"),await this.sleep(n)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(s=>{let r=Date.now(),n=()=>{if(Date.now()-r>t){s("failed");return}let a=A(e);if(!a){s("failed");return}if(a.status==="completed"){s("completed");return}if(a.status==="failed"||a.status==="cancelled"){s("failed");return}setTimeout(n,500)};n()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var O=E("scheduler"),Xe="ai-hourly-digest";function Qn(){if(U(Xe)){O.debug({templateId:Xe},"Built-in template already exists");return}let e={id:Xe,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
1
+ import{a as ks,b as Ts,d as kr,e as Tr}from"./chunk-7SPKRIMZ.js";import{c as Pr,d as _r}from"./chunk-NICRQZ7T.js";import{b as fr,c as yr}from"./chunk-B6S2AEOD.js";import{a as hr,b as br,d as vr}from"./chunk-2EP27EGS.js";import{b as Rr}from"./chunk-UOTDT2KY.js";import{a as fs,b as ys,c as kt,d as ws,e as qe,f as Ss,g as Cs,h as Ps,i as _s,j as Xs,k as Zs,l as er,m as tr,n as sr,o as rr,p as nr,q as or,r as ar,s as ir,t as cr,u as dr,v as ve,w as lr,y as Ct}from"./chunk-2VKE7ONM.js";import{a as Js}from"./chunk-5JLMSNIW.js";import{a as us,c as ms,e as gs}from"./chunk-IXF3XBGX.js";import{a as pt,b as ut}from"./chunk-AXMXXUPO.js";import{a as pr,b as Ve,c as ur,d as mr,e as gr}from"./chunk-KICPHTI2.js";import{b as $e,c as Vs,d as H,e as Gs,f as Hs,g as Ks,h as wt,i as se,j as zs,n as Qs,o as Ys}from"./chunk-FUGJMHY4.js";import{b as Rs,c as Is}from"./chunk-5ASEAZCR.js";import{a as te,b as It,c as bs,e as vs}from"./chunk-742NWPTQ.js";import{b as $s,d as We,f as be}from"./chunk-PQ7KPALO.js";import{h as ls,i as ps}from"./chunk-FDWW245P.js";import{a as Tt,b as Os,c as Fs}from"./chunk-2GXYBWLS.js";import{a as Rt,b as hs}from"./chunk-WZOMGJSY.js";import{a as Us,c as Ws}from"./chunk-DT2LX4XI.js";import{b as le,c as Ue,d as qs,e as Bs}from"./chunk-WXN3PSVX.js";import{a as lt,b as D,c as G,d as M,e as os}from"./chunk-L7426WNY.js";import{a as f}from"./chunk-L7JP7DUO.js";import{a as As,b as Be,c as Es,g as xs,j as Ds}from"./chunk-HAWA62R2.js";import{a as ds,b as wr,c as Pt,d as Sr,e as Cr,f as Ar}from"./chunk-EALDBELJ.js";import{b as St,c as Ge,d as Ir}from"./chunk-JXD6ZPV7.js";import{a as js,b as ne,c as Ns,d as Ls,g as Ms}from"./chunk-VF6GJGD6.js";import{b as ts,c as ss,d as rs,e as ns}from"./chunk-T25NLVMY.js";import{a as es}from"./chunk-ETQ7KC73.js";import{a as je,b as it,c as Jt,d as U,e as Ne,f as Le,g as Xt,h as ct}from"./chunk-FYDFMYUP.js";import"./chunk-TN6H2WM2.js";import{a as ee,b as we,c as ht,d as bt,f as vt}from"./chunk-U36NBCR3.js";import{a as as,b as is,c as Dn,e as mt,f as q,g as gt,h as ft,i as Te,j as yt,l as he}from"./chunk-XNWZZYAV.js";import{b as L,c as dt,d as ke}from"./chunk-PCSZW2PE.js";import{b as Zt,c as A,g as de}from"./chunk-SFUS33SO.js";import{a as cs,c as O,d as Me}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{writeFileSync as _n,mkdirSync as An,unlinkSync as na}from"fs";import{join as nt}from"path";de();import{readFileSync as On,existsSync as Fn}from"fs";import{resolve as _t}from"path";function Er(o=A){let e=[],t=[],r=process.env.ADAM_ENV_FILE;r&&t.push(_t(o,r)),t.push(_t(o,".env.local")),t.push(_t(o,".env"));for(let s of t){if(!Fn(s))continue;jn(s)>0&&e.push(s)}return e}function jn(o){let t=On(o,"utf-8").split(`
2
+ `),r=0;for(let s of t){let n=s.trim();if(!n||n.startsWith("#"))continue;n.startsWith("export ")&&(n=n.slice(7).trim());let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim();if(!i)continue;let c=n.slice(a+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c=c.replace(/\$\{(\w+)\}|\$(\w+)/g,(l,d,m)=>{let h=d??m;return process.env[h]??""}),(i.startsWith("ANTHROPIC_")||process.env[i]===void 0)&&(process.env[i]=c,r++)}return r}ke();he();vt();import{existsSync as xr}from"fs";import Nn from"path";import Ln from"fastify";import Mn from"@fastify/cors";import qn from"@fastify/static";import Bn from"@fastify/websocket";import Un from"@fastify/swagger";import Wn from"@fastify/swagger-ui";import{timingSafeEqual as $n}from"crypto";function Or(o,e){let t=Ln({logger:!1});if(t.register(Un,{openapi:{info:{title:"Adam API",description:"Agent orchestration server built on Claude Agent SDK. Multi-agent system with parallel task execution, intelligent agent routing, self-evolving personas, and REST/WebSocket API.",version:"2.0.0"},servers:[{url:"http://localhost:7100"}],tags:[{name:"Tasks",description:"Task lifecycle management"},{name:"Roles",description:"Role CRUD and workspace management"},{name:"Skills",description:"Skill CRUD and permissions"},{name:"Memories",description:"Agent memory search and retrieval"},{name:"Goals",description:"Goal-driven task management"},{name:"Strategies",description:"Thompson Sampling strategy engine"},{name:"Templates",description:"Task template CRUD and triggers"},{name:"Webhooks",description:"External system integration"},{name:"Config",description:"Runtime configuration management"},{name:"Evolution",description:"Agent evolution audit log"},{name:"Health",description:"Server health checks"}],components:{securitySchemes:{apiKey:{type:"apiKey",in:"header",name:"x-api-key",description:"API key for webhook endpoints"}}}}}),t.register(Wn,{routePrefix:"/docs"}),t.register(Mn,{origin:!0}),t.register(Bn,{options:{maxPayload:1024*1024*16}}),e){let s=Buffer.from(e);t.addHook("onRequest",async(n,a)=>{let i=n.url;if(i==="/healthz"||i==="/readyz"||i.startsWith("/docs")||i.startsWith("/ui"))return;let c=n.headers["x-api-key"];if(c&&Dr(c,s))return;let l=n.query,d=l.api_key||l["x-api-key"];if(!(d&&Dr(d,s)))return a.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"})})}let r=Nn.join(ds,"web/dist");return xr(r)&&(t.register(qn,{root:r,prefix:"/ui/",wildcard:!1}),t.get("/ui",async(s,n)=>n.sendFile("index.html",r)),t.get("/ui/*",async(s,n)=>n.sendFile("index.html",r))),t.setErrorHandler((s,n,a)=>{if(s.validation){let c=s.validation.map(l=>{let d=l.instancePath||l.params?.missingProperty||"";return d?`${d}: ${l.message}`:l.message});return a.status(400).send({code:"VALIDATION_ERROR",message:c.join("; ")})}let i=s.statusCode??500;return a.status(i).send({code:"INTERNAL_ERROR",message:s.message})}),t.setNotFoundHandler((s,n)=>s.url.startsWith("/ui")&&xr(r)?n.sendFile("index.html",r):n.status(404).send({code:"NOT_FOUND",message:"Route not found"})),t}function Dr(o,e){try{let t=Buffer.from(o);return t.length!==e.length?!1:$n(t,e)}catch{return!1}}import{z as p}from"zod/v4";import{v4 as Jn}from"uuid";var Vn=o=>({...o,nullable:!0}),w={type:"object",properties:{code:{type:"string"},message:{type:"string"}}},Gn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}},Hn={type:"object",additionalProperties:!0,properties:{type:{type:"string"},cron:{type:"string"},event:{type:"string"}}},Fr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},trigger:Hn,steps:{type:"array",items:Gn},agentPreference:{type:"string"},config:{type:"object",additionalProperties:!0},tags:{type:"array",items:{type:"string"}},enabled:{type:"boolean"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Kn={type:"object",properties:{input:{type:"number"},output:{type:"number"}}},jr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},parentId:{type:"string"},status:{type:"string"},prompt:{type:"string"},originalPrompt:{type:"string"},config:{type:"object",additionalProperties:!0},result:{type:"string"},error:{type:"string"},sdkSessionId:{type:"string"},roleId:{type:"string"},templateId:{type:"string"},createdAt:{type:"number"},startedAt:{type:"number"},completedAt:{type:"number"},costUsd:{type:"number"},tokenUsage:Kn,numTurns:{type:"number"},totalDurationMs:{type:"number"}}},zn={type:"object",additionalProperties:!0,properties:{model:{type:"string"},effort:{type:"string"},maxTurns:{type:"number"}}},He={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},source:{type:"string"},traits:{type:"array",items:{type:"string"}},background:{type:"string"},preferences:zn,learnedRules:{type:"array",items:{type:"string"}},memoryStreamId:{type:"string"},status:{type:"string"},createdAt:{type:"number"},lastActiveAt:{type:"number"},taskCount:{type:"number"},performanceScore:{type:"number"},role:{type:"string"},toolProfile:{type:"array",items:{type:"string"}},evaluationCriteria:{type:"object",additionalProperties:{type:"number"}},strategyPoolId:{type:"string"}}},At={type:"object",additionalProperties:!0,properties:{id:{type:"string"},roleId:{type:"string"},type:{type:"string"},content:{type:"string"},keywords:{type:"array",items:{type:"string"}},importance:{type:"number"},sourceType:{type:"string"},sourceTaskId:{type:"string"},evidence:{type:"array",items:{type:"string"}},createdAt:{type:"number"},lastAccessed:{type:"number"},retrievedCount:{type:"number"},score:{type:"number"}}},Qn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},role:{type:"string"},taskType:{type:"string"},name:{type:"string"},promptTemplate:{type:"string"},alpha:{type:"number"},beta:{type:"number"},totalTrials:{type:"number"},avgReward:{type:"number"},toolProfile:{type:"array",items:{type:"string"}},createdAt:{type:"number"},updatedAt:{type:"number"}}},Et={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},role:{type:"string"},metricType:{type:"string"},targetValue:{type:"number"},currentValue:{type:"number"},deadline:{type:"number"},budgetUsd:{type:"number"},status:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Yn={type:"object",additionalProperties:!0,properties:{name:{type:"string"},displayName:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}},trigger:{type:"string"}}},R={templateCreated:{201:{type:"object",properties:{templateId:{type:"string"}}}},templateList:{200:{type:"object",properties:{templates:{type:"array",items:Fr}}}},templateDetail:{200:{type:"object",properties:{template:Fr}},404:w},templateUpdated:{200:{type:"object",properties:{templateId:{type:"string"}}},404:w},templateDeleted:{200:{type:"object",properties:{templateId:{type:"string"},deleted:{type:"boolean"}}},404:w},templateRun:{200:{type:"object",properties:{executionId:{type:"string"},status:{type:"string"}}},404:w},taskCreated:{201:{type:"object",properties:{taskId:{type:"string"}}},400:w},taskList:{200:{type:"object",properties:{tasks:{type:"array",items:jr}}}},taskDetail:{200:{type:"object",properties:{task:jr}},404:w},taskAction:{200:{type:"object",additionalProperties:!0,properties:{taskId:{type:"string"}}},400:w,404:w},approvalAction:{200:{type:"object",properties:{approvalId:{type:"string"},decision:{type:"string"}}},404:w},agentList:{200:{type:"object",properties:{roles:{type:"array",items:He}}}},agentDetail:{200:{type:"object",properties:{agent:He}},404:w},agentCreated:{201:{type:"object",properties:{agent:He}}},agentUpdated:{200:{type:"object",properties:{agent:He}},404:w},agentDeleted:{200:{type:"object",properties:{agentId:{type:"string"},deleted:{type:"boolean"}}},400:w,404:w},agentPersona:{200:{type:"object",properties:{persona:Vn({type:"string"})}},404:w},memoryList:{200:{type:"object",properties:{memories:{type:"array",items:At},count:{type:"number"}}},404:w},memoryQuery:{200:{type:"object",properties:{memories:{type:"array",items:At},count:{type:"number"}}},404:w},memoryCreated:{201:{type:"object",properties:{memory:At}},400:w,404:w},memoryUpdated:{200:{type:"object",properties:{memoryId:{type:"string"},updated:{type:"boolean"},embeddingUpdated:{type:"boolean"}}},400:w,404:w},memoryDeleted:{200:{type:"object",properties:{memoryId:{type:"string"},deleted:{type:"boolean"}}},404:w},strategyList:{200:{type:"object",properties:{strategies:{type:"array",items:Qn}}}},strategyProbabilities:{200:{type:"object",additionalProperties:!0,properties:{role:{type:"string"},taskType:{type:"string"},stats:{type:"object",additionalProperties:!0},probabilities:{type:"object",additionalProperties:{type:"number"}}}}},goalList:{200:{type:"object",properties:{goals:{type:"array",items:Et}}}},goalDetail:{200:{type:"object",properties:{goal:Et}},404:w},goalCreated:{201:{type:"object",properties:{goal:Et}},400:{...w,additionalProperties:!0,properties:{...w.properties,errors:{type:"array",items:{type:"string"}},warnings:{type:"array",items:{type:"string"}}}}},webhookTriggered:{202:{type:"object",properties:{code:{type:"string"},message:{type:"string"},executionId:{type:"string"},templateId:{type:"string"}}},401:w,404:w,409:w,500:w},webhookList:{200:{type:"object",properties:{webhooks:{type:"array",items:Yn},auth:{type:"string"}}}},configGet:{200:{type:"object",additionalProperties:!0,properties:{config:{type:"object",additionalProperties:{type:"object",additionalProperties:!0,properties:{value:{},mutable:{type:"boolean"}}}},mutable:{type:"array",items:{type:"string"}},restartRequired:{type:"array",items:{type:"string"}}}}},configPatch:{200:{type:"object",additionalProperties:!0,properties:{success:{type:"boolean"},updated:{type:"array",items:{type:"string"}},errors:{type:"array",items:{type:"string"}},message:{type:"string"}}}},healthz:{200:{type:"object",properties:{status:{type:"string"}}}},readyz:{200:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}},503:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}}}};var Nr=p.union([p.object({type:p.literal("session"),sessionId:p.string()}),p.object({type:p.literal("channel"),channelId:p.string(),chatId:p.string().optional()})]),Xn=p.object({prompt:p.string().min(1,"prompt is required"),roleId:p.string().optional(),deliverTo:p.array(Nr).optional(),reportTo:p.array(Nr).optional(),config:p.object({allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),maxTurns:p.number().optional(),maxBudgetUsd:p.number().optional(),mcpServers:p.record(p.string(),p.unknown()).optional(),model:p.string().optional(),effort:p.enum(["low","medium","high","max"]).optional(),settingSources:p.array(p.string()).optional(),workspacePath:p.string().optional(),timeout:p.number().optional(),approvalRequired:p.array(p.string()).optional(),approvalTimeout:p.number().optional(),fileAccess:p.object({allowedPaths:p.array(p.string()),deniedPaths:p.array(p.string())}).optional(),env:p.record(p.string(),p.string()).optional(),plugins:p.array(p.string()).optional()}).optional()}),pe=p.object({id:p.string().uuid()}),Zn=["pending","queued","running","paused","completed","failed","cancelled"],eo=p.object({status:p.enum(Zn).optional(),roleId:p.string().optional(),limit:p.coerce.number().min(1).max(100).default(100),offset:p.coerce.number().min(0).default(0)});async function Lr(o){let e=new ys;o.post("/tasks",{schema:{tags:["Tasks"],summary:"Create a task",description:"Create a new task with a prompt and optional agent/config overrides. The task enters 'pending' status and is picked up by the scheduler.",body:{type:"object",required:["prompt"],properties:{prompt:{type:"string",minLength:1,description:"Task prompt"},roleId:{type:"string",description:"Role to assign"},config:{type:"object",description:"Optional task configuration overrides",properties:{model:{type:"string"},maxTurns:{type:"integer"},maxBudgetUsd:{type:"number"},timeout:{type:"integer"},effort:{type:"string",enum:["low","medium","high","max"]}}}}},response:R.taskCreated}},async(n,a)=>{let i=Xn.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{prompt:c,roleId:l,config:d,deliverTo:m,reportTo:h}=i.data,I=rs(),y={timeout:d?.timeout??I.timeout,approvalRequired:d?.approvalRequired??I.approvalRequired,approvalTimeout:d?.approvalTimeout??I.approvalTimeout,fileAccess:d?.fileAccess??I.fileAccess,allowedTools:d?.allowedTools??I.allowedTools,disallowedTools:d?.disallowedTools??I.disallowedTools,maxTurns:d?.maxTurns??I.maxTurns,maxBudgetUsd:d?.maxBudgetUsd??I.maxBudgetUsd,mcpServers:d?.mcpServers,model:d?.model||I.model||void 0,effort:d?.effort??I.effort,settingSources:d?.settingSources??I.settingSources,workspacePath:d?.workspacePath,env:d?.env??I.env,claudeCodePath:I.claudeCodePath,plugins:d?.plugins},g={id:Jn(),status:"pending",prompt:c,roleId:l,config:y,deliverTo:m,reportTo:h,createdAt:Date.now()};return lt(g),f.emit({type:"task_created",taskId:g.id}),a.status(201).send({taskId:g.id})}),o.get("/tasks",{schema:{tags:["Tasks"],summary:"List tasks",description:"List tasks with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["pending","queued","running","paused","completed","failed","cancelled"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}},response:R.taskList}},async(n,a)=>{let i=eo.safeParse(n.query);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{status:c,roleId:l,limit:d,offset:m}=i.data;return{tasks:M(c,d,m,l)}}),o.get("/tasks/:id",{schema:{tags:["Tasks"],summary:"Get task by ID",description:"Retrieve a single task by its UUID.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskDetail}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=D(i.data.id);return c?{task:c}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"})}),o.post("/tasks/:id/cancel",{schema:{tags:["Tasks"],summary:"Cancel a task",description:"Cancel a running, queued, pending, or paused task. Returns 400 if the task is in a terminal state.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskAction}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=D(i.data.id);return c?c.status!=="running"&&c.status!=="queued"&&c.status!=="pending"&&c.status!=="paused"?a.status(400).send({code:"INVALID_STATE",message:`Cannot cancel task in status: ${c.status}`}):(e.cancelTask(c.id),{taskId:c.id,status:"cancelled"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"})});let t=p.object({taskIds:p.array(p.string()).min(1).max(500)});o.post("/tasks/batch-cancel",{schema:{tags:["Tasks"],summary:"Batch cancel tasks",description:"Cancel multiple tasks at once. Skips tasks that are already in terminal state. Returns count of cancelled tasks.",body:{type:"object",required:["taskIds"],properties:{taskIds:{type:"array",items:{type:"string"},minItems:1,maxItems:500}}}}},async(n,a)=>{let i=t.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=new Set(["pending","queued","running","paused"]),l=0,d=[];for(let m of i.data.taskIds){let h=D(m);if(!h){d.push({taskId:m,reason:"not found"});continue}if(!c.has(h.status)){d.push({taskId:m,reason:`already ${h.status}`});continue}e.cancelTask(m),l++}return{cancelled:l,total:i.data.taskIds.length,errors:d.length>0?d:void 0}}),o.get("/tasks/:id/logs",{schema:{tags:["Tasks"],summary:"Get task step logs",description:"Returns execution step logs for a task (reasoning, tool calls, results).",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(n,a)=>{let i=D(n.params.id);if(!i)return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:c=50,offset:l=0}=n.query;return{logs:ut(i.id,c,l)}});let r=p.object({approvalId:p.string().uuid(),reason:p.string().optional()});o.post("/tasks/:id/approve",{schema:{tags:["Tasks"],summary:"Approve a pending approval",description:"Approve a tool-use approval request for a paused task. The skill agent resumes execution with the approved tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=r.safeParse(n.body);return c.success?D(i.data.id)?e.resolveApproval(c.data.approvalId,"allow",c.data.reason)?{approvalId:c.data.approvalId,decision:"allow"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(c.error)})}),o.post("/tasks/:id/reject",{schema:{tags:["Tasks"],summary:"Reject a pending approval",description:"Reject a tool-use approval request for a paused task. The skill agent skips the denied tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=r.safeParse(n.body);return c.success?D(i.data.id)?e.resolveApproval(c.data.approvalId,"deny",c.data.reason)?{approvalId:c.data.approvalId,decision:"deny"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(c.error)})});let s=p.object({planId:p.string(),decision:p.enum(["allow","deny"]),approvalType:p.enum(["once","permanent"]).optional(),reason:p.string().optional()});o.post("/tasks/:id/approve-plan",{schema:{tags:["Tasks"],summary:"Approve or deny an execution plan",description:"Respond to a plan approval request. Allow once (single task), allow permanent (create rule for similar tasks), or deny.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["planId","decision"],properties:{planId:{type:"string"},decision:{type:"string",enum:["allow","deny"]},approvalType:{type:"string",enum:["once","permanent"]},reason:{type:"string"}}}}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=s.safeParse(n.body);if(!c.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(c.error)});if(!D(i.data.id))return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{planId:d,decision:m,approvalType:h,reason:I}=c.data;return e.resolvePlanApproval(d,m,h,I)?{planId:d,decision:m,approvalType:h}:a.status(404).send({code:"NOT_FOUND",message:"Plan approval not found or already resolved"})}),o.get("/tasks/:id/plan",{schema:{tags:["Tasks"],summary:"Get execution plans for a task",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(n,a)=>{let i=pe.safeParse(n.params);return i.success?D(i.data.id)?{plans:ms(i.data.id)}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)})}),o.get("/tasks/:id/delivery-log",{schema:{tags:["Tasks"],summary:"Get delivery log for a task",description:"Returns delivery log entries for a task, including channel and webhook delivery attempts.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async(n,a)=>{let i=pe.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let c=D(i.data.id);if(!c)return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:l=50}=n.query;return{logs:ls(c.id,l)}})}ke();he();async function Mr(o,e){o.get("/healthz",{schema:{tags:["Health"],summary:"Health check",description:"Basic liveness probe. Returns 200 if the server process is running.",response:R.healthz}},async(t,r)=>({status:"ok"})),o.get("/readyz",{schema:{tags:["Health"],summary:"Readiness check",description:"Readiness probe that checks database, roles, config, embedding model, and task hub. Returns 503 if any check fails.",response:R.readyz}},async(t,r)=>{let s={database:!1,manager:!1,config:!1};try{L().prepare("SELECT 1").get(),s.database=!0}catch{s.database=!1}s.manager=!0,s.config=!!e.server;try{let a=Te(void 0,1,0);s.agents=a.length>0}catch{s.agents=!1}return s.embedding=hs(),s.taskHub=!0,Object.values(s).every(a=>a)?{status:"ready",checks:s}:r.status(503).send({status:"not_ready",checks:s})}),o.get("/stats",{schema:{tags:["Health"],summary:"Runtime statistics",description:"Returns execution pool status, active/pending task counts, and cost summary."}},async(t,r)=>{let n=U().execution?.maxConcurrent??5,a=M("running"),i=M("pending");return{executionPool:{active:a.length,max:n,queued:i.length}}})}import{timingSafeEqual as Br}from"crypto";import{z as Ur}from"zod/v4";var xt=class{connections=new Map;eventBuffers=new Map;eventIndices=new Map;addConnection(e,t){this.connections.has(e)||this.connections.set(e,new Set),this.connections.get(e).add(t);let r=this.getBufferedEvents(e);for(let s of r)t.readyState===1&&t.send(JSON.stringify(s));t.on("close",()=>{this.removeConnection(e,t)})}removeConnection(e,t){let r=this.connections.get(e);r&&(r.delete(t),r.size===0&&this.connections.delete(e))}broadcast(e,t){this.addToBuffer(e,t);let r=this.connections.get(e);if(!r||r.size===0)return;let s=JSON.stringify(t);for(let n of r)n.readyState===1&&n.send(s)}addToBuffer(e,t){let r=this.eventBuffers.get(e);r||(r=[],this.eventBuffers.set(e,r)),r.push(t),r.length>100&&r.shift(),this.eventIndices.set(e,t.index)}getBufferedEvents(e){return this.eventBuffers.get(e)??[]}getNextIndex(e){let r=(this.eventIndices.get(e)??0)+1;return this.eventIndices.set(e,r),r}},qr=new xt;var to=Ur.object({id:Ur.string().uuid()});async function Wr(o,e){o.get("/tasks/:id/stream",{websocket:!0},(t,r)=>{if(e&&!so(r,e)){t.close(4401,"Unauthorized");return}let s=to.safeParse(r.params);if(!s.success){t.close(1008,"Invalid task ID");return}let{id:n}=s.data;if(!D(n)){t.close(1008,"Task not found");return}qr.addConnection(n,t)})}function so(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&Br(n,a))return!0}catch{}let r=o.query,s=r.api_key||r["x-api-key"];if(s)try{let n=Buffer.from(s),a=Buffer.from(e);if(n.length===a.length&&Br(n,a))return!0}catch{}return!1}import{timingSafeEqual as $r}from"crypto";var ro=O("ws"),Ke=new Set;function Vr(o,e){o.get("/events",{websocket:!0},(t,r)=>{if(e&&!no(r,e)){t.close(4401,"Unauthorized");return}Ke.add(t),t.on("close",()=>{Ke.delete(t)}),t.on("error",s=>{ro.error({error:s},"WebSocket error"),Ke.delete(t)})}),f.on("task_status_change",t=>{K(t)}),f.on("approval_request",t=>{K(t)}),f.on("stats_update",t=>{K(t)}),f.on("log_event",t=>{K(t)}),f.on("config_changed",t=>{K(t)}),f.on("plan_approval_request",t=>{(()=>{try{let s=vs(t.taskId);if(!s)return!1;let n=Rs(s.sessionId);return n?n.source.type==="channel"&&!!n.source.channelId:!1}catch{return!1}})()||K(t)}),f.on("plan_approval_decision",t=>{K(t)}),f.on("task_created",t=>{K(t)}),f.on("execution_slot_change",t=>{K(t)}),f.on("execution_task_start",t=>{K(t)}),f.on("execution_task_end",t=>{K(t)}),f.on("delivery_status_change",t=>{K(t)})}function K(o){let e=JSON.stringify(o);for(let t of Ke)t.readyState===1&&t.send(e)}function no(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&$r(n,a))return!0}catch{}let r=o.query,s=r.api_key||r["x-api-key"];if(s)try{let n=Buffer.from(s),a=Buffer.from(e);if(n.length===a.length&&$r(n,a))return!0}catch{}return!1}ke();function oo(o){return{id:o.id,sdkSessionId:o.sdk_session_id??void 0,userTaskSessionId:o.user_task_session_id??void 0,workspacePath:o.workspace_path??void 0,toolsFingerprint:o.tools_fingerprint??void 0,createdAt:o.created_at,lastActiveAt:o.last_active_at??void 0}}function Dt(){let o=L(),e=o.prepare("SELECT * FROM server_state WHERE id = 1").get();if(e)return oo(e);let t=Date.now();return o.prepare("INSERT INTO server_state (id, created_at) VALUES (1, ?)").run(t),{id:1,createdAt:t}}function Se(o){let e=L(),t=[],r=[];"sdkSessionId"in o&&(t.push("sdk_session_id = ?"),r.push(o.sdkSessionId??null)),"userTaskSessionId"in o&&(t.push("user_task_session_id = ?"),r.push(o.userTaskSessionId??null)),"workspacePath"in o&&(t.push("workspace_path = ?"),r.push(o.workspacePath??null)),"lastActiveAt"in o&&(t.push("last_active_at = ?"),r.push(o.lastActiveAt??null)),"toolsFingerprint"in o&&(t.push("tools_fingerprint = ?"),r.push(o.toolsFingerprint??null)),t.length!==0&&(Dt(),r.push(1),e.prepare(`UPDATE server_state SET ${t.join(", ")} WHERE id = ?`).run(...r))}function ze(o){Se({sdkSessionId:o,lastActiveAt:Date.now()})}function Gr(){Se({sdkSessionId:void 0,lastActiveAt:Date.now()})}function Hr(o){Se({workspacePath:o})}he();vt();import{z as u}from"zod/v4";import{v4 as Kr}from"uuid";_s();import{rmSync as ao,existsSync as Ot}from"fs";var zr=u.object({model:u.string().optional(),effort:u.enum(["low","medium","high","max"]).optional(),maxTurns:u.number().optional()}),Qr=u.object({path:u.string(),inheritPlugins:u.boolean().optional(),inheritMcp:u.boolean().optional(),inheritPermissions:u.boolean().optional()}),io=u.object({name:u.string().min(1,"name is required").regex(/^[\p{L}\p{N}_-]+$/u,"name must contain only letters, numbers, underscores, or hyphens"),cagPrompt:u.string().optional(),learnedRules:u.array(u.string()).optional(),allowedTools:u.array(u.string()).optional(),disallowedTools:u.array(u.string()).optional(),evaluationCriteria:u.record(u.string(),u.number()).optional(),executionMode:u.enum(["isolated","inline"]).optional(),model:u.string().optional(),maxBudgetUsd:u.number().optional(),approvalRequired:u.array(u.string()).optional(),preferences:zr.optional(),additionalDirectories:u.array(Qr).optional(),allowedChannels:u.array(u.string()).optional(),inheritUserSettings:u.boolean().optional()}),co=u.object({name:u.string().min(1).optional(),cagPrompt:u.string().optional(),learnedRules:u.array(u.string()).optional(),status:u.enum(["active","inactive","retired"]).optional(),allowedTools:u.array(u.string()).optional(),disallowedTools:u.array(u.string()).optional(),evaluationCriteria:u.record(u.string(),u.number()).optional(),executionMode:u.enum(["isolated","inline"]).optional(),model:u.string().optional(),maxBudgetUsd:u.number().optional(),approvalRequired:u.array(u.string()).optional(),preferences:zr.optional(),additionalDirectories:u.array(Qr).optional(),allowedChannels:u.array(u.string()).nullable().optional(),inheritUserSettings:u.boolean().optional()}),Qe=u.object({id:u.string().min(1)}),lo=u.object({status:u.enum(["active","inactive","retired"]).optional(),limit:u.coerce.number().min(1).max(100).default(100),offset:u.coerce.number().min(0).default(0)}),po=u.object({path:u.string().min(1)});async function Yr(o){o.get("/roles",{schema:{tags:["Roles"],summary:"List all roles",description:"List all roles with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["active","inactive","retired"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(e,t)=>{let r=lo.safeParse(e.query);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let{status:s,limit:n,offset:a}=r.data;return{roles:Te(s,n,a).map(c=>({...c,workspacePath:ee(c.name)}))}}),o.post("/roles",{schema:{tags:["Roles"],summary:"Create a role",description:"Create a new role with a name, CAG prompt, and optional preferences.",body:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let r=io.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let{name:s,cagPrompt:n,learnedRules:a,allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:h,approvalRequired:I,preferences:y,additionalDirectories:g,allowedChannels:C,inheritUserSettings:W}=r.data;if(gt(s))return t.status(409).send({code:"CONFLICT",message:`Role with name '${s}' already exists`});let $={id:`role-${Kr().slice(0,8)}`,name:s,cagPrompt:n??"",learnedRules:a??[],memoryStreamId:`mem-${Kr().slice(0,8)}`,status:"active",preferences:y??{},allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:h,approvalRequired:I,additionalDirectories:g,allowedChannels:C,inheritUserSettings:W,createdAt:Date.now()};return mt($),we($),t.status(201).send({role:$})}),o.get("/roles/:id",{schema:{tags:["Roles"],summary:"Get role by ID",description:"Retrieve a single role with its project-scope plugins.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let r=Qe.safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let s=q(r.data.id);if(!s)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=ee(s.name),a=qe({scope:"project",projectPath:n});return{role:s,projectPlugins:a,workspacePath:n}}),o.get("/roles/:id/scores",{schema:{tags:["Roles"],summary:"Get role quality scores",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20}}}}},async(e,t)=>{let r=u.object({id:u.string().min(1)}).safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let s=q(r.data.id);if(!s)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=e.query.limit??20,a=ks(s.id,n),i=Ts(s.id);return{scores:a,latestEma:i??null}}),o.patch("/roles/:id",{schema:{tags:["Roles"],summary:"Update a role",description:"Partially update a role's CAG prompt, learned rules, status, or preferences.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},learnedRules:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","inactive","retired"]},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let r=Qe.safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let s=co.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(s.error)});if(!q(r.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let{allowedChannels:a,...i}=s.data,c={...i,updatedAt:Date.now()};if(a!==void 0&&(c.allowedChannels=a??void 0),ft(r.data.id,c),s.data.cagPrompt!==void 0||s.data.learnedRules!==void 0){let d=q(r.data.id);if(d){let m=ee(d.name);Ot(m)&&ht(m,d)}}let l=q(r.data.id);if(l&&(s.data.allowedTools!==void 0||s.data.disallowedTools!==void 0)){let d=ee(l.name);Ot(d)&&bt(l.id,l.allowedTools,d)}return{role:l}}),o.delete("/roles/:id",{schema:{tags:["Roles"],summary:"Delete a role",description:"Delete a role and its workspace.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let r=Qe.safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let s=q(r.data.id);if(!s)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=ee(s.name);if(Ot(n))try{ao(n,{recursive:!0,force:!0})}catch{}return yt(r.data.id),{roleId:r.data.id,deleted:!0}}),o.post("/roles/:id/scan-directory",{schema:{tags:["Roles"],summary:"Scan directory for plugin/permission configuration",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}}}}},async(e,t)=>{let r=Qe.safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(r.error)});let s=po.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(s.error)});if(!q(r.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=Ps(s.data.path);return{path:s.data.path,enabledPlugins:a.enabledPlugins,mcpServers:a.mcpServers,allowedTools:a.allowedTools,disallowedTools:a.disallowedTools}})}de();import{z as Jr}from"zod/v4";import{readdirSync as uo,existsSync as mo}from"fs";import{join as Ft,resolve as Xr,sep as en}from"path";import{homedir as go}from"os";var fo=20,yo=Jr.object({prefix:Jr.string()});function tn(o){return o.startsWith("~/")?Ft(go(),o.slice(2)):o}function Zr(o){let e=Xr(o);for(let t of Zt){let r=tn(t),s=Xr(r);if(e===s||e.startsWith(s+en))return!0}return!1}async function sn(o){o.get("/fs/suggest-dirs",{schema:{tags:["FS"],summary:"Suggest directory completions",description:"Return directory suggestions matching a given path prefix.",querystring:{type:"object",required:["prefix"],properties:{prefix:{type:"string"}}}}},async(e,t)=>{let r=yo.safeParse(e.query);if(!r.success)return{suggestions:[]};let{prefix:s}=r.data;if(!s.startsWith("/")&&!s.startsWith("~/"))return{suggestions:[]};if(Zr(s))return{suggestions:[]};let n=tn(s),a,i;if(s.endsWith("/"))a=n,i="";else{let g=Math.max(n.lastIndexOf("/"),n.lastIndexOf(en));if(g<0)return{suggestions:[]};a=n.slice(0,g+1),i=n.slice(g+1)}if(!mo(a))return{suggestions:[]};let c;try{c=uo(a,{withFileTypes:!0}).filter(g=>g.isDirectory()).map(g=>g.name)}catch{return{suggestions:[]}}let l=i.toLowerCase(),d=c.filter(g=>g.toLowerCase().startsWith(l)),I=(i.startsWith(".")?d:d.filter(g=>!g.startsWith("."))).filter(g=>!Zr(Ft(a,g)));return I.sort((g,C)=>g.localeCompare(C,void 0,{sensitivity:"base"})),{suggestions:I.slice(0,fo).map(g=>Ft(a,g))}})}import{z as S}from"zod/v4";he();import{v4 as ho}from"uuid";var bo=S.object({roleId:S.string().min(1)}),vo=S.object({roleId:S.string().min(1),prompt:S.string().min(1),topK:S.number().min(1).max(50).default(10)}),Ro=S.object({limit:S.coerce.number().min(1).max(200).default(50),offset:S.coerce.number().min(0).default(0)});function jt(o){return q(o)!==void 0}async function rn(o){o.get("/memories/:roleId",{schema:{tags:["Memories"],summary:"List role memories",description:"List all memories for a specific role with pagination. Embeddings are stripped from the response.",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}},response:R.memoryList}},async(r,s)=>{let n=bo.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:S.prettifyError(n.error)});let a=n.data.roleId;if(!jt(a))return s.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let i=Ro.safeParse(r.query),{limit:c,offset:l}=i.success?i.data:{limit:50,offset:0},m=xs(a,c,l).map(({embedding:h,...I})=>I);return{memories:m,count:m.length}}),o.post("/memories/query",{schema:{tags:["Memories"],summary:"Query role memories",description:"Query a role's memories using hybrid search (FTS5 + vector similarity) with Smallville-style scoring (recency, importance, relevance).",body:{type:"object",required:["roleId","prompt"],properties:{roleId:{type:"string",minLength:1,description:"The role whose memories to query"},prompt:{type:"string",minLength:1,description:"The search query"},topK:{type:"integer",minimum:1,maximum:50,default:10,description:"Number of results to return"}}},response:R.memoryQuery}},async(r,s)=>{let n=vo.safeParse(r.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:S.prettifyError(n.error)});let{roleId:a,prompt:i,topK:c}=n.data;if(!jt(a))return s.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let d=(await Tt(a,i,{topK:c})).map(({embedding:m,...h})=>h);return{memories:d,count:d.length}});let e=S.object({roleId:S.string().min(1),content:S.string().min(1),type:S.enum(["event","thought","reflection"]).default("thought"),keywords:S.array(S.string()).default([]),importance:S.number().min(1).max(5).default(3),tier:S.enum(["working","episodic","semantic"]).default("episodic")});o.post("/memories",{schema:{tags:["Memories"],summary:"Create memory",description:"Create a new memory for a role. Embedding is auto-generated from content.",body:{type:"object",required:["roleId","content"],properties:{roleId:{type:"string",minLength:1},content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"],default:"thought"},keywords:{type:"array",items:{type:"string"},default:[]},importance:{type:"integer",minimum:1,maximum:5,default:3},tier:{type:"string",enum:["working","episodic","semantic"],default:"episodic"}}},response:R.memoryCreated}},async(r,s)=>{let n=e.safeParse(r.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:S.prettifyError(n.error)});let{roleId:a,content:i,type:c,keywords:l,importance:d,tier:m}=n.data;if(!jt(a))return s.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let h;try{h=await Rt(i)}catch{}let I=`mem-${ho().slice(0,8)}`,y=Date.now();As({id:I,roleId:a,type:c,content:i,embedding:h,keywords:l,importance:d,sourceType:"manual",createdAt:y,lastAccessed:y,retrievedCount:0,tier:m??"episodic"});let g=Be(I),{embedding:C,...W}=g;return s.status(201).send({memory:W})});let t=S.object({content:S.string().min(1).optional(),type:S.enum(["event","thought","reflection"]).optional(),keywords:S.array(S.string()).optional(),importance:S.number().min(1).max(5).optional()});o.patch("/memories/:id",{schema:{tags:["Memories"],summary:"Update memory",description:"Update a memory's content, type, keywords, or importance. Embedding is regenerated if content changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"]},keywords:{type:"array",items:{type:"string"}},importance:{type:"integer",minimum:1,maximum:5}}},response:R.memoryUpdated}},async(r,s)=>{let{id:n}=r.params;if(!Be(n))return s.status(404).send({code:"NOT_FOUND",message:"Memory not found"});let i=t.safeParse(r.body);if(!i.success)return s.status(400).send({code:"VALIDATION_ERROR",message:S.prettifyError(i.error)});let c=i.data,l,d=!0;if(c.content)try{l=await Rt(c.content)}catch{d=!1}let m=Es(n,{content:c.content,embedding:l,keywords:c.keywords,importance:c.importance,type:c.type});return{memoryId:n,updated:m,embeddingUpdated:d}}),o.delete("/memories/:id",{schema:{tags:["Memories"],summary:"Delete memory",description:"Delete a memory by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.memoryDeleted}},async(r,s)=>{let{id:n}=r.params;return Be(n)?(Ds(n),{memoryId:n,deleted:!0}):s.status(404).send({code:"NOT_FOUND",message:"Memory not found"})})}import{query as So}from"@anthropic-ai/claude-agent-sdk";import{v4 as ue}from"uuid";Dn();de();var Io=new Set(["Read","Glob","Grep","LSP"]),ko=new Set(["Edit","Write","NotebookEdit"]);function Ce(o,e){return async(t,r,{agentID:s})=>{if(Io.has(t))return{behavior:"allow",updatedInput:r};let n=o(s??"");if(ko.has(t)){let a=as(t,r),i=A;if(a.length===0)return{behavior:"allow",updatedInput:r};let c={allowedPaths:n?.allowedPaths??[],deniedPaths:n?.deniedPaths??[]};for(let l of a){let d=is(l,i,c);if(!d.allowed)return{behavior:"deny",message:`Path denied: ${d.reason}. Try an alternative within allowed paths.`}}return{behavior:"allow",updatedInput:r}}if(n?.disallowedTools?.includes(t))return{behavior:"deny",message:`Tool ${t} is not allowed for this role.`};if(e&&n?.approvalRequired?.length){let a=t==="Bash"?r.command??"":`${t} ${JSON.stringify(r)}`;for(let i of n.approvalRequired)try{if(new RegExp(i).test(a))return await e(t,r,i,s)}catch{}}return{behavior:"allow",updatedInput:r}}}function Pe(o){return{SessionStart:[{hooks:[async e=>{if(!o.roleId)return{};let t=e.source,r=o.roleId==="role-chat-manager";if(!r&&t!=="startup"&&t!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-BKLZIRK6.js"),n=o.taskPrompt||"role context and recent interactions",a=r?["semantic","working"]:["semantic","episodic"],i=await s(o.roleId,n,a,{topK:5});if(i.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
3
+ ${i.map(d=>`- [${d.tier??"episodic"}] ${d.content}`).join(`
4
+ `)}
3
5
 
4
- \u641C\u7D22\u6765\u6E90:
5
- 1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
6
- 2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
7
- 3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
8
-
9
- \u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
10
-
11
- \u8F93\u51FA\u683C\u5F0F:
12
- - \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
13
- - \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
14
- - \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
15
- - \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
16
-
17
- \u6587\u7AE0\u4FE1\u606F:
18
- {{search_ai_news.result}}
19
-
20
- \u8BF7:
21
- 1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
22
- 2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
23
- 3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
24
-
25
- \u603B\u7ED3\u7ED3\u6784:
26
- ## \u6838\u5FC3\u53D1\u73B0
27
- [\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
28
-
29
- ## \u6280\u672F\u7EC6\u8282
30
- [\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
31
-
32
- ## \u5F71\u54CD/\u610F\u4E49
33
- [\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
34
-
35
- ## \u539F\u6587\u94FE\u63A5
36
- [\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
37
-
38
- \u603B\u7ED3\u5185\u5BB9:
39
- {{summarize_article.result}}
40
-
41
- \u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
42
-
43
- osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
44
-
45
- \u6CE8\u610F\uFF1A
46
- - \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
47
- - \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
48
- - \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
49
-
50
- \u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300,fileAccess:{allowedPaths:["~/.adam/","/Users/norvyn/Code/Projects/Adam/scripts/"],deniedPaths:[]}},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};We(e),O.info({templateId:Xe,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var Ze=class{cronJobs=new Map;workflowExecutor=new Ye;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,Qn();let e=we(!0),t=0;for(let s of e)s.trigger.type==="cron"&&s.trigger.cron&&(this.scheduleCronJob(s),t++);this.taskCompletionHandler=s=>{s.newStatus==="completed"&&this.checkEventTriggers(s.taskId).catch(r=>{O.error({taskId:s.taskId,error:r},"Event trigger check failed")})},g.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),O.info({cronCount:t},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=oe(void 0,1e3,0),t=0;for(let s of e)t+=hs(s.id);t>0&&O.info({totalCleaned:t},"Memory cleanup completed")}catch(e){O.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(g.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,O.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let s;try{s=Jn.parse(e.trigger.cron)}catch{O.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let c=s.next().getTime()-Date.now();return Math.max(c,1e3)},n=()=>{this.executeCronTrigger(e.id).catch(c=>{O.error({templateId:e.id,error:c},"Cron trigger failed")});let d=setTimeout(n,r());this.cronJobs.set(t,d)},a=r(),i=setTimeout(n,a);this.cronJobs.set(t,i),O.debug({jobName:t,nextRun:new Date(Date.now()+a).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=U(e);!t||!t.enabled||(O.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,be()))}async scheduleJob(e){let t=U(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,s=this.cronJobs.get(t);s&&(clearTimeout(s),this.cronJobs.delete(t))}async runNow(e){let t=U(e);if(!t)throw new Error(`Template ${e} not found`);let s=be();return this.executeWorkflow(t,s).catch(r=>{O.error({templateId:e,error:r},"Workflow execution failed")}),s}async checkEventTriggers(e){let t=A(e);if(!t)return;let s=we(!0),r=s.filter(n=>n.trigger.type==="event"&&n.trigger.event==="task_complete");for(let n of r)O.debug({templateName:n.name},"Event trigger matched"),await this.executeWorkflow(n,be());if(t.templateId){let n=s.filter(a=>a.trigger.type!=="event"||!a.trigger.event?!1:a.trigger.event===`template_complete:${t.templateId}`);for(let a of n)O.info({templateName:a.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(a,be())}}async executeWorkflow(e,t){if(O.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let s of e.goalIds){let r=re(s);if(!r){O.warn({goalId:s,templateId:e.id},"Goal reference not found, skipping");continue}let n=be();ks({id:n,name:r.name,description:r.description,roleId:r.roleId,metricType:r.metricType,targetValue:r.targetValue,currentValue:0,deadline:r.deadline,budgetUsd:r.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,notifyTargets:e.notifyTargets});let a=be();ae({id:a,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:n,config:ge(),createdAt:Date.now(),templateId:e.id}),g.emit({type:"task_created",taskId:a}),O.info({templateId:e.id,sourceGoalId:s,newGoalId:n,taskId:a},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}};import{query as Zn}from"@anthropic-ai/claude-agent-sdk";import{v4 as ne}from"uuid";on();me();var Yn=new Set(["Read","Glob","Grep","LSP"]),Xn=new Set(["Edit","Write","NotebookEdit"]);function _e(o,e){return async(t,s,{agentID:r})=>{if(Yn.has(t))return{behavior:"allow",updatedInput:s};let n=o(r??"");if(Xn.has(t)){let a=Zt(t,s),i=q;if(a.length===0)return{behavior:"allow",updatedInput:s};let d={allowedPaths:n?.allowedPaths??[],deniedPaths:n?.deniedPaths??[]};for(let c of a){let l=es(c,i,d);if(!l.allowed)return{behavior:"deny",message:`Path denied: ${l.reason}. Try an alternative within allowed paths.`}}return{behavior:"allow",updatedInput:s}}if(n?.disallowedTools?.includes(t))return{behavior:"deny",message:`Tool ${t} is not allowed for this role.`};if(e&&n?.approvalRequired?.length){let a=t==="Bash"?s.command??"":`${t} ${JSON.stringify(s)}`;for(let i of n.approvalRequired)try{if(new RegExp(i).test(a))return await e(t,s,i,r)}catch{}}return{behavior:"allow",updatedInput:s}}}function Ae(o){return{SubagentStart:[{hooks:[async e=>{let t=o.roleId??e.agent_id;if(!t)return{};try{let s=await vs("role startup context",t,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async e=>{let t=e.agent_id;if(!t||!o.currentTaskId)return{};try{let{createMemory:s}=await import("./memories-BUNOVQVG.js"),r=e.transcript;if(r&&r.length>100){let n=r.slice(0,500);s({id:`session-${Date.now()}`,roleId:o.roleId??t,type:"event",content:n,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:o.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0})}}catch{}return{}}]}],PostToolUse:[{hooks:[async e=>{if(!o.currentTaskId)return{};let t=e.tool_name,s=e.tool_input,r=e.tool_response,n=typeof r=="string"?r:JSON.stringify(r??"");try{gt({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:o.currentTaskId,index:0,type:"tool_call",content:`${t}: ${JSON.stringify(s??{})} \u2192 ${n.slice(0,200)}`,toolName:t,toolInput:s,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async e=>{let t=e.compact_summary;if(!t)return{};try{let{createMemory:s}=await import("./memories-BUNOVQVG.js");s({id:`compact-${Date.now()}`,roleId:o.roleId??"role-chat-manager",type:"thought",content:t.slice(0,500),keywords:["manager","decision","compaction"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0})}catch{}return{}}]}]}}function Mt(o){return`# ChatManager \u2014 User Interface Agent
6
+ `}}}catch{}return{}}]}],SubagentStart:[{hooks:[async e=>{let t=o.roleId??e.agent_id;if(!t)return{};try{let r=o.taskPrompt||"role context",s=await Os(r,t,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async e=>{let t=e.agent_id;if(!t||!o.currentTaskId)return{};try{let{createMemory:r}=await import("./memories-EFQ4SFZG.js"),{getDb:s}=await import("./db-PNZ3UJOE.js"),n=e.transcript;if(!n||n.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(o.currentTaskId))return{};let i=`[Task ${o.currentTaskId} reasoning] ${n.slice(0,800)}`;r({id:`session-${Date.now()}`,roleId:o.roleId??t,type:"thought",content:i,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:o.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async e=>{if(!o.currentTaskId)return{};let t=e.tool_name,r=e.tool_input,s=e.tool_response,n=typeof s=="string"?s:JSON.stringify(s??"");try{pt({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:o.currentTaskId,index:0,type:"tool_call",content:`${t}: ${JSON.stringify(r??{})} \u2192 ${n.slice(0,200)}`,toolName:t,toolInput:r,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async e=>{let t=e.compact_summary;if(!t)return{};try{let{createMemory:r}=await import("./memories-EFQ4SFZG.js");r({id:`compact-${Date.now()}`,roleId:o.roleId??"role-chat-manager",type:"thought",content:t.slice(0,2e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}function Nt(o){return`# ChatManager \u2014 User Interface Agent
51
7
 
52
8
  You are the primary interface between the user and the goal-driven autonomous system.
53
9
  You have access to a persistent conversation session and the adam-tools MCP server.
@@ -78,14 +34,27 @@ When the user asks what you can do or asks for help, call **get_capabilities** t
78
34
  ## Current Context
79
35
  - Time: ${new Date(o.currentTime).toISOString()}
80
36
 
37
+ ## Session Context
38
+ When the prompt includes a [Session context] section, it contains recent conversation turns
39
+ retrieved from the database. This may overlap with your SDK session memory \u2014 in case of
40
+ conflict, treat the [Session context] as authoritative (it reflects the latest DB state).
41
+
42
+ ## CRITICAL: No Hallucinated Confirmations
43
+ - **NEVER claim an operation succeeded unless you just called the corresponding tool and it returned success.**
44
+ - When the user asks you to do something (dispatch task, schedule, create template, send message, create role, etc.), you MUST call the tool FIRST, then confirm based on the tool's return value.
45
+ - If you cannot call the tool (missing parameters, unclear intent), ASK the user for clarification. Do not fabricate a success message.
46
+ - Saying "\u5DF2\u8BBE\u7F6E", "\u5DF2\u521B\u5EFA", "\u5DF2\u53D1\u9001", "done", "completed" without a preceding successful tool call is FORBIDDEN.
47
+ - This rule has NO exceptions. Even if you are confident about what to do, call the tool first, confirm after.
48
+
81
49
  ## Decision Principles
82
50
  - Answer simple questions directly from state (no task needed)
83
51
  - For ANY work request that needs external data (weather, news, web content, file operations, code execution): ALWAYS use dispatch_task. Do NOT tell the user "I can't do this" \u2014 dispatch_task delegates to workers that CAN do it.
84
52
  - Never block waiting for task completion \u2014 respond immediately and update later
85
- - When a task completes, the system will inject the result into your session context
53
+ - When the system injects a [System] task lifecycle message, compose a natural response in the user's language. Do NOT call send_to_channel \u2014 the platform handles delivery automatically.
54
+ - Task lifecycle messages include: task started, approval needed, task completed, task failed. Respond naturally to each (e.g., "\u5929\u6C14\u67E5\u8BE2\u4EFB\u52A1\u5DF2\u542F\u52A8" / "\u4EFB\u52A1\u9700\u8981\u4F60\u7684\u6388\u6743" / "\u67E5\u8BE2\u5B8C\u6210\uFF0C\u7ED3\u679C\u5982\u4E0B").
55
+ - Task completion delivery is automatic: reportTo targets receive your composed status message; deliverTo targets receive the full result. Do NOT call send_to_channel for task lifecycle events.
86
56
  - NEVER say "I don't have the ability to..." \u2014 use dispatch_task instead. The workers have WebSearch, WebFetch, Bash, and all standard tools.
87
- - When a task completes and the user previously asked to send results to a channel \u2192 use send_to_channel(channelName, result) to deliver
88
- - **Role selection**: Before dispatching, call list_roles to discover available roles and their capabilities (allowedTools). Pass the matching role's id as roleId to dispatch_task. Never dispatch without a roleId unless no role matches the task.
57
+ - **Role selection**: Before dispatching, call list_roles to discover available roles and their full capabilities (allowedTools, plugins with skills/agents). Match the task to the role whose plugin skills best fit the work. Pass the matching role's id as roleId to dispatch_task. Never dispatch without a roleId unless no role matches the task.
89
58
 
90
59
  ## Decision Patterns
91
60
  - Simple task request \u2192 list_roles \u2192 pick best role \u2192 dispatch_task with roleId
@@ -94,20 +63,29 @@ When the user asks what you can do or asks for help, call **get_capabilities** t
94
63
  - One-shot delayed request ("\u534A\u5C0F\u65F6\u540E", "in 30 minutes", "\u660E\u59293\u70B9") \u2192 schedule_task
95
64
  - Check system capacity \u2192 get_system_status
96
65
  - Send to channel \u2192 list_channels to find target \u2192 send_to_channel
97
- - Deliver task output to a specific channel \u2192 pass deliverTo in dispatch_task or schedule_task (use list_channels to get channel info)
98
- - Send status report to a different channel than output \u2192 pass reportTo (defaults to originating channel/session if omitted)
66
+ - Deliver task result to a specific recipient: pass deliverTo in dispatch_task or schedule_task.
67
+ - Send status notification to task requester: pass reportTo (defaults to originating channel/session if omitted).
68
+ - reportTo and deliverTo serve different purposes: reportTo = status ("task completed"); deliverTo = output (result details, file locations, etc.)
69
+ - Both can target the same channel. When they do, the recipient gets two distinct messages: one status update and one result delivery.
70
+ - **Task completion delivery is automatic**: When a task completes, the platform automatically delivers reportTo (status) and deliverTo (result) messages to the configured targets. The originating channel receives a status notification by default. Do NOT call send_to_channel to deliver task results \u2014 this causes duplicate messages. Only use send_to_channel for ad-hoc messages unrelated to task completion.
99
71
  - Check goal/task progress \u2192 list_goals / read_task_status
100
72
  - **Create new role**: When the user asks to create a role with specific capabilities (e.g., "\u80FD\u8BBF\u95EE\u7F51\u7EDC"), pass the required tools in allowedTools (e.g., ["WebSearch", "WebFetch"]). Without allowedTools, the role has no tool permissions and cannot execute tasks that need those tools.
101
73
 
102
74
  ## Conversation Coherence
103
75
  When task completion notifications arrive, incorporate the results naturally into your conversation.
104
76
  For example, if the user asked "run a report" and Task xyz completed, summarize the result for the user.
105
- `}me();var F=E("chat-manager"),ea=q,Ee=class{sessionId;adamToolsInstance=null;running=!1;processing=!1;messageQueue=[];lastActivityAt=Date.now();consecutiveStaleCount=0;subscribed=!1;activeChatSessionId;activeChatSource;taskOriginMap=new Map;taskNotifyMap=new Map;constructor(e){this.sessionId=e}async start(){this.running||(this.running=!0,this.subscribeToEvents(),F.info("ChatManager started"))}stop(){this.running=!1,F.info("ChatManager stopped")}async handleMessage(e,t,s){return new Promise((r,n)=>{this.messageQueue.push({content:e,resolve:a=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,r(a)},reject:a=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,n(a)}}),this.activeChatSessionId=t,this.activeChatSource=s,this.processQueue()})}async processQueue(){if(this.processing||!this.running)return;let e=this.messageQueue.shift();if(e){this.processing=!0;try{let t=await this.runQuery(e.content);e.resolve(t)}catch(t){e.reject(t instanceof Error?t:new Error(String(t)))}finally{this.processing=!1,this.processQueue()}}}async runQuery(e){let t=Mt({currentTime:Date.now()});this.adamToolsInstance||(this.adamToolsInstance=Ct());let s=Ae({currentTaskId:void 0,roleId:"role-chat-manager"}),r=_e(d=>({disallowedTools:["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"]}));F.debug({hasApiKey:!!process.env.ANTHROPIC_API_KEY,hasResume:!!this.sessionId},"ChatManager SDK query starting");let n=["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"],a=Zn({prompt:e,options:{cwd:ea,additionalDirectories:[process.cwd()],systemPrompt:t,resume:this.sessionId,maxTurns:50,maxBudgetUsd:5,disallowedTools:n,settingSources:["project"],mcpServers:{"adam-tools":this.adamToolsInstance},hooks:s,canUseTool:r,env:{...process.env,DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1",DISABLE_AUTO_COMPACT:"1",DISABLE_COMPACT:"1",ANTHROPIC_SMALL_FAST_MODEL:process.env.ANTHROPIC_MODEL??""},stderr:d=>{d.trim()&&F.debug({stderr:d.trim().slice(0,500)},"ChatManager SDK stderr")}}}),i="";for await(let d of a){let c=d;F.debug({eventType:c.type,subtype:c.subtype},"ChatManager SDK event"),this.lastActivityAt=Date.now(),this.consecutiveStaleCount=0,c.session_id&&typeof c.session_id=="string"&&(this.sessionId=c.session_id,Dt(this.sessionId)),c.type==="result"&&typeof c.result=="string"&&(i=c.result)}return i}subscribeToEvents(){this.subscribed||(this.subscribed=!0,g.on("task_created",e=>{this.activeChatSessionId&&this.activeChatSource&&($(e.taskId,{sourceSessionId:this.activeChatSessionId}),this.taskOriginMap.set(e.taskId,{chatSessionId:this.activeChatSessionId,source:this.activeChatSource,createdAt:Date.now()}),F.debug({taskId:e.taskId,chatSessionId:this.activeChatSessionId},"Tracked task origin for result delivery"));let t=A(e.taskId);if(t?.parentId){let s=this.taskOriginMap.get(t.parentId),r=s?void 0:A(t.parentId),n=s?.chatSessionId??r?.sourceSessionId;n&&($(e.taskId,{sourceSessionId:n}),s&&this.taskOriginMap.set(e.taskId,{...s}))}}),g.on("task_complete_event",e=>{this.handleTaskCompletion(e.taskId,e.result,e.error)}),setInterval(()=>{let e=Date.now()-864e5;for(let[t,s]of this.taskOriginMap)s.createdAt<e&&this.taskOriginMap.delete(t)},3600*1e3))}async handleTaskCompletion(e,t,s){let r=A(e),n=this.taskOriginMap.get(e);if(!n&&r?.sourceSessionId){let u=H(r.sourceSessionId);u&&(n={chatSessionId:u.id,source:u.source,createdAt:r.createdAt})}let a=r?.roleId?await this.getRoleName(r.roleId):void 0,i=a?`${a}`:e.slice(0,8),d=s?"\u274C":"\u2705",c=s?`\u4EFB\u52A1\u5931\u8D25: ${s.slice(0,200)}`:(t??"").slice(0,500),l=`${d} \u4EFB\u52A1\u5B8C\u6210 (${i})
77
+ `}function To(o){return o.map(e=>`${e.role==="user"?"User":"Assistant"}: ${e.content}`).join(`
78
+ `)}function wo(o){return o.map(e=>`Memory [${e.tier??"episodic"}]: ${e.content} (importance: ${e.importance})`).join(`
79
+ `)}async function nn(o,e){let t=ns(),r=bs(o,t.maxSessionTurns),s=To(r),n="";try{let i=await Fs(void 0,e,["semantic","working"],{topK:5});i.length>0&&(n=wo(i))}catch{}let a=[];return s&&a.push(`[Session context \u2014 last ${t.maxSessionTurns} turns]
80
+ ${s}`),n&&a.push(`[Relevant memories \u2014 from Memory system]
81
+ ${n}`),a.push(`[Current message]
82
+ User: ${e}`),a.join(`
83
+
84
+ `)}de();var F=O("chat-manager"),Co=A,_e=class{sessionId;adamToolsInstance=null;running=!1;processing=!1;messageQueue=[];lastActivityAt=Date.now();consecutiveStaleCount=0;subscribed=!1;activeChatSessionId;activeChatSource;taskOriginMap=new Map;constructor(e){this.sessionId=e}async start(){this.running||(this.running=!0,this.subscribeToEvents(),F.info("ChatManager started"))}stop(){this.running=!1,F.info("ChatManager stopped")}async handleMessage(e,t,r){return new Promise((s,n)=>{let a=t;this.messageQueue.push({content:e,chatSessionId:a,resolve:i=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,s(i)},reject:i=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,n(i)}}),this.activeChatSessionId=t,this.activeChatSource=r,this.processQueue()})}async processQueue(){if(this.processing||!this.running)return;let e=this.messageQueue.shift();if(e){this.processing=!0;try{let t=await this.runQuery(e.content,e.chatSessionId);e.resolve(t)}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("Prompt is too long")||r.includes("prompt is too long")){F.warn("Prompt too long \u2014 resetting session and retrying"),this.sessionId=void 0,ze(void 0);try{let s=await this.runQuery(e.content,e.chatSessionId);e.resolve(s)}catch(s){e.reject(s instanceof Error?s:new Error(String(s)))}}else e.reject(t instanceof Error?t:new Error(r))}finally{this.processing=!1,this.processQueue()}}}async runQuery(e,t){let r=Nt({currentTime:Date.now()}),s=e;if(t)try{let d=await nn(t,e);d&&d!==e&&(s=d)}catch(d){F.debug({error:d},"Session context enrichment failed, using raw message")}this.adamToolsInstance||(this.adamToolsInstance=Ct());let n=Pe({currentTaskId:void 0,roleId:"role-chat-manager"}),a=Ce(d=>({disallowedTools:["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"]}));F.debug({hasApiKey:!!process.env.ANTHROPIC_API_KEY,hasResume:!!this.sessionId},"ChatManager SDK query starting");let i=["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"],c=So({prompt:s,options:{cwd:Co,additionalDirectories:[process.cwd()],systemPrompt:r,resume:this.sessionId,maxTurns:50,maxBudgetUsd:5,disallowedTools:i,settingSources:["project"],mcpServers:{"adam-tools":this.adamToolsInstance},hooks:n,canUseTool:a,env:{...process.env,...Le(),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1",ANTHROPIC_SMALL_FAST_MODEL:U().anthropic?.smallFastModel||process.env.ANTHROPIC_MODEL||""},stderr:d=>{d.trim()&&F.debug({stderr:d.trim().slice(0,500)},"ChatManager SDK stderr")}}}),l="";for await(let d of c){let m=d;F.debug({eventType:m.type,subtype:m.subtype},"ChatManager SDK event"),this.lastActivityAt=Date.now(),this.consecutiveStaleCount=0,m.session_id&&typeof m.session_id=="string"&&(this.sessionId=m.session_id,ze(this.sessionId)),m.type==="result"&&typeof m.result=="string"&&(l=m.result)}return l}subscribeToEvents(){this.subscribed||(this.subscribed=!0,f.on("task_created",e=>{this.activeChatSessionId&&this.activeChatSource&&(G(e.taskId,{sourceSessionId:this.activeChatSessionId}),this.taskOriginMap.set(e.taskId,{chatSessionId:this.activeChatSessionId,source:this.activeChatSource,createdAt:Date.now()}),F.debug({taskId:e.taskId,chatSessionId:this.activeChatSessionId},"Tracked task origin for result delivery"));let t=D(e.taskId);if(t?.parentId){let r=this.taskOriginMap.get(t.parentId),s=r?void 0:D(t.parentId),n=r?.chatSessionId??s?.sourceSessionId;n&&(G(e.taskId,{sourceSessionId:n}),r&&this.taskOriginMap.set(e.taskId,{...r}))}}),f.on("task_complete_event",e=>{this.handleTaskCompletion(e.taskId,e.result,e.error)}),f.on("task_status_change",e=>{let t=this.taskOriginMap.get(e.taskId);t&&e.newStatus==="running"&&this.handleTaskStatusReport(e.taskId,e.newStatus,t)}),f.on("plan_approval_request",e=>{let t=this.taskOriginMap.get(e.taskId);t&&this.handleTaskStatusReport(e.taskId,"approval_requested",t)}),setInterval(()=>{let e=Date.now()-864e5;for(let[t,r]of this.taskOriginMap)r.createdAt<e&&this.taskOriginMap.delete(t)},3600*1e3))}async handleTaskStatusReport(e,t,r){let s=D(e),a=(s?.roleId?await this.getRoleName(s.roleId):void 0)??e.slice(0,8),i=s?.prompt?.slice(0,200)??"",c;switch(t){case"running":c=`[System] Task "${a}" has started execution. Task prompt: "${i}". Compose a brief, natural status message for the user (1-2 sentences in the user's language). Do NOT call any tools \u2014 just output the message text.`;break;case"approval_requested":c=`[System] Task "${a}" needs user approval (privilege escalation). The approval request has been sent separately. Compose a brief notice for the user (1 sentence). Do NOT call any tools.`;break;default:return}let l={running:`\u4EFB\u52A1 ${a} \u5DF2\u542F\u52A8`,approval_requested:`\u4EFB\u52A1 ${a} \u9700\u8981\u6388\u6743`},d=!1,m=setTimeout(()=>{if(d)return;d=!0;let h=l[t]??`\u4EFB\u52A1 ${a}: ${t}`;this.deliverReport(r,e,h)},3e4);this.messageQueue.push({content:c,resolve:h=>{if(d)return;d=!0,clearTimeout(m);let I=h?.trim()||(l[t]??`\u4EFB\u52A1 ${a}: ${t}`);this.deliverReport(r,e,I)},reject:()=>{if(d)return;d=!0,clearTimeout(m);let h=l[t]??`\u4EFB\u52A1 ${a}: ${t}`;this.deliverReport(r,e,h)}}),this.processQueue()}deliverReport(e,t,r){let s={id:ue(),sessionId:e.chatSessionId,role:"assistant",content:r,source:e.source,taskId:t,createdAt:Date.now()};te(s),f.emit({type:"chat_message",sessionId:e.chatSessionId,message:s}),se(e.chatSessionId),e.source.type==="channel"&&e.source.channelId&&e.source.chatId&&this.deliverToChannel(e.source.channelId,e.source.chatId,r,"report")}async handleTaskCompletion(e,t,r){let s=D(e),n=this.taskOriginMap.get(e);if(!n&&s?.sourceSessionId){let y=H(s.sourceSessionId);y&&(n={chatSessionId:y.id,source:y.source,createdAt:s.createdAt})}let a=r?`\u4EFB\u52A1\u5931\u8D25: ${r}`:t??"",i=async(y,g)=>{try{let C=H(y);if(!C)return;te({id:ue(),sessionId:y,role:"assistant",content:g,source:C.source,taskId:e,createdAt:Date.now()}),se(y),f.emit({type:"chat_message",sessionId:y,message:{id:ue(),sessionId:y,role:"assistant",content:g,source:C.source,createdAt:Date.now()}})}catch(C){F.error({error:C,taskId:e,targetSession:y},"Failed to deliver to session")}},c=s?.roleId?await this.getRoleName(s.roleId):void 0,l=c?`${c}`:e.slice(0,8),d=r?`[System] Task "${l}" failed. Error: ${r.slice(0,300)}. Compose a brief failure report for the user (2-3 sentences). Do NOT call any tools.`:`[System] Task "${l}" completed successfully. Result summary: ${(t??"").slice(0,500)}. Compose a brief completion report for the user (2-3 sentences, highlight key outcomes). Do NOT call any tools.`,m={success:`\u4EFB\u52A1\u5B8C\u6210 (${l})`,error:`\u4EFB\u52A1\u5931\u8D25 (${l})`},h=!1,I=setTimeout(()=>{if(h)return;h=!0;let y=r?m.error:m.success;if(n&&this.deliverReport(n,e,y),s?.reportTo&&s.reportTo.length>0)for(let g of s.reportTo)g.type==="channel"&&g.channelId&&g.chatId?this.deliverToChannel(g.channelId,g.chatId,y,"report"):g.type==="session"&&g.sessionId&&i(g.sessionId,y)},3e4);if(this.messageQueue.push({content:d,resolve:y=>{if(h)return;h=!0,clearTimeout(I);let g=y?.trim()||(r?m.error:m.success);if(n&&this.deliverReport(n,e,g),s?.reportTo&&s.reportTo.length>0)for(let C of s.reportTo)C.type==="channel"&&C.channelId&&C.chatId?this.deliverToChannel(C.channelId,C.chatId,g,"report"):C.type==="session"&&C.sessionId&&i(C.sessionId,g);n&&this.taskOriginMap.delete(e)},reject:()=>{if(h)return;h=!0,clearTimeout(I);let y=r?m.error:m.success;if(n&&this.deliverReport(n,e,y),s?.reportTo&&s.reportTo.length>0)for(let g of s.reportTo)g.type==="channel"&&g.channelId&&g.chatId?this.deliverToChannel(g.channelId,g.chatId,y,"report"):g.type==="session"&&g.sessionId&&i(g.sessionId,y);n&&this.taskOriginMap.delete(e)}}),this.processQueue(),n||F.debug({taskId:e},"Task completed but no chat session origin tracked (may be API-created or template-triggered)"),s?.deliverTo&&s.deliverTo.length>0)for(let y of s.deliverTo)y.type==="channel"&&y.channelId&&y.chatId?this.deliverToChannel(y.channelId,y.chatId,a,"deliver"):y.type==="session"&&y.sessionId&&await i(y.sessionId,a);else if(n?.source.type==="channel"&&n.source.channelId&&n.source.chatId){let g=a.length>2e3?a.slice(0,2e3)+`
106
85
 
107
- ${c}`;if(this.sessionId){let u=`[System notification] Task ${e} ${s?"failed":"completed"}. Result:
108
- ${(s??t??"").slice(0,500)}`;this.messageQueue.push({content:u,resolve:y=>{if(y&&y.trim()&&n){let w={id:ne(),sessionId:n.chatSessionId,role:"assistant",content:y,source:n.source,taskId:e,createdAt:Date.now()};X(w),g.emit({type:"chat_message",sessionId:n.chatSessionId,message:w}),Z(n.chatSessionId)}},reject:()=>{}}),this.processQueue()}if(n){let u={id:ne(),sessionId:n.chatSessionId,role:"assistant",content:l,source:n.source,taskId:e,createdAt:Date.now()};try{X(u),g.emit({type:"chat_message",sessionId:n.chatSessionId,message:u}),Z(n.chatSessionId),Se(n.chatSessionId),F.info({taskId:e,chatSessionId:n.chatSessionId,sourceType:n.source.type},"Task result delivered to chat session"),n.source.type==="channel"&&n.source.channelId&&n.source.chatId&&this.deliverToChannel(n.source.channelId,n.source.chatId,l)}catch(y){F.error({error:y,taskId:e},"Failed to deliver task result to chat session")}this.taskOriginMap.delete(e)}else F.debug({taskId:e},"Task completed but no chat session origin tracked (may be API-created or template-triggered)");let b=async(u,y)=>{try{let w=H(u);if(!w)return;X({id:ne(),sessionId:u,role:"assistant",content:y,source:w.source,taskId:e,createdAt:Date.now()}),Z(u),g.emit({type:"chat_message",sessionId:u,message:{id:ne(),sessionId:u,role:"assistant",content:y,source:w.source,createdAt:Date.now()}})}catch(w){F.error({error:w,taskId:e,targetSession:u},"Failed to deliver to session")}};if(r?.reportTo&&r.reportTo.length>0)for(let u of r.reportTo)u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,l):u.type==="session"&&u.sessionId&&await b(u.sessionId,l);else n?.source.type==="channel"&&n.source.channelId&&n.source.chatId&&this.deliverToChannel(n.source.channelId,n.source.chatId,l);if(r?.deliverTo&&r.deliverTo.length>0)for(let u of r.deliverTo){let y=s?`\u4EFB\u52A1\u5931\u8D25: ${(s??"").slice(0,200)}`:t??"";u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,y):u.type==="session"&&u.sessionId&&await b(u.sessionId,y)}if(!r?.deliverTo&&r?.notifyTargets&&r.notifyTargets.length>0)for(let u of r.notifyTargets)u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,l):u.type==="session"&&u.sessionId&&await b(u.sessionId,l);if(r?.parentId){let u=re(r.parentId);if(u){let y=Xt(r.parentId);if(y.every(v=>v.status==="completed"||v.status==="failed")){let v=y.some(te=>te.status==="failed"),W=v?"failed":"completed";Ge(r.parentId,{status:W,updatedAt:Date.now()}),F.info({goalId:r.parentId,goalName:u.name,finalStatus:W},"Goal completed");let T=`${v?"\u274C":"\u2705"} \u76EE\u6807\u5B8C\u6210: ${u.name}
86
+ ... \u67E5\u770B\u5B8C\u6574\u7ED3\u679C\u8BF7\u8BBF\u95EE Web UI`:a;this.deliverToChannel(n.source.channelId,n.source.chatId,g,"deliver")}if(s?.parentId){let y=le(s.parentId);if(y){let g=os(s.parentId);if(g.every(W=>W.status==="completed"||W.status==="failed")){let W=g.some(ae=>ae.status==="failed"),oe=W?"failed":"completed";Ue(s.parentId,{status:oe,updatedAt:Date.now()}),F.info({goalId:s.parentId,goalName:y.name,finalStatus:oe},"Goal completed");let $=`${W?"\u274C":"\u2705"} \u76EE\u6807\u5B8C\u6210: ${y.name}
109
87
 
110
- ${y.length} \u4E2A\u5B50\u4EFB\u52A1\u5168\u90E8\u5B8C\u6210`;await this.routeGoalNotification(u,T,r.parentId)}}}}async getRoleName(e){try{let{getRole:t}=await import("./roles-CMV5FMIA.js");return t(e)?.name}catch{return}}async deliverToChannel(e,t,s){if(!e||!t){F.warn({channelId:e,chatId:t},"Cannot deliver to channel: missing channelId or chatId");return}try{let{getChannelManager:r}=await import("./channels-CNLMTKHM.js"),n=r();n&&(await n.sendMessage(e,t,{content:s}),F.info({channelId:e,chatId:t.slice(0,12)},"Delivered notification to channel"))}catch(r){F.error({error:r,channelId:e,chatId:t.slice(0,12)},"Failed to deliver to channel")}}async routeGoalNotification(e,t,s){let r=e.deliverTo??e.notifyTargets??[],n=e.sourceSessionId;if(!(r.length===0&&!n)){for(let a of r)if(a.type==="session")try{let i=H(a.sessionId);i&&(X({id:ne(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}),Z(a.sessionId),g.emit({type:"chat_message",sessionId:a.sessionId,message:{id:ne(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}}))}catch(i){F.error({error:i,goalId:s,targetSession:a.sessionId},"Failed to deliver Goal notification to session")}else a.type==="channel"&&await this.deliverToChannel(a.channelId,a.chatId??"",t);if(n&&!r.some(a=>a.type==="session"&&a.sessionId===n))try{let a=H(n);a&&(X({id:ne(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}),Z(n),g.emit({type:"chat_message",sessionId:n,message:{id:ne(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}}))}catch(a){F.error({error:a,goalId:s,sessionId:n},"Failed to deliver Goal notification to source session")}}}getLastActivityAt(){return this.lastActivityAt}getConsecutiveStaleCount(){return this.consecutiveStaleCount}isHealthy(){return this.running}async restartSession(){F.warn("Restarting ChatManager session (Watchdog triggered)"),this.consecutiveStaleCount++,this.sessionId=void 0,Dt(void 0)}};import{query as na}from"@anthropic-ai/claude-agent-sdk";import{v4 as aa}from"uuid";function jt(o){let e=o.roleName?`## Role Context
88
+ ${g.length} \u4E2A\u5B50\u4EFB\u52A1\u5168\u90E8\u5B8C\u6210`;await this.routeGoalNotification(y,$,s.parentId)}}}}async getRoleName(e){try{let{getRole:t}=await import("./roles-SG2YAR64.js");return t(e)?.name}catch{return}}async deliverToChannel(e,t,r,s="reply"){if(!e||!t){F.warn({channelId:e,chatId:t},"Cannot deliver to channel: missing channelId or chatId");return}try{await Rr().send({channelId:e,chatId:t,content:r,messageType:s}),F.info({channelId:e,chatId:t.slice(0,12),messageType:s},"Delivered notification to channel")}catch(n){F.error({error:n,channelId:e,chatId:t.slice(0,12)},"Failed to deliver to channel")}}async routeGoalNotification(e,t,r){let s=e.deliverTo??[],n=e.sourceSessionId;if(!(s.length===0&&!n)){for(let a of s)if(a.type==="session")try{let i=H(a.sessionId);i&&(te({id:ue(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}),se(a.sessionId),f.emit({type:"chat_message",sessionId:a.sessionId,message:{id:ue(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}}))}catch(i){F.error({error:i,goalId:r,targetSession:a.sessionId},"Failed to deliver Goal notification to session")}else a.type==="channel"&&await this.deliverToChannel(a.channelId,a.chatId??"",t);if(n&&!s.some(a=>a.type==="session"&&a.sessionId===n))try{let a=H(n);a&&(te({id:ue(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}),se(n),f.emit({type:"chat_message",sessionId:n,message:{id:ue(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}}))}catch(a){F.error({error:a,goalId:r,sessionId:n},"Failed to deliver Goal notification to source session")}}}getLastActivityAt(){return this.lastActivityAt}getConsecutiveStaleCount(){return this.consecutiveStaleCount}isHealthy(){return this.running}async restartSession(){F.warn("Restarting ChatManager session (Watchdog triggered)"),this.consecutiveStaleCount++,this.sessionId=void 0,ze(void 0)}};import{query as Eo}from"@anthropic-ai/claude-agent-sdk";import{v4 as xo}from"uuid";function Lt(o){let e=o.roleName?`## Role Context
111
89
  - Role: ${o.roleName}
112
90
  ${o.roleCagPrompt?`- CAG Prompt: ${o.roleCagPrompt.slice(0,200)}`:""}`:"",t=o.allowedTools&&o.allowedTools.length>0?`## Available Tools
113
91
  You have access to: ${o.allowedTools.join(", ")}. Use them as needed to complete the task.`:"";return`# Execution Agent \u2014 Task Focus
@@ -133,20 +111,20 @@ ${t}
133
111
  - Report completion with a clear result summary
134
112
  - If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
135
113
  - If a tool is unavailable, state it clearly in the result rather than guessing
136
- `}ie();kt();me();ke();import{randomUUID as ta}from"crypto";function Mr(o,e,t){let r=j().prepare(`
114
+ `}he();vt();de();ke();import{randomUUID as Po}from"crypto";function an(o,e,t){let s=L().prepare(`
137
115
  INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
138
116
  VALUES (?, ?, ?, ?, ?, ?)
139
- `),n=Date.now();for(let a of e){let i=a.split("/").pop()??a;r.run(ta(),o,a,i,t??null,n)}}function jr(o){return j().prepare(`
117
+ `),n=Date.now();for(let a of e){let i=a.split("/").pop()??a;s.run(Po(),o,a,i,t??null,n)}}function cn(o){return L().prepare(`
140
118
  SELECT plugin_name as pluginName, COUNT(*) as usageCount
141
119
  FROM task_plugins
142
120
  WHERE role_id = ?
143
121
  GROUP BY plugin_path
144
122
  ORDER BY usageCount DESC
145
- `).all(o)}function Nr(o=50){return j().prepare(`
123
+ `).all(o)}function dn(o=50){return L().prepare(`
146
124
  SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
147
125
  FROM task_plugins
148
126
  GROUP BY plugin_path
149
127
  ORDER BY usageCount DESC
150
128
  LIMIT ?
151
- `).all(o)}ie();import{createSdkMcpServer as sa,tool as Lr}from"@anthropic-ai/claude-agent-sdk";import{z as qr}from"zod";async function ra(o){let{listChannels:e}=await import("./channels-VNG7U6UQ.js"),t=e(),{listSessions:s}=await import("./session-manager-KO4CR3W6.js"),r=[...s("active"),...s("archived")],n=t.find(d=>d.name.toLowerCase().includes(o.toLowerCase()));if(!n)return null;let i=r.find(d=>d.source.type==="channel"&&d.source.channelId===n.id&&d.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:i}}function ve(o){return{content:[{type:"text",text:JSON.stringify(o)}]}}function Br(o){let e=o?B(o):void 0,t=[Lr("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:s}=await import("./channels-VNG7U6UQ.js"),r=s();return ve({channels:r.map(n=>({id:n.id,name:n.name,enabled:n.enabled,type:n.config?.type??"unknown"}))})}),Lr("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:qr.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:qr.string().describe("The message content to send")},async s=>{if(e?.allowedChannels!==void 0){if(e.allowedChannels.length===0)return ve({error:"This role is not allowed to send to any channels"});if(!e.allowedChannels.some(c=>c.toLowerCase()===s.channelName.toLowerCase()))return ve({error:`Channel "${s.channelName}" is not in the allowed channels list for this role`})}let r=await ra(s.channelName);if(!r)return ve({error:`Channel "${s.channelName}" not found or has no chatId available`});let{getChannelManager:n}=await import("./channels-CNLMTKHM.js"),a=n();if(!a)return ve({error:"ChannelManager not available"});let i=await a.sendMessage(r.channelId,r.chatId,{content:s.message});return ve({success:!!i,channelName:s.channelName})})];return sa({name:"execution-tools",version:"1.0.0",tools:t})}St();var J=E("execution"),xe=class{async execute(e,t){let s=Date.now(),r,n,a;$(e.id,{status:"running",startedAt:Date.now()}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),J.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let i=e.roleId?B(e.roleId):void 0,d=q;i&&(Te(i),d=se(i.name));let c={taskId:e.id,prompt:e.prompt,roleName:i?.name,roleCagPrompt:i?.cagPrompt,allowedTools:i?.allowedTools},l=jt(c),b=Ae({currentTaskId:e.id,roleId:e.roleId}),u=e.config.approvalTimeout??300,w=i?.preferences?.permissions,W=_e(P=>({allowedPaths:w?.allowedPaths,deniedPaths:w?.deniedPaths,disallowedTools:i?.disallowedTools,approvalRequired:i?.approvalRequired??e.config.approvalRequired}),async(P,x,V,Le)=>{let M=aa(),Gt=os(Le??e.roleId,e.prompt,"medium");if(Gt)return J.info({operationId:M,ruleId:Gt.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:x};let Vt={steps:[{index:0,description:`${P}: ${JSON.stringify(x).slice(0,300)}`,toolsNeeded:[P],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return rs({id:M,taskId:e.id,roleId:Le??e.roleId,plan:Vt,status:"pending",createdAt:Date.now()}),g.emit({type:"plan_approval_request",taskId:e.id,planId:M,plan:Vt}),J.info({taskId:e.id,operationId:M,toolName:P,matchedPattern:V},"Privilege escalation: awaiting user decision"),new Promise(lt=>{let nn=setTimeout(()=>{Ht(),as(M,"denied"),J.warn({taskId:e.id,operationId:M},"Privilege escalation timed out, auto-denied"),lt({behavior:"deny",message:`Operation timed out after ${u}s. Auto-denied. Try a safer alternative that does not require approval.`})},u*1e3),$t=ue=>{if(ue.planId===M)if(Ht(),ue.decision==="allow")J.info({taskId:e.id,operationId:M,approvalType:ue.approvalType},"Operation authorized by user"),lt({behavior:"allow",updatedInput:x});else{let an=ue.reason?`Operation denied by user: ${ue.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";J.info({taskId:e.id,operationId:M,reason:ue.reason??"no reason given"},"Operation denied by user"),lt({behavior:"deny",message:an})}},Ht=()=>{clearTimeout(nn),g.off("plan_approval_decision",$t)};g.on("plan_approval_decision",$t)})}),T={...process.env,DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1",DISABLE_AUTO_COMPACT:"1",DISABLE_COMPACT:"1"},te=e.config.maxBudgetUsd??5,Q=e.config.maxTurns??100,Me=Br(e.roleId??""),ce=i?.mcpServers??{},it=e.config.mcpServers??{},je={...ce,...it,"execution-tools":Me},f=[],G=i?.additionalDirectories??[];for(let P of G){let x=Ue(P.path);if(P.inheritPlugins||P.inheritMcp){let V=Object.entries(x.enabledPlugins).filter(([,M])=>M).map(([M])=>M),Le=gs(V);for(let[,M]of Le)f.includes(M)||f.push(M)}P.inheritPermissions}if(i){let P=fe({scope:"project",projectPath:d});for(let x of P)x.installPath&&!f.includes(x.installPath)&&f.push(x.installPath)}let le=[e.config.workspacePath??process.cwd(),...G.map(P=>P.path)].filter((P,x,V)=>V.indexOf(P)===x),Ie=na({prompt:e.prompt,options:{cwd:d,additionalDirectories:le,systemPrompt:l,maxTurns:Q,maxBudgetUsd:te,allowedTools:i?.allowedTools,model:i?.model,mcpServers:je,settingSources:i?.inheritUserSettings?["project","user"]:["project"],hooks:b,canUseTool:W,env:T,plugins:f.map(P=>({type:"local",path:P})),stderr:P=>{P.trim()&&J.debug({stderr:P.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),pe="",dt=0,Ne=()=>{J.warn({taskId:e.id},"ExecutionManager: abort signal received")};t&&t.addEventListener("abort",Ne);try{for await(let P of Ie){let x=P;if(J.debug({eventType:x.type,taskId:e.id},"ExecutionManager SDK event"),x.type==="result"&&typeof x.result=="string"&&(pe=x.result),x.type==="result"&&dt++,x.token_usage){let V=x.token_usage;V.input_tokens!==void 0&&V.output_tokens!==void 0&&(r={input:V.input_tokens,output:V.output_tokens}),V.cost_usd!==void 0&&(n=V.cost_usd)}}}finally{t&&t.removeEventListener("abort",Ne)}a=dt;let ct=Date.now()-s;return $(e.id,{status:"completed",result:pe,completedAt:Date.now(),costUsd:n,tokenUsage:r,numTurns:a,totalDurationMs:ct}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),g.emit({type:"task_complete_event",taskId:e.id,result:pe}),f.length>0&&Mr(e.id,f,e.roleId),J.info({taskId:e.id,durationMs:ct,costUsd:n},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:pe,costUsd:n,tokenUsage:r,numTurns:a,durationMs:ct}}catch(i){let d=i instanceof Error?i.message:String(i),c=Date.now()-s;return $(e.id,{status:"failed",error:d,completedAt:Date.now(),totalDurationMs:c}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),g.emit({type:"task_complete_event",taskId:e.id,error:d}),J.error({taskId:e.id,error:i},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:d,durationMs:c}}}};var de=E("execution-pool"),De=class{slots;running=!1;pollTimeoutId=null;executor;constructor(e,t){this.slots=Array.from({length:e},(s,r)=>({index:r,taskId:null,abortController:null})),this.executor=t??new xe}async start(){if(this.running)return;this.running=!0,g.on("task_created",s=>{this.onTaskCreated(s.taskId)}),g.on("task_status_change",s=>{s.newStatus==="pending"&&this.pickupPendingTasks()});let t=Y().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t),de.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let e of this.slots)e.abortController&&(e.abortController.abort(),e.taskId=null,e.abortController=null);de.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let t=Y().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t)};async onTaskCreated(e){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let e=this.slots.find(i=>i.taskId===null);if(!e){de.debug("No free slots available");return}let t=N("pending");if(t.length===0)return;let r=[...t].sort((i,d)=>i.createdAt-d.createdAt)[0];e.taskId=r.id,e.abortController=new AbortController;let n=e.index,a=r.id;de.info({slotIndex:n,taskId:a},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(r,n).catch(i=>{de.error({taskId:a,error:i},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(e,t){let s=this.slots[t];if(!s)return;let r="completed";try{g.emit({type:"execution_task_start",taskId:e.id,slotIndex:t});let n=await this.executor.execute(e,s.abortController?.signal);r=n.status,de.info({taskId:e.id,status:n.status,slotIndex:t},"ExecutionPool: task finished")}finally{s.taskId=null,s.abortController=null,g.emit({type:"execution_task_end",taskId:e.id,slotIndex:t,status:r}),this.emitSlotChange(),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(s=>s.taskId!==null).length,t=N("pending");g.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:t.length})}getStatus(){let e=this.slots.filter(s=>s.taskId!==null).length,t=N("pending");return{active:e,max:this.slots.length,queued:t.length}}isHealthy(){return this.running}releaseSlot(e){let t=this.slots.find(s=>s.taskId===e);t&&(de.warn({taskId:e,slotIndex:t.index},"ExecutionPool: force-releasing slot"),t.abortController&&t.abortController.abort(),t.taskId=null,t.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};import{v4 as Nt}from"uuid";async function oa(o,e){if(!(await import("./config-42ZJPZDM.js").then(r=>r.getChatConfig())).autoTitle)return;let s=["Generate a very short title (max 50 characters) for a chat session that started with this message:",`"${e.slice(0,200)}"`,"Respond with only the title, no quotes or explanation."].join(`
152
- `);try{let n=(await Os(s,"You are a concise title generator. Reply with only the title, max 50 characters.")).trim().slice(0,50);n.length>0&&ps(o,{title:n})}catch{}}var Lt=null;function Ur(o){Lt=o}async function et(o,e,t,s){let r;s&&(r=H(s)),r||(r=Ps(e)),r||(r=$e(e,t));let n=Nt(),a={id:n,sessionId:r.id,role:"user",content:o,source:e,createdAt:Date.now()};if(X(a),g.emit({type:"chat_message",sessionId:r.id,message:a}),r.messageCount===0&&oa(r.id,o),Z(r.id),Se(r.id),Lt){let i=r.id,d=r.source;(async()=>{try{let c=await Lt.handleMessage(o,i,e),l={id:Nt(),sessionId:i,role:"assistant",content:c,source:e,createdAt:Date.now()};X(l),g.emit({type:"chat_message",sessionId:i,message:l}),Z(i),Se(i),d.type==="channel"&&d.channelId&&d.chatId&&ia(d.channelId,d.chatId,c)}catch(c){(await import("./logger-BEG4WFIM.js")).getLogger("message-handler").error({error:c,sessionId:i},"ChatManager response failed");let b={id:Nt(),sessionId:i,role:"assistant",content:`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${c instanceof Error?c.message:String(c)}`,source:e,createdAt:Date.now()};X(b),g.emit({type:"chat_message",sessionId:i,message:b}),Z(i)}})()}return{sessionId:r.id,messageId:n}}async function ia(o,e,t){try{let{getChannelManager:s}=await import("./channels-CNLMTKHM.js"),r=s();r&&await r.sendMessage(o,e,{content:t})}catch{}}import{z as h}from"zod/v4";import{v4 as da}from"uuid";var Wr=h.union([h.object({type:h.literal("session"),sessionId:h.string()}),h.object({type:h.literal("channel"),channelId:h.string(),chatId:h.string().optional()})]),ca=h.object({id:h.string(),prompt:h.string(),dependsOn:h.array(h.string()).optional(),outputAs:h.string().optional()}),la=h.object({type:h.enum(["cron","manual","event"]),cron:h.string().optional(),event:h.string().optional()}),qt=h.object({name:h.string().min(1),description:h.string().optional(),trigger:la,steps:h.array(ca).min(1),rolePreference:h.string().optional(),config:h.record(h.string(),h.unknown()).optional(),enabled:h.boolean().default(!0),goalIds:h.array(h.string()).optional(),notifyTargets:h.array(Wr).optional(),deliverTo:h.array(Wr).optional()}),Md=qt.transform(o=>({...o,notifyTargets:o.notifyTargets,deliverTo:o.deliverTo})),pa=qt.partial().transform(o=>({...o,notifyTargets:o.notifyTargets,deliverTo:o.deliverTo})),tt=h.object({id:h.string().min(1)});async function Gr(o,e){o.post("/task-templates",{schema:{tags:["Templates"],summary:"Create a task template",description:"Create a new task template with trigger (cron/manual/event) and execution steps. Cron-triggered templates are automatically scheduled.",body:{type:"object",required:["name","trigger","steps"],properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",required:["type"],properties:{type:{type:"string",enum:["cron","manual","event"]},cron:{type:"string",description:"Cron expression (required when type is cron)"},event:{type:"string",description:"Event name (required when type is event)"}}},steps:{type:"array",minItems:1,items:{type:"object",required:["id","prompt"],properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean",default:!0},goalIds:{type:"array",items:{type:"string"}},notifyTargets:{type:"array",items:{type:"object"}}}},response:R.templateCreated}},async(t,s)=>{let r=qt.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n={id:da(),...r.data,createdAt:Date.now()};return We(n),n.enabled&&n.trigger.type==="cron"&&n.trigger.cron&&await e.scheduleJob(n.id),s.status(201).send({templateId:n.id})}),o.get("/task-templates",{schema:{tags:["Templates"],summary:"List task templates",description:"List all task templates, optionally filtering to enabled-only.",querystring:{type:"object",properties:{enabled:{type:"string",enum:["true","false"],description:"Filter to enabled templates only when 'true'"}}},response:R.templateList}},async t=>{let r=t.query.enabled==="true";return{templates:we(r)}}),o.get("/task-templates/:id",{schema:{tags:["Templates"],summary:"Get task template by ID",description:"Retrieve a single task template by its ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDetail}},async(t,s)=>{let r=tt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n=U(r.data.id);return n?{template:n}:s.status(404).send({code:"NOT_FOUND",message:"Template not found"})}),o.patch("/task-templates/:id",{schema:{tags:["Templates"],summary:"Update a task template",description:"Partially update a task template. Cron schedules are automatically rescheduled if the trigger changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",properties:{type:{type:"string",enum:["cron","manual","event"]},cron:{type:"string"},event:{type:"string"}}},steps:{type:"array",items:{type:"object"}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean"},goalIds:{type:"array",items:{type:"string"}},notifyTargets:{type:"array",items:{type:"object"}},deliverTo:{type:"array",items:{type:"object"}}}},response:R.templateUpdated}},async(t,s)=>{let r=tt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n=pa.safeParse(t.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(n.error)});if(!U(r.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Template not found"});Rs(r.data.id,n.data),await e.unscheduleJob(r.data.id);let i=U(r.data.id);return i?.enabled&&i.trigger.type==="cron"&&i.trigger.cron&&await e.scheduleJob(i.id),{templateId:r.data.id}}),o.delete("/task-templates/:id",{schema:{tags:["Templates"],summary:"Delete a task template",description:"Delete a task template by ID. Cron jobs are automatically unscheduled.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDeleted}},async(t,s)=>{let r=tt.safeParse(t.params);return r.success?U(r.data.id)?(await e.unscheduleJob(r.data.id),Is(r.data.id),{templateId:r.data.id,deleted:!0}):s.status(404).send({code:"NOT_FOUND",message:"Template not found"}):s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)})}),o.post("/task-templates/:id/run",{schema:{tags:["Templates"],summary:"Run a task template",description:"Manually trigger execution of a task template regardless of its trigger type.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateRun}},async(t,s)=>{let r=tt.safeParse(t.params);return r.success?U(r.data.id)?{executionId:await e.runNow(r.data.id),status:"started"}:s.status(404).send({code:"NOT_FOUND",message:"Template not found"}):s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)})})}import{z as C}from"zod/v4";St();var Bt=C.object({id:C.string().min(1)}),ua=C.object({scope:C.enum(["user","project"]).optional(),cwd:C.string().optional()}),ma=C.object({scope:C.enum(["user","project"]).optional(),cwd:C.string().optional()});async function Vr(o){o.get("/plugins",{schema:{tags:["Plugins"],summary:"List all installed plugins",querystring:{type:"object",properties:{scope:{type:"string",enum:["user","project","local"]}}}}},async t=>{let s=t.query,r=fe({scope:s.scope}),n=wt();return{plugins:r.map(a=>({...a,globalEnabled:n[a.id]??a.enabled}))}}),o.get("/plugins/:id",{schema:{tags:["Plugins"],summary:"Get plugin by ID",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});let n=ms(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Plugin not found"});let a=us(n.installPath),i=wt();return{plugin:{...n,globalEnabled:i[n.id]??n.enabled,manifest:a}}}),o.post("/plugins/:id/enable",{schema:{tags:["Plugins"],summary:"Enable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});try{return Us(r.data.id),{pluginId:r.data.id,enabled:!0}}catch(n){return s.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Enable failed"})}}),o.post("/plugins/:id/disable",{schema:{tags:["Plugins"],summary:"Disable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});try{return Ws(r.data.id),{pluginId:r.data.id,enabled:!1}}catch(n){return s.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Disable failed"})}}),o.get("/plugins/stats",{schema:{tags:["Plugins"],summary:"Get plugin usage statistics",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async t=>{let s=t.query;return{stats:Nr(s.limit??50)}});let e=C.object({roleId:C.string().min(1)});o.get("/plugins/stats/role/:roleId",{schema:{tags:["Plugins"],summary:"Get plugin usage by role",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}}}},async(t,s)=>{let r=e.safeParse(t.params);return r.success?{roleId:r.data.roleId,stats:jr(r.data.roleId)}:s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)})}),o.get("/plugins/marketplace",{schema:{tags:["Marketplace"],summary:"List available marketplace plugins"}},async(t,s)=>{if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found. Install Claude Code to use marketplace features."});try{let r=Ls();return{available:r.available,installed:r.installed}}catch(r){return s.status(500).send({code:"CLI_ERROR",message:r instanceof Error?r.message:"CLI command failed"})}}),o.get("/plugins/marketplaces",{schema:{tags:["Marketplace"],summary:"List known marketplace sources"}},async()=>({sources:fs()})),o.post("/plugins/install/:name",{schema:{tags:["Marketplace"],summary:"Install a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,s)=>{let n=C.object({name:C.string().min(1)}).safeParse(t.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(n.error)});let a=ua.safeParse(t.body??{});if(!a.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(a.error)});if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return qs(n.data.name,a.data.scope??"user",a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return s.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Install failed"})}}),o.post("/plugins/uninstall/:name",{schema:{tags:["Marketplace"],summary:"Uninstall a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,s)=>{let n=C.object({name:C.string().min(1)}).safeParse(t.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(n.error)});let a=ma.safeParse(t.body??{});if(!a.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(a.error)});if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return Bs(n.data.name,a.data.scope,a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return s.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Uninstall failed"})}})}import{z as Ut}from"zod/v4";var ga=Ut.object({name:Ut.string().min(1)}),fa="x-api-key";async function $r(o,e,t){o.post("/webhooks/:name",{schema:{tags:["Webhooks"],summary:"Trigger a webhook",description:"Trigger a task template execution by name or ID. Requires X-API-Key header if API key is configured.",security:[{apiKey:[]}],params:{type:"object",required:["name"],properties:{name:{type:"string",description:"Template name or ID"}}},response:R.webhookTriggered}},async(s,r)=>{if(t&&s.headers[fa]!==t)return r.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"});let n=ga.safeParse(s.params);if(!n.success)return r.status(400).send({code:"VALIDATION_ERROR",message:Ut.prettifyError(n.error)});let{name:a}=n.data,i=U(a);if(!i){let{listTaskTemplates:d}=await import("./task-templates-AKQB7RRB.js");i=d(!1).find(l=>l.name===a||l.id===a)}if(!i)return r.status(404).send({code:"NOT_FOUND",message:`Template '${a}' not found`});if(!i.enabled)return r.status(409).send({code:"DISABLED",message:`Template '${a}' is disabled`});try{let d=await e.runNow(i.id);return r.status(202).send({code:"ACCEPTED",message:`Template '${i.name}' triggered`,executionId:d,templateId:i.id})}catch(d){let c=d instanceof Error?d.message:String(d);return r.status(500).send({code:"EXECUTION_ERROR",message:c})}}),o.get("/webhooks",{schema:{tags:["Webhooks"],summary:"List available webhooks",description:"List all enabled task templates that can be triggered via webhook, along with auth requirements.",response:R.webhookList}},async()=>{let{listTaskTemplates:s}=await import("./task-templates-AKQB7RRB.js");return{webhooks:s(!0).map(n=>({name:n.id,displayName:n.name,description:n.description,tags:n.tags,trigger:`POST /webhooks/${n.id}`})),auth:t?"X-API-Key header required":"No auth configured"}})}import{z as k}from"zod/v4";var ya=k.object({status:k.string().optional(),limit:k.coerce.number().min(1).max(100).default(20),offset:k.coerce.number().min(0).default(0)}),zr=k.union([k.object({type:k.literal("session"),sessionId:k.string()}),k.object({type:k.literal("channel"),channelId:k.string(),chatId:k.string().optional()})]),ha=k.object({input:k.string().min(1,"goal input is required"),notifyTargets:k.array(zr).optional()}),Hr=k.object({id:k.string().min(1)}),ba=k.object({name:k.string().min(1).optional(),description:k.string().optional(),status:k.enum(["active","paused","completed","failed"]).optional(),currentValue:k.number().optional(),budgetUsd:k.number().min(0).optional(),notifyTargets:k.array(zr).optional()});async function Kr(o){o.get("/goals",{schema:{tags:["Goals"],summary:"List goals",description:"List goals with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",description:"Filter by goal status"},limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0}}},response:R.goalList}},async(e,t)=>{let s=ya.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let{status:r,limit:n,offset:a}=s.data;return{goals:Ts(r,n,a)}}),o.get("/goals/:id",{schema:{tags:["Goals"],summary:"Get goal by ID",description:"Retrieve a single goal by its ID, including metric tree and progress.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.goalDetail}},async(e,t)=>{let s=re(e.params.id);return s?{goal:s}:t.status(404).send({code:"NOT_FOUND",message:"Goal not found"})}),o.post("/goals",{schema:{tags:["Goals"],summary:"Create a goal",description:"Create a new goal from a natural language input. The input is parsed, validated, and a metric tree is built.",body:{type:"object",required:["input"],properties:{input:{type:"string",minLength:1,description:"Natural language goal description"},notifyTargets:{type:"array",items:{type:"object"},description:"Notification targets (session or channel)"}}},response:R.goalCreated}},async(e,t)=>{let s=ha.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let r=await Fs(s.data.input);if(!r.validationResult.isValid)return t.status(400).send({code:"INVALID_GOAL",errors:r.validationResult.errors,warnings:r.validationResult.warnings});let n=Ms(r.goalState,s.data.notifyTargets);return js(n.id,n.metricType),t.status(201).send({goal:n})}),o.patch("/goals/:id",{schema:{tags:["Goals"],summary:"Update a goal",description:"Partially update a goal's name, description, status, currentValue, or budgetUsd.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},status:{type:"string"},currentValue:{type:"number"},budgetUsd:{type:"number",minimum:0},notifyTargets:{type:"array",items:{type:"object"},description:"Notification targets (session or channel)"}}},response:R.goalDetail}},async(e,t)=>{let s=Hr.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let r=ba.safeParse(e.body);return r.success?re(s.data.id)?(Ge(s.data.id,{...r.data,updatedAt:Date.now()}),{goal:re(s.data.id)}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)})}),o.delete("/goals/:id",{schema:{tags:["Goals"],summary:"Delete a goal",description:"Delete a goal by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Hr.safeParse(e.params);return s.success?re(s.data.id)?(ws(s.data.id),{goalId:s.data.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)})})}import{z as Oe}from"zod/v4";var va=Oe.object({role:Oe.enum(["engineer","analyst","content_creator","reviewer"]).optional(),taskType:Oe.string().optional(),limit:Oe.coerce.number().min(1).max(100).default(50)});async function Jr(o){o.get("/strategies",{schema:{tags:["Strategies"],summary:"List strategies",description:"List agent strategies with optional role/taskType filter. Returns evolutionary strategy entries used for agent routing.",querystring:{type:"object",properties:{role:{type:"string",enum:["engineer","analyst","content_creator","reviewer"]},taskType:{type:"string",description:"Filter by task type"},limit:{type:"integer",minimum:1,maximum:100,default:50}}},response:R.strategyList}},async(e,t)=>{let s=va.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:Oe.prettifyError(s.error)});let{role:r,taskType:n,limit:a}=s.data,i;if(r&&n)i=Ns.getStrategies(r,n);else if(r)i=Pt(r);else{let d=["engineer","analyst","content_creator","reviewer"];i=[];for(let c of d)i.push(...Pt(c))}return{strategies:i.slice(0,a)}})}async function Qr(o){o.get("/config",{schema:{tags:["Config"],summary:"Get current configuration",description:"Returns the current server configuration with runtime-mutable vs restart-required indication for each setting.",response:R.configGet}},async(e,t)=>{let s=Y(),r=[...qe,...pt],n={};for(let a of r){let i=ut(s,a),d=qe.includes(a);n[a]={value:i,mutable:d}}return{config:n,mutable:[...qe],restartRequired:[...pt]}}),o.patch("/config",{schema:{tags:["Config"],summary:"Update runtime-mutable configuration",description:"Updates configuration values that can be changed at runtime. Restart-required settings are rejected but valid mutable changes are still applied (partial success).",response:R.configPatch}},async(e,t)=>{let s=e.body;if(!s||typeof s!="object")return t.status(400).send({success:!1,updated:[],errors:["Request body must be a JSON object with config key-value pairs"],message:"Validation error"});let r=Yt(s);if(r.updated.includes("logging.level")){let n=s["logging.level"];typeof n=="string"&&Be(n)}if(r.updated.length>0){let n=Y(),a=r.updated.map(i=>({path:i,value:ut(n,i)}));g.emit({type:"config_changed",changes:a})}return{success:r.errors.length===0,updated:r.updated,errors:r.errors,message:r.errors.length===0?`Updated ${r.updated.length} configuration value(s)`:`Updated ${r.updated.length} value(s); ${r.errors.length} rejected (restart required)`}})}async function Yr(o){o.get("/evolution-audit",{schema:{tags:["Evolution"],summary:"List evolution audit records",description:"Returns evolution audit log entries with optional role filter.",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0},roleId:{type:"string"}}}}},async(e,t)=>{let{limit:s=20,offset:r=0,roleId:n}=e.query;return n?Ks(n,s,r):zs(s,r)})}import{z as I}from"zod/v4";var Ra=["active","archived"],Ia=I.object({source:I.object({type:I.enum(["tui","web","api","channel"]),channelId:I.string().optional(),chatId:I.string().optional()}),roleId:I.string().optional()}),Fe=I.object({id:I.string().uuid()}),ka=I.object({status:I.enum(Ra).optional(),limit:I.coerce.number().min(1).max(100).default(100),offset:I.coerce.number().min(0).default(0)}),Ta=I.object({limit:I.coerce.number().min(1).max(200).default(50),offset:I.coerce.number().min(0).default(0)});async function Xr(o){o.post("/chat/sessions",{schema:{tags:["Chat"],summary:"Create a chat session",body:{type:"object",required:["source"],properties:{source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"}}}}},async(t,s)=>{let r=Ia.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{source:n,roleId:a}=r.data,i=$e(n,a);return s.status(201).send({session:i})}),o.get("/chat/sessions",{schema:{tags:["Chat"],summary:"List chat sessions",querystring:{type:"object",properties:{status:{type:"string",enum:["active","archived"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(t,s)=>{let r=ka.safeParse(t.query);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{status:n}=r.data;return{sessions:Es(n)}}),o.get("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Get chat session with messages",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=Tt(n.id);return{session:n,messages:a}}),o.post("/chat/sessions/:id/archive",{schema:{tags:["Chat"],summary:"Archive a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);return n?(Cs(n.id),{sessionId:n.id,status:"archived"}):s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.post("/chat/sessions/:id/restore",{schema:{tags:["Chat"],summary:"Restore an archived session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=_s(r.data.id);return n?{session:n}:s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.delete("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Delete a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);return n?(As(n.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.get("/chat/sessions/:id/messages",{schema:{tags:["Chat"],summary:"Get messages for a session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=Ta.safeParse(t.query),{limit:i=50,offset:d=0}=a.success?a.data:{};return{messages:Tt(n.id,i,d)}});let e=I.object({content:I.string().min(1,"content is required"),source:I.object({type:I.enum(["tui","web","api","channel"]),channelId:I.string().optional(),chatId:I.string().optional()}),roleId:I.string().optional(),sessionId:I.string().uuid().optional()});o.post("/chat/messages",{schema:{tags:["Chat"],summary:"Send a chat message",description:"Send a message. Creates a session if no active session exists for the source. Returns sessionId, messageId, and response.",body:{type:"object",required:["content","source"],properties:{content:{type:"string",minLength:1},source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"},sessionId:{type:"string"}}}}},async(t,s)=>{let r=e.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{content:n,source:a,roleId:i,sessionId:d}=r.data,c=await et(n,a,i,d);return s.status(201).send(c)})}var wa=E("ws"),st=new Set,rt=[],Sa=50;function Pa(o){rt.push(o),rt.length>Sa&&rt.shift()}function Re(o){Pa(o);let e=JSON.stringify(o);for(let t of st)t.readyState===1&&t.send(e)}function Zr(o){o.get("/chat/stream",{websocket:!0},(e,t)=>{st.add(e);for(let s of rt)e.readyState===1&&e.send(JSON.stringify(s));e.on("close",()=>{st.delete(e)}),e.on("error",s=>{wa.error({error:s},"Chat WebSocket error"),st.delete(e)})}),g.on("session_created",e=>Re(e)),g.on("session_archived",e=>Re(e)),g.on("session_restored",e=>Re(e)),g.on("session_deleted",e=>Re(e)),g.on("chat_message",e=>Re(e)),g.on("task_complete_event",e=>Re(e))}var L=E("channels"),nt=class{adapters=new Map;rateLimits=new Map;healthInterval;rateLimitPerMinute;constructor(e){this.rateLimitPerMinute=e?.rateLimitPerMinute??60}async addChannel(e,t){this.adapters.set(e.id,t),t.onMessage(s=>{this.handleInbound(e.id,s)}),e.enabled&&await this.connectChannel(e.id)}async removeChannel(e){let t=this.adapters.get(e);if(t){try{await t.disconnect()}catch(s){L.error({channelId:e,error:s},"Error disconnecting channel")}this.adapters.delete(e),this.rateLimits.delete(e)}}async connectChannel(e){let t=this.adapters.get(e);if(!t)throw new Error(`No adapter registered for channel ${e}`);try{ye(e,"connecting"),await t.connect(),ye(e,"connected"),L.info({channelId:e,platform:t.platform},"Channel connected")}catch(s){throw ye(e,"error"),L.error({channelId:e,error:s},"Failed to connect channel"),s}}async disconnectChannel(e){let t=this.adapters.get(e);if(t)try{await t.disconnect(),ye(e,"disconnected"),L.info({channelId:e},"Channel disconnected")}catch(s){L.error({channelId:e,error:s},"Error disconnecting channel")}}getChannelStatus(e){let t=this.adapters.get(e);return t?t.getStatus():"disconnected"}getChannelStatuses(){let e=new Map;for(let[t,s]of this.adapters)e.set(t,s.getStatus());return e}hasAdapter(e){return this.adapters.has(e)}async sendMessage(e,t,s){let r=this.adapters.get(e);if(!r)return L.warn({channelId:e},"No adapter for outbound message"),null;if(!this.checkRateLimit(e))return L.warn({channelId:e},"Rate limit exceeded, dropping outbound message"),null;try{return await r.sendMessage(t,s)}catch(n){return L.error({channelId:e,chatId:t,error:n},"Failed to send outbound message"),null}}checkRateLimit(e){let t=Date.now(),s=this.rateLimits.get(e);return!s||t-s.windowStart>=6e4?(this.rateLimits.set(e,{count:1,windowStart:t}),!0):s.count>=this.rateLimitPerMinute?!1:(s.count++,!0)}async handleInbound(e,t){if(t.source==="system"){L.debug({channelId:e},"Skipping system message (anti-loop)");return}try{let{isDeliveryMessage:r}=await import("./engine-7VBPXTGK.js"),n=t.channelMessageId??t.raw?.MsgId??"";if(n&&r(String(n))){L.debug({channelId:e,messageId:n},"Skipping delivery-sent message (anti-loop)");return}}catch{}if(!this.checkRateLimit(e)){L.warn({channelId:e,senderId:t.senderId},"Rate limit exceeded for inbound message");return}try{let{handleInboundForApproval:r}=await import("./approval-handler-SBFVVFGH.js");if(await r(e,t.chatId,t.content)){L.debug({channelId:e,chatId:t.chatId},"Inbound message consumed as approval reply");return}}catch{}let s=Ss(e);if(s?.allowedChatIds&&!s.allowedChatIds.includes(t.chatId)){L.debug({channelId:e,chatId:t.chatId},"Chat not in allowlist, ignoring");return}try{let r=await et(t.content,{type:"channel",channelId:e,chatId:t.chatId},s?.linkedRoleId);L.info({channelId:e,chatId:t.chatId,sessionId:r.sessionId},"Inbound message routed to session")}catch(r){L.error({channelId:e,chatId:t.chatId,error:r},"Failed to route inbound message")}}startHealthMonitor(e=3e4){this.stopHealthMonitor(),this.healthInterval=setInterval(()=>{this.checkHealth()},e)}stopHealthMonitor(){this.healthInterval&&(clearInterval(this.healthInterval),this.healthInterval=void 0)}checkHealth(){for(let[e,t]of this.adapters){let s=t.getStatus();try{ye(e,s)}catch{}}}async startAll(){let e=Ve(!0);for(let t of e){let s=this.adapters.get(t.id);if(s&&s.getStatus()!=="connected")try{await this.connectChannel(t.id)}catch{}}this.startHealthMonitor()}async stopAll(){this.stopHealthMonitor();for(let e of this.adapters.keys())await this.disconnectChannel(e);this.adapters.clear(),this.rateLimits.clear()}_getAdapterCount(){return this.adapters.size}_getRateLimitEntry(e){return this.rateLimits.get(e)}};ke();var ee=E("watchdog"),at=null;function en(o,e,t,s){if(!o.enabled){ee.info("Watchdog disabled");return}let r=o.intervalMinutes*6e4;ee.info({intervalMinutes:o.intervalMinutes},"Watchdog started"),at=setInterval(()=>{Ca(o,e,t,s)},r)}function tn(){at&&(clearInterval(at),at=null,ee.info("Watchdog stopped"))}function Ca(o,e,t,s){let{rules:r}=o;if(r.managerHealthCheck.enabled){let n=r.managerHealthCheck.staleDurationMinutes*6e4,a=e.getLastActivityAt();if(Date.now()-a>n){let i=`ChatManager session stale (no activity for ${r.managerHealthCheck.staleDurationMinutes} min)`;if(ee.warn(i),r.managerHealthCheck.action==="restart"){let d=e.getConsecutiveStaleCount()>0;e.restartSession(),d&&(ee.fatal("ChatManager unrecoverable after session restart \u2014 exiting for supervisor restart"),process.exit(1))}else r.managerHealthCheck.action==="notify"&&s(i)}}if(!t.isHealthy()){let n="ExecutionPool is not healthy (stopped unexpectedly)";ee.warn(n),s(n)}if(r.staleTasks.enabled){let n=r.staleTasks.maxPendingMinutes*6e4,i=N("pending").filter(d=>Date.now()-d.createdAt>n);if(i.length>0){let d=`${i.length} stale task(s) pending > ${r.staleTasks.maxPendingMinutes} min`;ee.warn({count:i.length},d),r.staleTasks.action==="notify"&&s(d)}}if(r.staleRunningTasks?.enabled){let n=r.staleRunningTasks.maxRunningMinutes*6e4,i=N("running").filter(d=>{if(!d.startedAt||Date.now()-d.startedAt<n)return!1;try{let u=j().prepare("SELECT MAX(timestamp) as latest FROM step_logs WHERE task_id = ?").get(d.id)?.latest??d.startedAt;return Date.now()-u>n}catch{return!0}});if(i.length>0){let d=`${i.length} task(s) running with no activity for > ${r.staleRunningTasks.maxRunningMinutes} min \u2014 marking as failed`;ee.warn({count:i.length,taskIds:i.map(c=>c.id)},d);for(let c of i)$(c.id,{status:"failed",error:`Watchdog timeout: no activity for > ${r.staleRunningTasks.maxRunningMinutes} min`,completedAt:Date.now()}),g.emit({type:"task_status_change",taskId:c.id,oldStatus:"running",newStatus:"failed"}),t.releaseSlot(c.id);s(d)}}if(r.dbMaintenance.enabled)try{let a=j().pragma("wal_checkpoint(PASSIVE)");ee.debug({walSize:a},"WAL checkpoint")}catch(n){ee.error({error:n},"DB health check failed")}}import{z as D}from"zod";import{v4 as _a}from"uuid";var Aa=D.object({eventType:D.enum(["task_complete","task_error","plan_approval_request","*"]),matchCriteria:D.object({templateId:D.string().optional(),skillId:D.string().optional(),skillRole:D.string().optional(),promptPattern:D.string().optional(),taskStatus:D.string().optional()}).optional().default({}),target:D.object({type:D.enum(["channel","webhook"]),channelId:D.string().optional(),chatId:D.string().optional(),webhookUrl:D.string().optional()}),formatTemplate:D.string().optional(),maxPerMinute:D.number().int().min(1).max(60).optional().default(5),skipOriginChannel:D.boolean().optional().default(!0),enabled:D.boolean().optional().default(!0)});async function Wt(o){o.get("/delivery-rules",async(e,t)=>Vs()),o.post("/delivery-rules",async(e,t)=>{let s=Aa.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:D.prettifyError(s.error)});let r=s.data,n={id:_a(),eventType:r.eventType,matchCriteria:r.matchCriteria,target:r.target,formatTemplate:r.formatTemplate,maxPerMinute:r.maxPerMinute,skipOriginChannel:r.skipOriginChannel,enabled:r.enabled,createdAt:Date.now()};return Gs(n),t.status(201).send(n)}),o.put("/delivery-rules/:id",async(e,t)=>{if(!ze(e.params.id))return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let r=e.body;return $s(e.params.id,r),{id:e.params.id,updated:!0}}),o.delete("/delivery-rules/:id",async(e,t)=>ze(e.params.id)?(Hs(e.params.id),{id:e.params.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"})),o.get("/delivery-rules/:id/log",async(e,t)=>Xs(e.params.id)),o.post("/delivery-rules/:id/test",async(e,t)=>{let s=ze(e.params.id);if(!s)return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let{getDeliveryEngine:r}=await import("./engine-7VBPXTGK.js"),n=r();if(!n)return t.status(503).send({code:"ENGINE_NOT_READY",message:"DeliveryEngine not initialized"});let a=`[TEST] Delivery rule test at ${new Date().toISOString()}`,{createDeliveryLog:i}=await import("./delivery-log-7DQ36UGP.js"),{v4:d}=await import("uuid"),{TTL_MS:c}=await import("./delivery-log-7DQ36UGP.js"),l={id:d(),ruleId:s.id,status:"pending",target:s.target,content:a,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+c};i(l);try{return await n.attemptDeliveryPublic(l,s),{id:l.id,ruleId:s.id,status:"sent",content:a}}catch(b){let u=b instanceof Error?b.message:String(b);return t.status(500).send({code:"DELIVERY_FAILED",message:u,logId:l.id})}})}me();var _=E("adam");function xa(o){let e={...o};if(e.defaults&&typeof e.defaults=="object"){let t={...e.defaults};if(t.env&&typeof t.env=="object"){let s={...t.env};for(let r of Object.keys(s))s[r]&&(s[r]=s[r].slice(0,4)+"****");t.env=s}e.defaults=t}if(e.server&&typeof e.server=="object"){let t={...e.server};t.apiKey&&typeof t.apiKey=="string"&&(t.apiKey=t.apiKey.slice(0,4)+"****"),e.server=t}return e}async function Da(){sr();let o=rr();o.length>0&&console.log(`[adam] Migrated to ~/.adam/: ${o.join(", ")}`);let e=nr();_.info("Starting Adam Agent Server"),e.length>0&&_.info({files:e},"Loaded env files");let t=Jt();Qt(t),t.logging?.level&&Be(t.logging.level),_.info({config:xa(t)},"Config loaded"),process.env.ANTHROPIC_API_KEY||_.warn("ANTHROPIC_API_KEY not set \u2014 Manager LLM queries will fail"),process.env.ANTHROPIC_BASE_URL&&_.info({url:process.env.ANTHROPIC_BASE_URL},"Using custom API base URL");let s=t.defaults?.claudeCodePath;try{if(!s){let{createRequire:le}=await import("module"),{dirname:Ie,join:pe}=await import("path"),Ne=le(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");s=pe(Ie(Ne),"cli.js")}let{execSync:f}=await import("child_process"),G=f(`"${s}" --version`,{timeout:5e3,encoding:"utf-8"}).trim();_.info({path:s,version:G},"Claude Code CLI detected")}catch(f){let G=f;G.code==="ENOENT"?_.warn({path:s},"Claude Code CLI not found. Task execution will fail. Install: npm i -g @anthropic-ai/claude-code"):_.warn({path:s,error:(G.stderr?.trim()||String(f)).slice(0,200)},"Claude Code CLI check failed")}let n=j().prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();_.info({tables:n.map(f=>f.name).join(", ")},"Database initialized");let a=xt(),{getToolsFingerprint:i}=await import("./adam-tools-MKUMZWCR.js"),d=i(),c=a.sdkSessionId;if(c&&a.toolsFingerprint!==d&&(_.info({old:a.toolsFingerprint?.slice(0,40),new:d.slice(0,40)},"MCP tools changed \u2014 invalidating old SDK session"),Rr(),c=void 0),Pe({toolsFingerprint:d}),c){let f=process.cwd();a.workspacePath&&a.workspacePath!==f&&(_.warn({serverCwd:f,saved:a.workspacePath},"Workspace mismatch"),_.warn("SDK session may not resume correctly due to cwd mismatch")),_.info({sessionId:c.slice(0,8)},"Recovering manager SDK session")}else _.info("No previous manager SDK session found, starting fresh");a.userTaskSessionId&&_.info({sessionId:a.userTaskSessionId.slice(0,8)},"Recovering user task session"),Ir(process.cwd());let{initializeDefaultRoles:l}=await import("./role-presets-2X3VW75D.js"),b=l();_.info({count:b.length},"Roles initialized");let y=Y().execution??{maxConcurrent:3,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},w=new Ee(c),v=new De(y.maxConcurrent);Ur(w),await w.start(),await v.start();let W=N("running");if(W.length>0){_.warn({count:W.length},"Found orphaned running tasks from previous session \u2014 marking as failed");for(let f of W)$(f.id,{status:"failed",error:"Server restarted while task was running",completedAt:Date.now()})}let T=ir(t,t.server.apiKey);await T.register(f=>ur(f)),await T.register(f=>mr(f,t)),await T.register(f=>hr(f,t.server.apiKey)),await T.register(Sr),await T.register(Or),await T.register(Kr),await T.register(Jr);let te=new Ze;await te.start(),tr(),await T.register(f=>Gr(f,te)),await T.register(Vr),await T.register(f=>$r(f,te,process.env.ADAM_WEBHOOK_API_KEY)),await T.register(Qr),await T.register(Yr),await T.register(Xr);let Q=new nt;Qs(Q),await T.register(Ys),await T.register(Zr),await T.register(f=>vr(f,t.server.apiKey)),await T.register(xr),await T.register(Wt),xs(),Zs(),Q.startHealthMonitor();try{let f=Ve();for(let G of f)if(G.platform==="wechat"){let le=G.config;if(le.botToken){let Ie=new Js(G.id,le);Q.addChannel(G,Ie)}}}catch(f){_.error({error:f},"Failed to register WeChat adapters at startup")}let{host:Me,port:ce}=t.server;await T.listen({host:Me,port:ce}),_.info({host:Me,port:ce},"Server listening");let it=t.watchdog??Kt.watchdog;en(it,w,v,f=>{_.warn({alert:f},"Watchdog alert")}),ts(f=>{g.emit({type:"log_event",timestamp:f.time??Date.now(),level:f.level??"info",component:f.component??"adam",msg:f.msg??""})}),rn(q,{recursive:!0}),rn(ot(q,"logs"),{recursive:!0}),sn(ot(q,"adam.port"),String(ce)),t.server.apiKey&&sn(ot(q,"adam.key"),t.server.apiKey,{mode:384}),process.send?.({type:"ready",port:ce});let je=async()=>{_.info("Shutting down"),tn(),Ds(),er(),await Q.stopAll(),w.stop(),v.stop(),await te.stop(),await T.close(),mt();try{Ea(ot(q,"adam.key"))}catch{}process.exit(0)};process.on("SIGINT",()=>{je()}),process.on("SIGTERM",()=>{je()})}Da().catch(o=>{_.fatal(o,"Fatal error"),process.exit(1)});
129
+ `).all(o)}he();import{createSdkMcpServer as _o,tool as ln}from"@anthropic-ai/claude-agent-sdk";import{z as pn}from"zod";async function Ao(o){let{listChannels:e}=await import("./channels-VEUBY2NZ.js"),t=e(),{listSessions:r}=await import("./session-manager-45LFTPBA.js"),s=[...r("active"),...r("archived")],n=t.find(c=>c.name.toLowerCase().includes(o.toLowerCase()));if(!n)return null;let i=s.find(c=>c.source.type==="channel"&&c.source.channelId===n.id&&c.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:i}}function Ae(o){return{content:[{type:"text",text:JSON.stringify(o)}]}}function un(o){let e=o?q(o):void 0,t=[...nr(o),ln("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:r}=await import("./channels-VEUBY2NZ.js"),s=r();return Ae({channels:s.map(n=>({id:n.id,name:n.name,enabled:n.enabled,type:n.config?.type??"unknown"}))})}),ln("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:pn.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:pn.string().describe("The message content to send")},async r=>{if(e?.allowedChannels!==void 0){if(e.allowedChannels.length===0)return Ae({error:"This role is not allowed to send to any channels"});if(!e.allowedChannels.some(l=>l.toLowerCase()===r.channelName.toLowerCase()))return Ae({error:`Channel "${r.channelName}" is not in the allowed channels list for this role`})}let s=await Ao(r.channelName);if(!s)return Ae({error:`Channel "${r.channelName}" not found or has no chatId available`});let{getOutboundGateway:n}=await import("./outbound-gateway-FIPC4BZO.js"),i=await n().send({channelId:s.channelId,chatId:s.chatId,content:r.message,messageType:"reply"});return Ae({success:i.success,channelName:r.channelName})})];return _o({name:"execution-tools",version:"1.0.0",tools:t})}var z=O("execution"),Ee=class{async execute(e,t){let r=Date.now(),s,n,a;G(e.id,{status:"running",startedAt:Date.now()}),f.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),z.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let i=e.roleId?q(e.roleId):void 0,c=A;i&&(we(i),c=ee(i.name));let l={taskId:e.id,prompt:e.prompt,roleName:i?.name,roleCagPrompt:i?.cagPrompt,allowedTools:i?.allowedTools},d=Lt(l),m=Pe({currentTaskId:e.id,roleId:e.roleId,taskPrompt:e.prompt}),h=e.config.approvalTimeout??300,y=i?.preferences?.permissions,C=Ce(x=>({allowedPaths:y?.allowedPaths,deniedPaths:y?.deniedPaths,disallowedTools:i?.disallowedTools,approvalRequired:i?.approvalRequired??e.config.approvalRequired}),async(x,N,Y,Fe)=>{let Z=xo(),Kt=fs(Fe??e.roleId,e.prompt,"medium");if(Kt)return z.info({operationId:Z,ruleId:Kt.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:N};let zt={steps:[{index:0,description:`${x}: ${JSON.stringify(N).slice(0,300)}`,toolsNeeded:[x],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return us({id:Z,taskId:e.id,roleId:Fe??e.roleId,plan:zt,status:"pending",createdAt:Date.now()}),f.emit({type:"plan_approval_request",taskId:e.id,planId:Z,plan:zt}),z.info({taskId:e.id,operationId:Z,toolName:x,matchedPattern:Y},"Privilege escalation: awaiting user decision"),new Promise(at=>{let En=setTimeout(()=>{Yt(),gs(Z,"denied"),z.warn({taskId:e.id,operationId:Z},"Privilege escalation timed out, auto-denied"),at({behavior:"deny",message:`Operation timed out after ${h}s. Auto-denied. Try a safer alternative that does not require approval.`})},h*1e3),Qt=ye=>{if(ye.planId===Z)if(Yt(),ye.decision==="allow")z.info({taskId:e.id,operationId:Z,approvalType:ye.approvalType},"Operation authorized by user"),at({behavior:"allow",updatedInput:N});else{let xn=ye.reason?`Operation denied by user: ${ye.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";z.info({taskId:e.id,operationId:Z,reason:ye.reason??"no reason given"},"Operation denied by user"),at({behavior:"deny",message:xn})}},Yt=()=>{clearTimeout(En),f.off("plan_approval_decision",Qt)};f.on("plan_approval_decision",Qt)})}),W={...process.env,...Le(),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1"},oe=e.config.maxBudgetUsd??5,$=e.config.maxTurns??100,ae=un(e.roleId??""),Ie=i?.mcpServers??{},_=e.config.mcpServers??{},ie={...Ie,..._,"execution-tools":ae},me=i?.additionalDirectories??[],ge=i?lr(i):[],fe=[e.config.workspacePath??process.cwd(),...me.map(x=>x.path)].filter((x,N,Y)=>Y.indexOf(x)===N),ot=Eo({prompt:e.prompt,options:{cwd:c,additionalDirectories:fe,systemPrompt:d,maxTurns:$,maxBudgetUsd:oe,allowedTools:i?.allowedTools,model:i?.model,mcpServers:ie,settingSources:i?.inheritUserSettings?["project","user"]:["project"],hooks:m,canUseTool:C,env:W,plugins:ge.map(x=>({type:"local",path:x})),stderr:x=>{x.trim()&&z.debug({stderr:x.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),ce="",v=0,V=()=>{z.warn({taskId:e.id},"ExecutionManager: abort signal received")};t&&t.addEventListener("abort",V);try{for await(let x of ot){let N=x;if(z.debug({eventType:N.type,taskId:e.id},"ExecutionManager SDK event"),N.type==="result"&&typeof N.result=="string"&&(ce=N.result),N.type==="result"&&v++,N.token_usage){let Y=N.token_usage;Y.input_tokens!==void 0&&Y.output_tokens!==void 0&&(s={input:Y.input_tokens,output:Y.output_tokens}),Y.cost_usd!==void 0&&(n=Y.cost_usd)}}}finally{t&&t.removeEventListener("abort",V)}a=v;let re=Date.now()-r;return G(e.id,{status:"completed",result:ce,completedAt:Date.now(),costUsd:n,tokenUsage:s,numTurns:a,totalDurationMs:re}),f.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),f.emit({type:"task_complete_event",taskId:e.id,result:ce}),ge.length>0&&an(e.id,ge,e.roleId),z.info({taskId:e.id,durationMs:re,costUsd:n},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:ce,costUsd:n,tokenUsage:s,numTurns:a,durationMs:re}}catch(i){let c=i instanceof Error?i.message:String(i),l=Date.now()-r;return(c.includes("Prompt is too long")||c.includes("prompt is too long"))&&z.warn({taskId:e.id,error:c},"Task prompt exceeds model context window \u2014 task failed"),G(e.id,{status:"failed",error:c,completedAt:Date.now(),totalDurationMs:l}),f.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),f.emit({type:"task_complete_event",taskId:e.id,error:c}),z.error({taskId:e.id,error:i},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:c,durationMs:l}}}};var Q=O("execution-pool"),xe=class{slots;running=!1;pollTimeoutId=null;executor;constructor(e,t){this.slots=Array.from({length:e},(r,s)=>({index:s,taskId:null,abortController:null})),this.executor=t??new Ee}async start(){if(this.running)return;this.running=!0,f.on("task_created",r=>{this.onTaskCreated(r.taskId)}),f.on("task_status_change",r=>{r.newStatus==="pending"&&this.pickupPendingTasks()});let t=U().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t),Q.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let e of this.slots)e.abortController&&(e.abortController.abort(),e.taskId=null,e.abortController=null);Q.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let t=U().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t)};async onTaskCreated(e){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let e=this.slots.find(i=>i.taskId===null);if(!e){Q.debug("No free slots available");return}let t=M("pending");if(t.length===0)return;let s=[...t].sort((i,c)=>i.createdAt-c.createdAt)[0];e.taskId=s.id,e.abortController=new AbortController;let n=e.index,a=s.id;Q.info({slotIndex:n,taskId:a},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,n).catch(i=>{Q.error({taskId:a,error:i},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(e,t){let r=this.slots[t];if(!r)return;let s="completed";try{f.emit({type:"execution_task_start",taskId:e.id,slotIndex:t});let n=await this.executor.execute(e,r.abortController?.signal);s=n.status,Q.info({taskId:e.id,status:n.status,slotIndex:t},"ExecutionPool: task finished")}finally{r.taskId=null,r.abortController=null,f.emit({type:"execution_task_end",taskId:e.id,slotIndex:t,status:s}),this.emitSlotChange(),this.runPostCompletion(e.id,e.roleId).catch(n=>{Q.error({taskId:e.id,error:n},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(r=>r.taskId!==null).length,t=M("pending");f.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:t.length})}async runPostCompletion(e,t){if(t){try{let{processTaskCompletion:r}=await import("./memory-extractor-GOISDQTO.js"),s=await r(e,t);s>0&&Q.debug({taskId:e,roleId:t,memoriesStored:s},"Post-completion: memories extracted")}catch(r){Q.error({taskId:e,roleId:t,error:r},"Post-completion: memory extraction failed")}try{let{processTaskReview:r}=await import("./learner-VMD5NQCD.js");await r(e)}catch(r){Q.error({taskId:e,roleId:t,error:r},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:r}=await import("./monitor-K7CGTLA6.js");r(e,t)}catch(r){Q.error({taskId:e,roleId:t,error:r},"Post-completion: monitor evaluation failed")}}}getStatus(){let e=this.slots.filter(r=>r.taskId!==null).length,t=M("pending");return{active:e,max:this.slots.length,queued:t.length}}isHealthy(){return this.running}releaseSlot(e){let t=this.slots.find(r=>r.taskId===e);t&&(Q.warn({taskId:e,slotIndex:t.index},"ExecutionPool: force-releasing slot"),t.abortController&&t.abortController.abort(),t.taskId=null,t.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};import{v4 as Mt}from"uuid";var qt=O("message-handler");async function Do(o,e){if(!(await import("./config-Y4QWELO3.js").then(s=>s.getChatConfig())).autoTitle)return;let r=["Generate a very short title (max 50 characters) for a chat session that started with this message:",`"${e.slice(0,200)}"`,"Respond with only the title, no quotes or explanation."].join(`
130
+ `);try{let n=(await Js(r,"You are a concise title generator. Reply with only the title, max 50 characters.")).trim().slice(0,50);n.length>0&&Is(o,{title:n})}catch{}}var Bt=null;function mn(o){Bt=o}async function Ye(o,e,t,r){let s;r&&(s=H(r)),s||(s=Vs(e)),s||(s=$e(e,t));let n=Mt(),a={id:n,sessionId:s.id,role:"user",content:o,source:e,createdAt:Date.now()};if(te(a),f.emit({type:"chat_message",sessionId:s.id,message:a}),s.messageCount===0&&Do(s.id,o),se(s.id),wt(s.id),Bt){let i=s.id,c=s.source;(async()=>{try{let l=await Bt.handleMessage(o,i,e),d={id:Mt(),sessionId:i,role:"assistant",content:l,source:e,createdAt:Date.now()};te(d),f.emit({type:"chat_message",sessionId:i,message:d}),se(i),wt(i),c.type==="channel"&&c.channelId&&c.chatId&&(qt.info({sessionId:i,sourceType:c.type,hasChannelId:!!c.channelId,hasResponse:!!l},"Chat response ready, checking channel delivery"),Oo(c.channelId,c.chatId,l))}catch(l){(await import("./logger-BEG4WFIM.js")).getLogger("message-handler").error({error:l,sessionId:i},"ChatManager response failed");let m={id:Mt(),sessionId:i,role:"assistant",content:`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`,source:e,createdAt:Date.now()};te(m),f.emit({type:"chat_message",sessionId:i,message:m}),se(i)}})()}return{sessionId:s.id,messageId:n}}async function Oo(o,e,t){qt.info({channelId:o,chatId:e.slice(0,12)},"Delivering chat response to channel");try{let{getOutboundGateway:r}=await import("./outbound-gateway-FIPC4BZO.js");await r().send({channelId:o,chatId:e,content:t,messageType:"reply"})}catch(r){qt.error({error:r,channelId:o,chatId:e.slice(0,12)},"Channel delivery failed (non-fatal)")}}import{z as b}from"zod/v4";import{v4 as Fo}from"uuid";var gn=b.union([b.object({type:b.literal("session"),sessionId:b.string()}),b.object({type:b.literal("channel"),channelId:b.string(),chatId:b.string().optional()})]),jo=b.object({id:b.string(),prompt:b.string(),dependsOn:b.array(b.string()).optional(),outputAs:b.string().optional()}),No=b.object({type:b.enum(["cron","manual","event","once"]),cron:b.string().optional(),event:b.string().optional(),runAt:b.string().optional()}),Ut=b.object({name:b.string().min(1),description:b.string().optional(),trigger:No,steps:b.array(jo).min(1),rolePreference:b.string().optional(),config:b.record(b.string(),b.unknown()).optional(),enabled:b.boolean().default(!0),goalIds:b.array(b.string()).optional(),deliverTo:b.array(gn).optional(),reportTo:b.array(gn).optional()}),nd=Ut.transform(o=>({...o,deliverTo:o.deliverTo,reportTo:o.reportTo})),Lo=Ut.partial().transform(o=>({...o,deliverTo:o.deliverTo,reportTo:o.reportTo})),Je=b.object({id:b.string().min(1)});async function fn(o,e){o.post("/task-templates",{schema:{tags:["Templates"],summary:"Create a task template",description:"Create a new task template with trigger (cron/manual/event) and execution steps. Cron-triggered templates are automatically scheduled.",body:{type:"object",required:["name","trigger","steps"],properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",required:["type"],properties:{type:{type:"string",enum:["cron","manual","event","once"]},cron:{type:"string",description:"Cron expression (required when type is cron)"},event:{type:"string",description:"Event name (required when type is event)"},runAt:{type:"string",description:"ISO 8601 timestamp (required when type is once)"}}},steps:{type:"array",minItems:1,items:{type:"object",required:["id","prompt"],properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean",default:!0},goalIds:{type:"array",items:{type:"string"}},deliverTo:{type:"array",items:{type:"object"}},reportTo:{type:"array",items:{type:"object"}}}},response:R.templateCreated}},async(t,r)=>{let s=Ut.safeParse(t.body);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(s.error)});let n={id:Fo(),...s.data,createdAt:Date.now()};return js(n),n.enabled&&n.trigger.type==="cron"&&n.trigger.cron?await e.scheduleJob(n.id):n.enabled&&n.trigger.type==="once"&&n.trigger.runAt&&e.scheduleOnceJob(n.id),r.status(201).send({templateId:n.id})}),o.get("/task-templates",{schema:{tags:["Templates"],summary:"List task templates",description:"List all task templates, optionally filtering to enabled-only.",querystring:{type:"object",properties:{enabled:{type:"string",enum:["true","false"],description:"Filter to enabled templates only when 'true'"}}},response:R.templateList}},async t=>{let s=t.query.enabled==="true";return{templates:Ls(s)}}),o.get("/task-templates/:id",{schema:{tags:["Templates"],summary:"Get task template by ID",description:"Retrieve a single task template by its ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDetail}},async(t,r)=>{let s=Je.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(s.error)});let n=ne(s.data.id);return n?{template:n}:r.status(404).send({code:"NOT_FOUND",message:"Template not found"})}),o.patch("/task-templates/:id",{schema:{tags:["Templates"],summary:"Update a task template",description:"Partially update a task template. Cron schedules are automatically rescheduled if the trigger changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",properties:{type:{type:"string",enum:["cron","manual","event","once"]},cron:{type:"string"},event:{type:"string"},runAt:{type:"string"}}},steps:{type:"array",items:{type:"object"}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean"},goalIds:{type:"array",items:{type:"string"}},deliverTo:{type:"array",items:{type:"object"}},reportTo:{type:"array",items:{type:"object"}}}},response:R.templateUpdated}},async(t,r)=>{let s=Je.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(s.error)});let n=Lo.safeParse(t.body);if(!n.success)return r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(n.error)});if(!ne(s.data.id))return r.status(404).send({code:"NOT_FOUND",message:"Template not found"});Ns(s.data.id,n.data),await e.unscheduleJob(s.data.id);let i=ne(s.data.id);return i?.enabled&&i.trigger.type==="cron"&&i.trigger.cron?await e.scheduleJob(i.id):i?.enabled&&i.trigger.type==="once"&&i.trigger.runAt&&e.scheduleOnceJob(i.id),{templateId:s.data.id}}),o.delete("/task-templates/:id",{schema:{tags:["Templates"],summary:"Delete a task template",description:"Delete a task template by ID. Cron jobs are automatically unscheduled.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDeleted}},async(t,r)=>{let s=Je.safeParse(t.params);return s.success?ne(s.data.id)?(await e.unscheduleJob(s.data.id),Ms(s.data.id),{templateId:s.data.id,deleted:!0}):r.status(404).send({code:"NOT_FOUND",message:"Template not found"}):r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(s.error)})}),o.post("/task-templates/:id/run",{schema:{tags:["Templates"],summary:"Run a task template",description:"Manually trigger execution of a task template regardless of its trigger type.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateRun}},async(t,r)=>{let s=Je.safeParse(t.params);return s.success?ne(s.data.id)?{executionId:await e.runNow(s.data.id),status:"started"}:r.status(404).send({code:"NOT_FOUND",message:"Template not found"}):r.status(400).send({code:"VALIDATION_ERROR",message:b.prettifyError(s.error)})})}import{z as E}from"zod/v4";_s();var Wt=E.object({id:E.string().min(1)}),Mo=E.object({scope:E.enum(["user","project"]).optional(),cwd:E.string().optional()}),qo=E.object({scope:E.enum(["user","project"]).optional(),cwd:E.string().optional()});async function yn(o){o.get("/plugins",{schema:{tags:["Plugins"],summary:"List all installed plugins",querystring:{type:"object",properties:{scope:{type:"string",enum:["user","project","local"]}}}}},async t=>{let r=t.query,s=qe({scope:r.scope}),n=kt();return{plugins:s.map(a=>({...a,globalEnabled:n[a.id]??a.enabled}))}}),o.get("/plugins/:id",{schema:{tags:["Plugins"],summary:"Get plugin by ID",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,r)=>{let s=Wt.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(s.error)});let n=Ss(s.data.id);if(!n)return r.status(404).send({code:"NOT_FOUND",message:"Plugin not found"});let a=ws(n.installPath),i=kt();return{plugin:{...n,globalEnabled:i[n.id]??n.enabled,manifest:a}}}),o.post("/plugins/:id/enable",{schema:{tags:["Plugins"],summary:"Enable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,r)=>{let s=Wt.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(s.error)});if(!ve())return r.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude CLI not found. Plugin enable/disable requires the Claude Agent SDK CLI."});try{return cr(s.data.id),{pluginId:s.data.id,enabled:!0}}catch(n){return r.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Enable failed"})}}),o.post("/plugins/:id/disable",{schema:{tags:["Plugins"],summary:"Disable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,r)=>{let s=Wt.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(s.error)});if(!ve())return r.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude CLI not found. Plugin enable/disable requires the Claude Agent SDK CLI."});try{return dr(s.data.id),{pluginId:s.data.id,enabled:!1}}catch(n){return r.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Disable failed"})}}),o.get("/plugins/stats",{schema:{tags:["Plugins"],summary:"Get plugin usage statistics",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async t=>{let r=t.query;return{stats:dn(r.limit??50)}});let e=E.object({roleId:E.string().min(1)});o.get("/plugins/stats/role/:roleId",{schema:{tags:["Plugins"],summary:"Get plugin usage by role",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}}}},async(t,r)=>{let s=e.safeParse(t.params);return s.success?{roleId:s.data.roleId,stats:cn(s.data.roleId)}:r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(s.error)})}),o.get("/plugins/marketplace",{schema:{tags:["Marketplace"],summary:"List available marketplace plugins"}},async(t,r)=>{if(!ve())return r.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found. Install Claude Code to use marketplace features."});try{let s=or();return{available:s.available,installed:s.installed}}catch(s){return r.status(500).send({code:"CLI_ERROR",message:s instanceof Error?s.message:"CLI command failed"})}}),o.get("/plugins/marketplaces",{schema:{tags:["Marketplace"],summary:"List known marketplace sources"}},async()=>({sources:Cs()})),o.post("/plugins/install/:name",{schema:{tags:["Marketplace"],summary:"Install a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,r)=>{let n=E.object({name:E.string().min(1)}).safeParse(t.params);if(!n.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(n.error)});let a=Mo.safeParse(t.body??{});if(!a.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(a.error)});if(!ve())return r.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return ar(n.data.name,a.data.scope??"user",a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return r.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Install failed"})}}),o.post("/plugins/uninstall/:name",{schema:{tags:["Marketplace"],summary:"Uninstall a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,r)=>{let n=E.object({name:E.string().min(1)}).safeParse(t.params);if(!n.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(n.error)});let a=qo.safeParse(t.body??{});if(!a.success)return r.status(400).send({code:"VALIDATION_ERROR",message:E.prettifyError(a.error)});if(!ve())return r.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return ir(n.data.name,a.data.scope,a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return r.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Uninstall failed"})}})}import{z as $t}from"zod/v4";var Bo=$t.object({name:$t.string().min(1)}),Uo="x-api-key";async function hn(o,e,t){o.post("/webhooks/:name",{schema:{tags:["Webhooks"],summary:"Trigger a webhook",description:"Trigger a task template execution by name or ID. Requires X-API-Key header if API key is configured.",security:[{apiKey:[]}],params:{type:"object",required:["name"],properties:{name:{type:"string",description:"Template name or ID"}}},response:R.webhookTriggered}},async(r,s)=>{if(t&&r.headers[Uo]!==t)return s.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"});let n=Bo.safeParse(r.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:$t.prettifyError(n.error)});let{name:a}=n.data,i=ne(a);if(!i){let{listTaskTemplates:c}=await import("./task-templates-7LSQ6OST.js");i=c(!1).find(d=>d.name===a||d.id===a)}if(!i)return s.status(404).send({code:"NOT_FOUND",message:`Template '${a}' not found`});if(!i.enabled)return s.status(409).send({code:"DISABLED",message:`Template '${a}' is disabled`});try{let c=await e.runNow(i.id);return s.status(202).send({code:"ACCEPTED",message:`Template '${i.name}' triggered`,executionId:c,templateId:i.id})}catch(c){let l=c instanceof Error?c.message:String(c);return s.status(500).send({code:"EXECUTION_ERROR",message:l})}}),o.get("/webhooks",{schema:{tags:["Webhooks"],summary:"List available webhooks",description:"List all enabled task templates that can be triggered via webhook, along with auth requirements.",response:R.webhookList}},async()=>{let{listTaskTemplates:r}=await import("./task-templates-7LSQ6OST.js");return{webhooks:r(!0).map(n=>({name:n.id,displayName:n.name,description:n.description,tags:n.tags,trigger:`POST /webhooks/${n.id}`})),auth:t?"X-API-Key header required":"No auth configured"}})}import{z as k}from"zod/v4";var Wo=k.object({status:k.string().optional(),limit:k.coerce.number().min(1).max(100).default(20),offset:k.coerce.number().min(0).default(0)}),Xe=k.union([k.object({type:k.literal("session"),sessionId:k.string()}),k.object({type:k.literal("channel"),channelId:k.string(),chatId:k.string().optional()})]),$o=k.object({input:k.string().min(1,"goal input is required"),deliverTo:k.array(Xe).optional(),reportTo:k.array(Xe).optional()}),bn=k.object({id:k.string().min(1)}),Vo=k.object({name:k.string().min(1).optional(),description:k.string().optional(),status:k.enum(["active","paused","completed","failed"]).optional(),currentValue:k.number().optional(),budgetUsd:k.number().min(0).optional(),deliverTo:k.array(Xe).optional(),reportTo:k.array(Xe).optional()});async function vn(o){o.get("/goals",{schema:{tags:["Goals"],summary:"List goals",description:"List goals with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",description:"Filter by goal status"},limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0}}},response:R.goalList}},async(e,t)=>{let r=Wo.safeParse(e.query);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)});let{status:s,limit:n,offset:a}=r.data;return{goals:qs(s,n,a)}}),o.get("/goals/:id",{schema:{tags:["Goals"],summary:"Get goal by ID",description:"Retrieve a single goal by its ID, including metric tree and progress.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.goalDetail}},async(e,t)=>{let r=le(e.params.id);return r?{goal:r}:t.status(404).send({code:"NOT_FOUND",message:"Goal not found"})}),o.post("/goals",{schema:{tags:["Goals"],summary:"Create a goal",description:"Create a new goal from a natural language input. The input is parsed, validated, and a metric tree is built.",body:{type:"object",required:["input"],properties:{input:{type:"string",minLength:1,description:"Natural language goal description"},deliverTo:{type:"array",items:{type:"object"},description:"Delivery targets (result output)"},reportTo:{type:"array",items:{type:"object"},description:"Report targets (status notifications)"}}},response:R.goalCreated}},async(e,t)=>{let r=$o.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)});let s=await Xs(r.data.input);if(!s.validationResult.isValid)return t.status(400).send({code:"INVALID_GOAL",errors:s.validationResult.errors,warnings:s.validationResult.warnings});let n=Zs(s.goalState,r.data.deliverTo,r.data.reportTo);return er(n.id,n.metricType),t.status(201).send({goal:n})}),o.patch("/goals/:id",{schema:{tags:["Goals"],summary:"Update a goal",description:"Partially update a goal's name, description, status, currentValue, or budgetUsd.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},status:{type:"string"},currentValue:{type:"number"},budgetUsd:{type:"number",minimum:0},deliverTo:{type:"array",items:{type:"object"},description:"Delivery targets (result output)"},reportTo:{type:"array",items:{type:"object"},description:"Report targets (status notifications)"}}},response:R.goalDetail}},async(e,t)=>{let r=bn.safeParse(e.params);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)});let s=Vo.safeParse(e.body);return s.success?le(r.data.id)?(Ue(r.data.id,{...s.data,updatedAt:Date.now()}),{goal:le(r.data.id)}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)})}),o.delete("/goals/:id",{schema:{tags:["Goals"],summary:"Delete a goal",description:"Delete a goal by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let r=bn.safeParse(e.params);return r.success?le(r.data.id)?(Bs(r.data.id),{goalId:r.data.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)})})}import{z as De}from"zod/v4";var Go=De.object({role:De.string().optional(),taskType:De.string().optional(),limit:De.coerce.number().min(1).max(100).default(50)});async function Rn(o){o.get("/strategies",{schema:{tags:["Strategies"],summary:"List strategies",description:"List agent strategies with optional role/taskType filter. Returns evolutionary strategy entries used for agent routing.",querystring:{type:"object",properties:{role:{type:"string",description:"Filter by role ID"},taskType:{type:"string",description:"Filter by task type"},limit:{type:"integer",minimum:1,maximum:100,default:50}}},response:R.strategyList}},async(e,t)=>{let r=Go.safeParse(e.query);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:De.prettifyError(r.error)});let{role:s,taskType:n,limit:a}=r.data,i;return s&&n?i=rr.getStrategies(s,n):s?i=sr(s):i=tr(a),{strategies:i.slice(0,a)}})}async function In(o){o.get("/config",{schema:{tags:["Config"],summary:"Get current configuration",description:"Returns the current server configuration with runtime-mutable vs restart-required indication for each setting.",response:R.configGet}},async(e,t)=>{let r=U(),s=[...je,...it],n={},a=new Set(["anthropic.apiKey","server.apiKey"]);for(let i of s){let c=ct(r,i),l=je.includes(i);a.has(i)&&typeof c=="string"&&c.length>0&&(c=c.slice(0,5)+"****"),n[i]={value:c??null,mutable:l}}return{config:n,mutable:[...je],restartRequired:[...it]}}),o.patch("/config",{schema:{tags:["Config"],summary:"Update runtime-mutable configuration",description:"Updates configuration values that can be changed at runtime. Restart-required settings are rejected but valid mutable changes are still applied (partial success).",response:R.configPatch}},async(e,t)=>{let r=e.body;if(!r||typeof r!="object")return t.status(400).send({success:!1,updated:[],errors:["Request body must be a JSON object with config key-value pairs"],message:"Validation error"});let s=Xt(r,St);if(s.updated.includes("logging.level")){let n=r["logging.level"];typeof n=="string"&&Me(n)}if(s.updated.length>0){let n=U(),a=s.updated.map(i=>({path:i,value:ct(n,i)}));f.emit({type:"config_changed",changes:a})}return{success:s.errors.length===0,updated:s.updated,errors:s.errors,message:s.errors.length===0?`Updated ${s.updated.length} configuration value(s)`:`Updated ${s.updated.length} value(s); ${s.errors.length} rejected (restart required)`}}),o.get("/config/env-diff",async()=>{let e=Ge();return{diffs:Sr(e),envFileExists:Pt()!==null}}),o.post("/config/sync-to-env",async()=>{let e=Ge();return{success:!0,changed:Cr(e)}}),o.post("/config/load-from-env",async()=>{let e=Pt();if(!e)return{success:!1,error:".env file not found"};let t=0;for(let[r,s]of Object.entries(e)){let n=Object.entries(wr).find(([,a])=>a===r)?.[0];n&&(St(n,s),t++)}return Ne(Ge),{success:!0,updated:t}})}async function kn(o){o.get("/evolution-audit",{schema:{tags:["Evolution"],summary:"List evolution audit records",description:"Returns evolution audit log entries with optional role filter.",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0},roleId:{type:"string"}}}}},async(e,t)=>{let{limit:r=20,offset:s=0,roleId:n}=e.query;return n?yr(n,r,s):fr(r,s)})}import{z as T}from"zod/v4";var Ho=["active","archived"],Ko=T.object({source:T.object({type:T.enum(["tui","web","api","channel"]),channelId:T.string().optional(),chatId:T.string().optional()}),roleId:T.string().optional()}),Oe=T.object({id:T.string().uuid()}),zo=T.object({status:T.enum(Ho).optional(),limit:T.coerce.number().min(1).max(100).default(100),offset:T.coerce.number().min(0).default(0)}),Qo=T.object({limit:T.coerce.number().min(1).max(200).default(50),offset:T.coerce.number().min(0).default(0)});async function Tn(o){o.post("/chat/sessions",{schema:{tags:["Chat"],summary:"Create a chat session",body:{type:"object",required:["source"],properties:{source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"}}}}},async(t,r)=>{let s=Ko.safeParse(t.body);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let{source:n,roleId:a}=s.data,i=$e(n,a);return r.status(201).send({session:i})}),o.get("/chat/sessions",{schema:{tags:["Chat"],summary:"List chat sessions",querystring:{type:"object",properties:{status:{type:"string",enum:["active","archived"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(t,r)=>{let s=zo.safeParse(t.query);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let{status:n}=s.data;return{sessions:zs(n)}}),o.get("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Get chat session with messages",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,r)=>{let s=Oe.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let n=H(s.data.id);if(!n)return r.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=It(n.id);return{session:n,messages:a}}),o.post("/chat/sessions/:id/archive",{schema:{tags:["Chat"],summary:"Archive a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,r)=>{let s=Oe.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let n=H(s.data.id);return n?(Gs(n.id),{sessionId:n.id,status:"archived"}):r.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.post("/chat/sessions/:id/restore",{schema:{tags:["Chat"],summary:"Restore an archived session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,r)=>{let s=Oe.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let n=Hs(s.data.id);return n?{session:n}:r.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.delete("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Delete a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,r)=>{let s=Oe.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let n=H(s.data.id);return n?(Ks(n.id),r.status(204).send()):r.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.get("/chat/sessions/:id/messages",{schema:{tags:["Chat"],summary:"Get messages for a session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(t,r)=>{let s=Oe.safeParse(t.params);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let n=H(s.data.id);if(!n)return r.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=Qo.safeParse(t.query),{limit:i=50,offset:c=0}=a.success?a.data:{};return{messages:It(n.id,i,c)}});let e=T.object({content:T.string().min(1,"content is required"),source:T.object({type:T.enum(["tui","web","api","channel"]),channelId:T.string().optional(),chatId:T.string().optional()}),roleId:T.string().optional(),sessionId:T.string().uuid().optional()});o.post("/chat/messages",{schema:{tags:["Chat"],summary:"Send a chat message",description:"Send a message. Creates a session if no active session exists for the source. Returns sessionId, messageId, and response.",body:{type:"object",required:["content","source"],properties:{content:{type:"string",minLength:1},source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"},sessionId:{type:"string"}}}}},async(t,r)=>{let s=e.safeParse(t.body);if(!s.success)return r.status(400).send({code:"VALIDATION_ERROR",message:T.prettifyError(s.error)});let{content:n,source:a,roleId:i,sessionId:c}=s.data,l=await Ye(n,a,i,c);return r.status(201).send(l)})}var Yo=O("ws"),Ze=new Set,et=[],Jo=50;function Xo(o){et.push(o),et.length>Jo&&et.shift()}function Re(o){Xo(o);let e=JSON.stringify(o);for(let t of Ze)t.readyState===1&&t.send(e)}function wn(o){o.get("/chat/stream",{websocket:!0},(e,t)=>{Ze.add(e);for(let r of et)e.readyState===1&&e.send(JSON.stringify(r));e.on("close",()=>{Ze.delete(e)}),e.on("error",r=>{Yo.error({error:r},"Chat WebSocket error"),Ze.delete(e)})}),f.on("session_created",e=>Re(e)),f.on("session_archived",e=>Re(e)),f.on("session_restored",e=>Re(e)),f.on("session_deleted",e=>Re(e)),f.on("chat_message",e=>Re(e)),f.on("task_complete_event",e=>Re(e))}var B=O("channels"),tt=class{adapters=new Map;rateLimits=new Map;healthInterval;rateLimitPerMinute;constructor(e){this.rateLimitPerMinute=e?.rateLimitPerMinute??60}async addChannel(e,t){this.adapters.set(e.id,t),t.onMessage(r=>{this.handleInbound(e.id,r)}),e.enabled&&await this.connectChannel(e.id)}async removeChannel(e){let t=this.adapters.get(e);if(t){try{await t.disconnect()}catch(r){B.error({channelId:e,error:r},"Error disconnecting channel")}this.adapters.delete(e),this.rateLimits.delete(e)}}async connectChannel(e){let t=this.adapters.get(e);if(!t)throw new Error(`No adapter registered for channel ${e}`);try{be(e,"connecting"),await t.connect(),be(e,"connected"),B.info({channelId:e,platform:t.platform},"Channel connected")}catch(r){throw be(e,"error"),B.error({channelId:e,error:r},"Failed to connect channel"),r}}async disconnectChannel(e){let t=this.adapters.get(e);if(t)try{await t.disconnect(),be(e,"disconnected"),B.info({channelId:e},"Channel disconnected")}catch(r){B.error({channelId:e,error:r},"Error disconnecting channel")}}getChannelStatus(e){let t=this.adapters.get(e);return t?t.getStatus():"disconnected"}getChannelStatuses(){let e=new Map;for(let[t,r]of this.adapters)e.set(t,r.getStatus());return e}hasAdapter(e){return this.adapters.has(e)}async sendMessage(e,t,r){let s=this.adapters.get(e);if(!s)return B.warn({channelId:e},"No adapter for outbound message"),null;if(!this.checkRateLimit(e))return B.warn({channelId:e},"Rate limit exceeded, dropping outbound message"),null;try{return await s.sendMessage(t,r)}catch(n){return B.error({channelId:e,chatId:t,error:n},"Failed to send outbound message"),null}}checkRateLimit(e){let t=Date.now(),r=this.rateLimits.get(e);return!r||t-r.windowStart>=6e4?(this.rateLimits.set(e,{count:1,windowStart:t}),!0):r.count>=this.rateLimitPerMinute?!1:(r.count++,!0)}async handleInbound(e,t){if(t.source==="system"){B.debug({channelId:e},"Skipping system message (anti-loop)");return}try{let{isRecentlySent:s}=await import("./outbound-gateway-FIPC4BZO.js"),n=t.channelMessageId??t.raw?.MsgId??"";if(n&&s(String(n))){B.debug({channelId:e,messageId:n},"Skipping delivery-sent message (anti-loop)");return}}catch{}if(!this.checkRateLimit(e)){B.warn({channelId:e,senderId:t.senderId},"Rate limit exceeded for inbound message");return}try{let{handleInboundForApproval:s}=await import("./approval-handler-D3J6NCMM.js");if(await s(e,t.chatId,t.content)){B.debug({channelId:e,chatId:t.chatId},"Inbound message consumed as approval reply");return}}catch{}let r=$s(e);if(r?.allowedChatIds&&!r.allowedChatIds.includes(t.chatId)){B.debug({channelId:e,chatId:t.chatId},"Chat not in allowlist, ignoring");return}try{let s=await Ye(t.content,{type:"channel",channelId:e,chatId:t.chatId},r?.linkedRoleId);B.info({channelId:e,chatId:t.chatId,sessionId:s.sessionId},"Inbound message routed to session")}catch(s){B.error({channelId:e,chatId:t.chatId,error:s},"Failed to route inbound message")}}startHealthMonitor(e=3e4){this.stopHealthMonitor(),this.healthInterval=setInterval(()=>{this.checkHealth()},e)}stopHealthMonitor(){this.healthInterval&&(clearInterval(this.healthInterval),this.healthInterval=void 0)}checkHealth(){for(let[e,t]of this.adapters){let r=t.getStatus();try{be(e,r)}catch{}}}async startAll(){let e=We(!0);for(let t of e){let r=this.adapters.get(t.id);if(r&&r.getStatus()!=="connected")try{await this.connectChannel(t.id)}catch{}}this.startHealthMonitor()}async stopAll(){this.stopHealthMonitor();for(let e of this.adapters.keys())await this.disconnectChannel(e);this.adapters.clear(),this.rateLimits.clear()}_getAdapterCount(){return this.adapters.size}_getRateLimitEntry(e){return this.rateLimits.get(e)}};ke();var J=O("watchdog"),st=null;function Sn(o,e,t,r){if(!o.enabled){J.info("Watchdog disabled");return}let s=o.intervalMinutes*6e4;J.info({intervalMinutes:o.intervalMinutes},"Watchdog started"),st=setInterval(()=>{Zo(o,e,t,r)},s)}function Cn(){st&&(clearInterval(st),st=null,J.info("Watchdog stopped"))}function Zo(o,e,t,r){let{rules:s}=o;if(s.managerHealthCheck.enabled){let n=s.managerHealthCheck.staleDurationMinutes*6e4,a=e.getLastActivityAt();if(Date.now()-a>n){let i=`ChatManager session stale (no activity for ${s.managerHealthCheck.staleDurationMinutes} min)`;if(J.warn(i),s.managerHealthCheck.action==="restart"){let c=e.getConsecutiveStaleCount()>0;e.restartSession(),c&&(J.fatal("ChatManager unrecoverable after session restart \u2014 exiting for supervisor restart"),process.exit(1))}else s.managerHealthCheck.action==="notify"&&r(i)}}if(!t.isHealthy()){let n="ExecutionPool is not healthy (stopped unexpectedly)";J.warn(n),r(n)}if(s.staleTasks.enabled){let n=s.staleTasks.maxPendingMinutes*6e4,i=M("pending").filter(c=>Date.now()-c.createdAt>n);if(i.length>0){let c=`${i.length} stale task(s) pending > ${s.staleTasks.maxPendingMinutes} min`;J.warn({count:i.length},c),s.staleTasks.action==="notify"&&r(c)}}if(s.staleRunningTasks?.enabled){let n=s.staleRunningTasks.maxRunningMinutes*6e4,i=M("running").filter(c=>{if(!c.startedAt||Date.now()-c.startedAt<n)return!1;try{let h=L().prepare("SELECT MAX(timestamp) as latest FROM step_logs WHERE task_id = ?").get(c.id)?.latest??c.startedAt;return Date.now()-h>n}catch{return!0}});if(i.length>0){let c=`${i.length} task(s) running with no activity for > ${s.staleRunningTasks.maxRunningMinutes} min \u2014 marking as failed`;J.warn({count:i.length,taskIds:i.map(l=>l.id)},c);for(let l of i)G(l.id,{status:"failed",error:`Watchdog timeout: no activity for > ${s.staleRunningTasks.maxRunningMinutes} min`,completedAt:Date.now()}),f.emit({type:"task_status_change",taskId:l.id,oldStatus:"running",newStatus:"failed"}),t.releaseSlot(l.id);r(c)}}if(s.dbMaintenance.enabled)try{let a=L().pragma("wal_checkpoint(PASSIVE)");J.debug({walSize:a},"WAL checkpoint")}catch(n){J.error({error:n},"DB health check failed")}}import{z as j}from"zod";import{v4 as ea}from"uuid";var ta=j.object({eventType:j.enum(["task_complete","task_error","plan_approval_request","*"]),matchCriteria:j.object({templateId:j.string().optional(),roleId:j.string().optional(),promptPattern:j.string().optional(),taskStatus:j.string().optional()}).optional().default({}),target:j.object({type:j.enum(["channel","webhook"]),channelId:j.string().optional(),chatId:j.string().optional(),webhookUrl:j.string().optional()}),formatTemplate:j.string().optional(),maxPerMinute:j.number().int().min(1).max(60).optional().default(5),skipOriginChannel:j.boolean().optional().default(!0),enabled:j.boolean().optional().default(!0)});async function Vt(o){o.get("/delivery-rules",async(e,t)=>ur()),o.post("/delivery-rules",async(e,t)=>{let r=ta.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:j.prettifyError(r.error)});let s=r.data,n={id:ea(),eventType:s.eventType,matchCriteria:s.matchCriteria,target:s.target,formatTemplate:s.formatTemplate,maxPerMinute:s.maxPerMinute,skipOriginChannel:s.skipOriginChannel,enabled:s.enabled,createdAt:Date.now()};return pr(n),t.status(201).send(n)}),o.put("/delivery-rules/:id",async(e,t)=>{if(!Ve(e.params.id))return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let s=e.body;return mr(e.params.id,s),{id:e.params.id,updated:!0}}),o.delete("/delivery-rules/:id",async(e,t)=>Ve(e.params.id)?(gr(e.params.id),{id:e.params.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"})),o.get("/delivery-rules/:id/log",async(e,t)=>ps(e.params.id)),o.post("/delivery-rules/:id/test",async(e,t)=>{let r=Ve(e.params.id);if(!r)return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let{getDeliveryEngine:s}=await import("./engine-V5MOGOLN.js"),n=s();if(!n)return t.status(503).send({code:"ENGINE_NOT_READY",message:"DeliveryEngine not initialized"});let a=`[TEST] Delivery rule test at ${new Date().toISOString()}`,{createDeliveryLog:i}=await import("./delivery-log-VYTYUFCK.js"),{v4:c}=await import("uuid"),{TTL_MS:l}=await import("./delivery-log-VYTYUFCK.js"),d={id:c(),ruleId:r.id,status:"pending",target:r.target,content:a,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+l};i(d);try{return await n.attemptDeliveryPublic(d,r),{id:d.id,ruleId:r.id,status:"sent",content:a}}catch(m){let h=m instanceof Error?m.message:String(m);return t.status(500).send({code:"DELIVERY_FAILED",message:h,logId:d.id})}})}de();de();import{existsSync as rt,copyFileSync as sa,mkdirSync as Gt,cpSync as ra}from"fs";import{join as X}from"path";function Ht(){Gt(A,{recursive:!0}),Gt(X(A,"logs"),{recursive:!0}),Gt(X(A,".claude"),{recursive:!0})}function Pn(o=process.cwd()){Ht();let e=[],t=[{from:X(o,"data","adam.db"),to:X(A,"adam.db"),label:"database"},{from:X(o,"adam.config.yaml"),to:X(A,"adam.config.yaml"),label:"config"},{from:X(o,".env"),to:X(A,".env"),label:".env"}];for(let{from:n,to:a,label:i}of t)rt(n)&&!rt(a)&&(sa(n,a),e.push(i));let r=X(o,".claude","plugins"),s=X(A,".claude","plugins");return rt(r)&&!rt(s)&&(ra(r,s,{recursive:!0}),e.push("plugins")),e}var P=O("adam");function oa(o){let e={...o};if(e.defaults&&typeof e.defaults=="object"){let t={...e.defaults};if(t.env&&typeof t.env=="object"){let r={...t.env};for(let s of Object.keys(r))r[s]&&(r[s]=r[s].slice(0,4)+"****");t.env=r}e.defaults=t}if(e.server&&typeof e.server=="object"){let t={...e.server};t.apiKey&&typeof t.apiKey=="string"&&(t.apiKey=t.apiKey.slice(0,4)+"****"),e.server=t}return e}async function aa(){Ht();let o=Pn();o.length>0&&console.log(`[adam] Migrated to ~/.adam/: ${o.join(", ")}`);let e=Er();P.info("Starting Adam Agent Server"),e.length>0&&P.info({files:e},"Loaded env files");let t=ts();Jt(t),U().anthropic?.apiKey||process.env.ANTHROPIC_API_KEY||P.warn("ANTHROPIC_API_KEY not set \u2014 configure via Settings UI or ~/.adam/.env"),process.env.ANTHROPIC_BASE_URL&&P.info({url:process.env.ANTHROPIC_BASE_URL},"Using custom API base URL");let s=t.defaults?.claudeCodePath;try{if(!s){let{createRequire:re}=await import("module"),{dirname:x,join:N}=await import("path"),Fe=re(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");s=N(x(Fe),"cli.js")}let{execSync:v}=await import("child_process"),V=v(`"${s}" --version`,{timeout:5e3,encoding:"utf-8"}).trim();P.info({path:s,version:V},"Claude Code CLI detected")}catch(v){let V=v;V.code==="ENOENT"?P.warn({path:s},"Claude Code CLI not found. Task execution will fail. Install: npm i -g @anthropic-ai/claude-code"):P.warn({path:s,error:(V.stderr?.trim()||String(v)).slice(0,200)},"Claude Code CLI check failed")}let a=L().prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();P.info({tables:a.map(v=>v.name).join(", ")},"Database initialized");let i=ss(),c=Ir(i);c>0&&P.info({count:c},"Seeded config DB from .env");let{getAllConfig:l}=await import("./config-WHXCZCI4.js");Ne(l);let d=U();d.logging?.level&&Me(d.logging.level),P.info({config:oa(d)},"Config loaded (DB + defaults)");let m=Dt(),{getToolsFingerprint:h}=await import("./adam-tools-Q4BRKX3U.js"),I=h(),y=m.sdkSessionId;if(y&&m.toolsFingerprint!==I&&(P.info({old:m.toolsFingerprint?.slice(0,40),new:I.slice(0,40)},"MCP tools changed \u2014 invalidating old SDK session"),Gr(),y=void 0),Se({toolsFingerprint:I}),y){let v=process.cwd();m.workspacePath&&m.workspacePath!==v&&(P.warn({serverCwd:v,saved:m.workspacePath},"Workspace mismatch"),P.warn("SDK session may not resume correctly due to cwd mismatch")),P.info({sessionId:y.slice(0,8)},"Recovering manager SDK session")}else P.info("No previous manager SDK session found, starting fresh");m.userTaskSessionId&&P.info({sessionId:m.userTaskSessionId.slice(0,8)},"Recovering user task session"),Hr(process.cwd());let{initializeDefaultRoles:g}=await import("./role-presets-FN2RWUCP.js"),C=g();P.info({count:C.length},"Roles initialized");let oe=U().execution??{maxConcurrent:3,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},$=new _e(y),ae=new xe(oe.maxConcurrent);mn($),await $.start(),await ae.start();let Ie=M("running");if(Ie.length>0){P.warn({count:Ie.length},"Found orphaned running tasks from previous session \u2014 marking as failed");for(let v of Ie)G(v.id,{status:"failed",error:"Server restarted while task was running",completedAt:Date.now()})}let _=Or(t,t.server.apiKey);await _.register(v=>Lr(v)),await _.register(v=>Mr(v,t)),await _.register(v=>Wr(v,t.server.apiKey)),await _.register(Yr),await _.register(rn),await _.register(vn),await _.register(Rn);let ie=new Us;Ws(ie),await ie.start(),Ar(),await _.register(v=>fn(v,ie)),await _.register(yn),await _.register(v=>hn(v,ie,process.env.ADAM_WEBHOOK_API_KEY)),await _.register(In),await _.register(kn),await _.register(Tn);let me=new tt;br(me),await _.register(vr),await _.register(wn),await _.register(v=>Vr(v,t.server.apiKey)),await _.register(sn),await _.register(Vt),Qs(),Pr(),kr(),me.startHealthMonitor();try{let v=We();for(let V of v)if(V.platform==="wechat"){let re=V.config;if(re.botToken){let x=new hr(V.id,re);me.addChannel(V,x)}}}catch(v){P.error({error:v},"Failed to register WeChat adapters at startup")}let{host:ge,port:fe}=t.server;await _.listen({host:ge,port:fe}),P.info({host:ge,port:fe},"Server listening");let ot=t.watchdog??es.watchdog;Sn(ot,$,ae,v=>{P.warn({alert:v},"Watchdog alert")}),cs(v=>{f.emit({type:"log_event",timestamp:v.time??Date.now(),level:v.level??"info",component:v.component??"adam",msg:v.msg??""})}),An(A,{recursive:!0}),An(nt(A,"logs"),{recursive:!0}),_n(nt(A,"adam.port"),String(fe)),t.server.apiKey&&_n(nt(A,"adam.key"),t.server.apiKey,{mode:384}),process.send?.({type:"ready",port:fe});let ce=async()=>{P.info("Shutting down"),Cn(),Tr(),Ys(),_r(),await me.stopAll(),$.stop(),ae.stop(),await ie.stop(),await _.close(),dt();try{na(nt(A,"adam.key"))}catch{}process.exit(0)};process.on("SIGINT",()=>{ce()}),process.on("SIGTERM",()=>{ce()})}aa().catch(o=>{P.fatal(o,"Fatal error"),process.exit(1)});