agentix-cli 0.133.0 → 0.134.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 (148) hide show
  1. package/dist/{App-WQPA77VJ.js → App-4UVAI5C5.js} +2 -2
  2. package/dist/{ChatApp-TGW66I4Y.js → ChatApp-COO67WIR.js} +2 -2
  3. package/dist/absorb-eval-WU7JR3BT.js +2 -0
  4. package/dist/{agent-FWHYHXWC.js → agent-2GPJGHHG.js} +2 -2
  5. package/dist/{board-dashboard-GKE4KWJH.js → board-dashboard-PUQPL4AX.js} +24 -8
  6. package/dist/board-dashboard-PUQPL4AX.js.map +1 -0
  7. package/dist/{chunk-ZN5DC6WS.js → chunk-3XVST5XX.js} +2 -2
  8. package/dist/{note-reader-LPPIYYLT.js → chunk-4LWFJ4MZ.js} +3 -3
  9. package/dist/{note-reader-LPPIYYLT.js.map → chunk-4LWFJ4MZ.js.map} +1 -1
  10. package/dist/{chunk-F5PVUB4Y.js → chunk-4XMALK7X.js} +2 -2
  11. package/dist/{chunk-VH2ASPFQ.js → chunk-AHO4CQRK.js} +2 -2
  12. package/dist/chunk-DDEDSYLF.js +105 -0
  13. package/dist/chunk-DDEDSYLF.js.map +1 -0
  14. package/dist/{chunk-2BF6HJJD.js → chunk-DYGQF3MI.js} +4 -4
  15. package/dist/chunk-DYGQF3MI.js.map +1 -0
  16. package/dist/{chunk-JA5Y4LDP.js → chunk-ERULJ2ZL.js} +2 -2
  17. package/dist/chunk-FEEXOWK5.js +41 -0
  18. package/dist/chunk-FEEXOWK5.js.map +1 -0
  19. package/dist/{chunk-RJFPCW7T.js → chunk-FWDRBUMS.js} +2 -2
  20. package/dist/chunk-G4HDRJVN.js +87 -0
  21. package/dist/chunk-G4HDRJVN.js.map +1 -0
  22. package/dist/{chunk-KUOH5MFS.js → chunk-K445URSN.js} +2 -2
  23. package/dist/{chunk-D5IHICX3.js → chunk-LUYN6RAC.js} +2 -2
  24. package/dist/{chunk-4NEO5KB2.js → chunk-MM3F74K4.js} +15 -15
  25. package/dist/{chunk-4NEO5KB2.js.map → chunk-MM3F74K4.js.map} +1 -1
  26. package/dist/{chunk-F7GKG5ZO.js → chunk-NXRSIWQA.js} +3 -3
  27. package/dist/chunk-NXRSIWQA.js.map +1 -0
  28. package/dist/chunk-NZQBS7GN.js +2 -0
  29. package/dist/{chunk-KBJNJGBP.js.map → chunk-NZQBS7GN.js.map} +1 -1
  30. package/dist/{chunk-3TETB22A.js → chunk-P3I7AATX.js} +2 -2
  31. package/dist/{chunk-V4IFJLQS.js → chunk-RDEFA6Y6.js} +2 -2
  32. package/dist/{chunk-HIUHKOKK.js → chunk-RJOA7QBB.js} +2 -2
  33. package/dist/{chunk-GZY5DYXT.js → chunk-RRGITX5B.js} +2 -2
  34. package/dist/{chunk-IDZXAOBC.js → chunk-SFVDQNTY.js} +67 -67
  35. package/dist/chunk-SFVDQNTY.js.map +1 -0
  36. package/dist/{chunk-GUEIF7ZF.js → chunk-SMAI7U6H.js} +2 -2
  37. package/dist/{chunk-S2UXDEGW.js → chunk-SSQMFHSM.js} +2 -2
  38. package/dist/{chunk-PHCWYKQW.js → chunk-TDGDH4RA.js} +2 -2
  39. package/dist/chunk-URN74FTP.js +55 -0
  40. package/dist/chunk-URN74FTP.js.map +1 -0
  41. package/dist/{chunk-4XPVU3N2.js → chunk-VQYVL72V.js} +2 -2
  42. package/dist/{chunk-ANC5QXFB.js → chunk-XOUO4XNA.js} +2 -2
  43. package/dist/{chunk-OQV3LWJI.js → chunk-XWO6ALJQ.js} +2 -2
  44. package/dist/{chunk-SJPQQ4OF.js → chunk-YSXE65O7.js} +234 -234
  45. package/dist/chunk-YSXE65O7.js.map +1 -0
  46. package/dist/cli.js +1 -1
  47. package/dist/{client-7UW2ELPP.js → client-NFPBE6L4.js} +2 -2
  48. package/dist/{config-TNYVPT4R.js → config-GHMRBRDL.js} +2 -2
  49. package/dist/{config-mutate-GV7BVG3I.js → config-mutate-2XV27EFV.js} +2 -2
  50. package/dist/config-mutator-6ITNU5DT.js +2 -0
  51. package/dist/{contributions-J57B3KIX.js → contributions-74M6YOCZ.js} +2 -2
  52. package/dist/{contributions-J57B3KIX.js.map → contributions-74M6YOCZ.js.map} +1 -1
  53. package/dist/{doctor-ROKIYJRT.js → doctor-UBXVMGJG.js} +2 -2
  54. package/dist/{follow-up-tool-S2U7DFSW.js → follow-up-tool-EARVITTS.js} +2 -2
  55. package/dist/{hub-HOVJC4HR.js → hub-VTDFUAEH.js} +2 -2
  56. package/dist/index.d.ts +279 -84
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/note-reader-IDE6RI34.js +2 -0
  60. package/dist/notes-settings-VPXI5IIS.js +2 -0
  61. package/dist/{program-LAOU5DQ3.js → program-3URNCVEZ.js} +254 -254
  62. package/dist/program-3URNCVEZ.js.map +1 -0
  63. package/dist/{promote-FVWRM4BE.js → promote-B2BADAEP.js} +2 -2
  64. package/dist/push-bridge-325SXDGN.js +1 -1
  65. package/dist/query-2VIIGGDS.js +2 -0
  66. package/dist/query-settings-VJ3POZS3.js +3 -0
  67. package/dist/query-settings-VJ3POZS3.js.map +1 -0
  68. package/dist/registry-PRCISYBO.js +2 -0
  69. package/dist/{request-planner-JOXSAAHO.js → request-planner-MFAIVLUQ.js} +2 -2
  70. package/dist/{review-candidates-6N5435V7.js → review-candidates-6WMDVVIZ.js} +2 -2
  71. package/dist/{routing-6G2QVFIG.js → routing-OPCLHIYW.js} +2 -2
  72. package/dist/schedule-tool-KPVTMYL3.js +2 -0
  73. package/dist/{scheduler-WOH2O3EP.js → scheduler-G3WWYETY.js} +2 -2
  74. package/dist/{seat-I2FBJDTV.js → seat-3HM4J7IX.js} +2 -2
  75. package/dist/{select-5YZQJLLD.js → select-VEFE2ESF.js} +2 -2
  76. package/dist/{set-enabled-CQEUZLHU.js → set-enabled-US5BYKFZ.js} +2 -2
  77. package/dist/{tool-PIJXUBEC.js → tool-HUSCHORN.js} +2 -2
  78. package/dist/{tool-R77KFLZ3.js → tool-XLWLXGB5.js} +2 -2
  79. package/dist/wiki-SXWJ5NJQ.js +2 -0
  80. package/dist/wiki-SXWJ5NJQ.js.map +1 -0
  81. package/package.json +1 -1
  82. package/dist/absorb-eval-37XZJACN.js +0 -2
  83. package/dist/board-dashboard-GKE4KWJH.js.map +0 -1
  84. package/dist/chunk-2BF6HJJD.js.map +0 -1
  85. package/dist/chunk-57Y2WZT2.js +0 -55
  86. package/dist/chunk-57Y2WZT2.js.map +0 -1
  87. package/dist/chunk-BI6VG4DV.js +0 -37
  88. package/dist/chunk-BI6VG4DV.js.map +0 -1
  89. package/dist/chunk-F7GKG5ZO.js.map +0 -1
  90. package/dist/chunk-IDZXAOBC.js.map +0 -1
  91. package/dist/chunk-IZDKRNXC.js +0 -52
  92. package/dist/chunk-IZDKRNXC.js.map +0 -1
  93. package/dist/chunk-KBJNJGBP.js +0 -2
  94. package/dist/chunk-RTHZQGFC.js +0 -105
  95. package/dist/chunk-RTHZQGFC.js.map +0 -1
  96. package/dist/chunk-SJPQQ4OF.js.map +0 -1
  97. package/dist/config-mutator-AKCR3VKM.js +0 -2
  98. package/dist/notes-settings-WMOH2V75.js +0 -2
  99. package/dist/program-LAOU5DQ3.js.map +0 -1
  100. package/dist/query-HBCL3FHO.js +0 -2
  101. package/dist/query-settings-RD6GEN2V.js +0 -3
  102. package/dist/query-settings-RD6GEN2V.js.map +0 -1
  103. package/dist/registry-NT4H7HYP.js +0 -2
  104. package/dist/schedule-tool-3NYUPKSC.js +0 -2
  105. package/dist/wiki-GCOFERTB.js +0 -2
  106. /package/dist/{App-WQPA77VJ.js.map → App-4UVAI5C5.js.map} +0 -0
  107. /package/dist/{ChatApp-TGW66I4Y.js.map → ChatApp-COO67WIR.js.map} +0 -0
  108. /package/dist/{absorb-eval-37XZJACN.js.map → absorb-eval-WU7JR3BT.js.map} +0 -0
  109. /package/dist/{agent-FWHYHXWC.js.map → agent-2GPJGHHG.js.map} +0 -0
  110. /package/dist/{chunk-ZN5DC6WS.js.map → chunk-3XVST5XX.js.map} +0 -0
  111. /package/dist/{chunk-F5PVUB4Y.js.map → chunk-4XMALK7X.js.map} +0 -0
  112. /package/dist/{chunk-VH2ASPFQ.js.map → chunk-AHO4CQRK.js.map} +0 -0
  113. /package/dist/{chunk-JA5Y4LDP.js.map → chunk-ERULJ2ZL.js.map} +0 -0
  114. /package/dist/{chunk-RJFPCW7T.js.map → chunk-FWDRBUMS.js.map} +0 -0
  115. /package/dist/{chunk-KUOH5MFS.js.map → chunk-K445URSN.js.map} +0 -0
  116. /package/dist/{chunk-D5IHICX3.js.map → chunk-LUYN6RAC.js.map} +0 -0
  117. /package/dist/{chunk-3TETB22A.js.map → chunk-P3I7AATX.js.map} +0 -0
  118. /package/dist/{chunk-V4IFJLQS.js.map → chunk-RDEFA6Y6.js.map} +0 -0
  119. /package/dist/{chunk-HIUHKOKK.js.map → chunk-RJOA7QBB.js.map} +0 -0
  120. /package/dist/{chunk-GZY5DYXT.js.map → chunk-RRGITX5B.js.map} +0 -0
  121. /package/dist/{chunk-GUEIF7ZF.js.map → chunk-SMAI7U6H.js.map} +0 -0
  122. /package/dist/{chunk-S2UXDEGW.js.map → chunk-SSQMFHSM.js.map} +0 -0
  123. /package/dist/{chunk-PHCWYKQW.js.map → chunk-TDGDH4RA.js.map} +0 -0
  124. /package/dist/{chunk-4XPVU3N2.js.map → chunk-VQYVL72V.js.map} +0 -0
  125. /package/dist/{chunk-ANC5QXFB.js.map → chunk-XOUO4XNA.js.map} +0 -0
  126. /package/dist/{chunk-OQV3LWJI.js.map → chunk-XWO6ALJQ.js.map} +0 -0
  127. /package/dist/{client-7UW2ELPP.js.map → client-NFPBE6L4.js.map} +0 -0
  128. /package/dist/{config-TNYVPT4R.js.map → config-GHMRBRDL.js.map} +0 -0
  129. /package/dist/{config-mutate-GV7BVG3I.js.map → config-mutate-2XV27EFV.js.map} +0 -0
  130. /package/dist/{config-mutator-AKCR3VKM.js.map → config-mutator-6ITNU5DT.js.map} +0 -0
  131. /package/dist/{doctor-ROKIYJRT.js.map → doctor-UBXVMGJG.js.map} +0 -0
  132. /package/dist/{follow-up-tool-S2U7DFSW.js.map → follow-up-tool-EARVITTS.js.map} +0 -0
  133. /package/dist/{hub-HOVJC4HR.js.map → hub-VTDFUAEH.js.map} +0 -0
  134. /package/dist/{notes-settings-WMOH2V75.js.map → note-reader-IDE6RI34.js.map} +0 -0
  135. /package/dist/{promote-FVWRM4BE.js.map → notes-settings-VPXI5IIS.js.map} +0 -0
  136. /package/dist/{query-HBCL3FHO.js.map → promote-B2BADAEP.js.map} +0 -0
  137. /package/dist/{registry-NT4H7HYP.js.map → query-2VIIGGDS.js.map} +0 -0
  138. /package/dist/{routing-6G2QVFIG.js.map → registry-PRCISYBO.js.map} +0 -0
  139. /package/dist/{request-planner-JOXSAAHO.js.map → request-planner-MFAIVLUQ.js.map} +0 -0
  140. /package/dist/{review-candidates-6N5435V7.js.map → review-candidates-6WMDVVIZ.js.map} +0 -0
  141. /package/dist/{schedule-tool-3NYUPKSC.js.map → routing-OPCLHIYW.js.map} +0 -0
  142. /package/dist/{scheduler-WOH2O3EP.js.map → schedule-tool-KPVTMYL3.js.map} +0 -0
  143. /package/dist/{seat-I2FBJDTV.js.map → scheduler-G3WWYETY.js.map} +0 -0
  144. /package/dist/{wiki-GCOFERTB.js.map → seat-3HM4J7IX.js.map} +0 -0
  145. /package/dist/{select-5YZQJLLD.js.map → select-VEFE2ESF.js.map} +0 -0
  146. /package/dist/{set-enabled-CQEUZLHU.js.map → set-enabled-US5BYKFZ.js.map} +0 -0
  147. /package/dist/{tool-PIJXUBEC.js.map → tool-HUSCHORN.js.map} +0 -0
  148. /package/dist/{tool-R77KFLZ3.js.map → tool-XLWLXGB5.js.map} +0 -0
@@ -1,55 +0,0 @@
1
- import{a as H,b as G,c as V}from"./chunk-IZDKRNXC.js";import{a as j,b as I,c as T,d as N,e as Y,j as B}from"./chunk-JA5Y4LDP.js";import{a as F}from"./chunk-7VLLZQ3N.js";import{y as D,z as at}from"./chunk-F5PVUB4Y.js";import{g as Q}from"./chunk-6TURWSMN.js";import{b as W,c as E}from"./chunk-QOYAX2FT.js";import{readFileSync as it,existsSync as K}from"fs";at();import{resolve as R}from"path";import{execSync as st}from"child_process";var ot=.8;function lt(e,r,l,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(o=>o.path).filter(o=>!o.includes("/_versions/"));return c.length===0&&(c=l.sharedPool.map(o=>o.path)),c.length===0?0:c.filter(o=>t.has(o)).length/c.length}async function vt(e,r,l,t={}){let c=t.selectorModel??"haiku",o=t.synthModel??"sonnet",p=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,a=t.timeoutMs??6e4,i=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??v,s=R(r.baseDir,"_index.md"),m=X(r,l,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=G(r,t.shared);if(b==="summaries"||lt(r,l,m,u)>=ot){let f=t.summaries??H,w=await V(e,m,u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??F,fetch:t.fetch,timeoutMs:a,log:i}),P=w.picked.map(y=>({title:y.meta.title,path:y.path,type:y.meta.type,hop:y.hop}));return{answer:w.answer,citations:w.status==="ok"?P.map(({title:y,path:$,type:nt})=>({title:y,path:$,type:nt})):[],candidates:P.filter(y=>y.hop===0).map(({title:y,path:$})=>({title:y,path:$})),walked:P,status:w.status,method:"summaries",live:w.live,liveAsked:w.liveAsked,trace:w.trace,...w.error?{error:w.error}:{}}}}if(!K(s)&&m.sharedPool.length===0)return x("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let et=(K(s)?it(s,"utf-8"):"")+dt(e,m.sharedPool,h,n),_=Date.now(),A=[],S="";try{let u=await q(e,m.pool,l,p,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await z(mt(e,et,p,h),c,a),A=ut(S))}catch(u){return i("selector failed:",u?.message),{...x("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-_,synthesisMs:0,selectorOutput:S}}}let M=Date.now()-_;if(A.length===0)return{...x("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:M,synthesisMs:0,selectorOutput:S}};let C=Z(A,m,g,d);if(C.length===0)return{...x("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:M,synthesisMs:0,selectorOutput:S}};let O=Date.now(),U="";try{U=await z(gt(e,C),o,a*2)}catch(u){return i("synthesis failed:",u?.message),{...x("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:M,synthesisMs:Date.now()-O,selectorOutput:S}}}let rt=Date.now()-O;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:M,synthesisMs:rt,selectorOutput:S}}}async function Pt(e,r,l,t={}){let c=t.maxCandidates??3,o=t.graphWeight??v,p=t.messagePath?.length?t.messagePath:void 0,g=t.pool??J(r);if(g.length===0||!e.trim())return[];let d=await q(e,g,l,c,p,o,t.stage??"retrieve");if(!d){let a=new Set(E(e,W(g.map(tt))).map(i=>i.docIndex));d=L(e,g,p,o).filter(i=>a.has(i)).slice(0,c).map(i=>({title:g[i].title,path:g[i].path}))}return d.length===0?[]:Z(d,X(r,l),t.maxHops??1,t.maxArticles??6)}function J(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function x(e,r,l){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:l}}function X(e,r,l=[]){let t=new Map,c=[];for(let a of e.listArticles(r||""))t.set(a.meta.title.toLowerCase(),a.path),c.push({path:a.path,related:a.meta.related??[],lastUpdated:a.meta.lastUpdated??""});let o=[],p=new Map;for(let a of l)if(a.store.baseDir!==e.baseDir){p.set(a.id,a);for(let i of a.store.listArticles(r||"")){if(i.path.includes("/_versions/")||a.skip?.(i.path))continue;let h=`@${a.id}/${i.path}`;o.push(ct(i,h)),c.push({path:h,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let n=i.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(p.size>0)for(let a of[...c].sort((i,h)=>h.lastUpdated.localeCompare(i.lastUpdated)))for(let i of a.related){let h=i.toLowerCase(),n=g.get(h)??[];n.includes(a.path)||n.push(a.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(a=>a.path)),get pool(){return d??=[...J(e),...o]},sharedPool:o,titleIndex:t,read(a){let i=a.match(/^@([^/]+)\/(.+)$/),h=i?p.get(i[1]):void 0;if(i&&!h)return null;let n=h?.store??e,s=i?i[2]:a,m=r?n.readArticleAs(s,r):n.readArticle(s);return m?{...m,path:a}:null}}}function ct(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(l=>l.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ht=150;function dt(e,r,l,t){return r.length===0?"":`
2
-
3
- ## Shared wiki (other agents' articles)
4
-
5
- ${L(e,r,l,t).slice(0,ht).map(o=>`- ${r[o].title}${r[o].type?` [${r[o].type}]`:""} (${r[o].path})`).join(`
6
- `)}
7
- `}var pt=3;function Z(e,r,l,t){let c=r.titleIndex,o=n=>n.startsWith("@"),p=[...e.filter(n=>!o(n.path)),...e.filter(n=>o(n.path))],g=p.length>0&&!o(p[0].path)?Math.floor(t/2):t,d=new Map,a=0,i=p.map(n=>({path:n.path,hop:0})),h=[];for(;d.size<t;){if(!i.length){if(!h.length||g>=t)break;g=t,i=h.splice(0)}let n=i.shift();if(d.has(n.path)||n.hop>l)continue;if(o(n.path)&&a>=g){h.push(n);continue}let s=r.read(n.path);if(s&&(d.set(n.path,{...s,hop:n.hop}),o(n.path)&&a++,!(n.hop>=l))){if(n.hop===0){let m=[s.meta.title,...s.meta.aliases??[]].map(k=>k.toLowerCase()),b=[...new Set(m.flatMap(k=>r.backlinks.get(k)??[]))].filter(k=>k!==n.path&&!d.has(k)).slice(0,pt);for(let k of b)i.push({path:k,hop:1})}for(let m of s.meta.related||[]){let b=c.get(m.toLowerCase());b&&!d.has(b)&&i.push({path:b,hop:n.hop+1})}}}return Array.from(d.values())}async function q(e,r,l,t,c,o=v,p="catalog-selector"){try{if(r.length<2)return null;let d=L(e,r,c,o).slice(0,I).map(n=>({id:`k${n}`,title:r[n].title||r[n].path,tags:r[n].tags,excerpt:[r[n].type?`type: ${r[n].type}`:"",(r[n].related??[]).length?`related: ${(r[n].related??[]).join(", ")}`:"",(r[n].graphPath??[]).length?`graph: ${(r[n].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),a=await D(j,T({query:e,candidates:d,excerptChars:300}),N(d),{features:{agent:l??"unknown",stage:p}});if(!a||a.mode!=="active")return null;let h=Y(a.answers,d).ranked.slice(0,t).map(n=>r[Number(n.slice(1))]).filter(Boolean).map(n=>({title:n.title,path:n.path}));return h.length>0?h:null}catch{return null}}var v=.6;function L(e,r,l,t=v){let c=E(e,W(r.map(tt))),o=c.reduce((s,m)=>Math.max(s,m.score),0),p=new Map(c.map(s=>[s.docIndex,o>0?s.score/o:0])),g=!!l?.length,d=s=>g&&s.graphPath?.length?B(l,s.graphPath):0,a=(s,m)=>m.score-s.score||s.i-m.i,i=r.map((s,m)=>({i:m,score:(p.get(m)??0)*(1+t*d(s))})).filter(s=>p.has(s.i)).sort(a),h=r.map((s,m)=>({i:m,score:d(s)})).filter(s=>!p.has(s.i)&&s.score>0).sort(a),n=[...i,...h].map(s=>s.i);for(let s=0;s<r.length;s++)n.includes(s)||n.push(s);return n}function tt(e){return[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")}function mt(e,r,l,t){let c=t?.length?`
8
- ## Intent
9
-
10
- The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
11
- `:"";return`You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.
12
-
13
- ## Question
14
-
15
- ${e}
16
- ${c}
17
- ## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
18
-
19
- ${r}
20
-
21
- ## Your task
22
-
23
- Pick up to ${l} articles from the catalog that are most likely to answer the question. Prefer:
24
- - Articles whose title directly names a subject in the question.
25
- - Articles of the right type (e.g. a "who owns X" question \u2192 person or project; a "what happened on DATE" \u2192 event).
26
- - Articles whose wikilinks suggest they sit at the center of a relevant subgraph.
27
-
28
- Return ONLY valid JSON, no markdown fencing, no prose:
29
-
30
- [
31
- {"title": "Exact Article Title", "path": "path/from/catalog.md"},
32
- ...
33
- ]
34
-
35
- If none of the articles match, return [].`}function gt(e,r){let l=r.map(t=>{let c=[t.meta.owner?`owner: ${t.meta.owner}`:"",t.meta.lastUpdated?`updated: ${t.meta.lastUpdated}`:""].filter(Boolean).join(", "),o=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]${c?` {${c}}`:""}`,p=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[o,p,"",t.content].filter(Boolean).join(`
36
- `)}).join(`
37
-
38
- ---
39
-
40
- `);return`You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.
41
-
42
- ## Question
43
-
44
- ${e}
45
-
46
- ## Articles (${r.length} walked from the catalog)
47
-
48
- ${l}
49
-
50
- ## Your task
51
-
52
- Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
53
-
54
- Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function ut(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let l=JSON.parse(r[0]);return Array.isArray(l)?l.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function z(e,r,l){let{writeFileSync:t,mkdirSync:c,rmSync:o}=await import("fs"),{tmpdir:p}=await import("os"),g=R(p(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let a=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,i=st(a,{env:Q(),encoding:"utf-8",timeout:l,maxBuffer:4*1024*1024});try{let h=JSON.parse(i);return String(h.result||h.content||"")}catch{return i}}finally{try{o(d,{force:!0})}catch{}}}async function $t(e){try{let{loadDaemonConfig:r}=await import("./config-TNYVPT4R.js");return r(e).wiki.query.shared}catch{return!0}}export{ot as a,vt as b,Pt as c,J as d,ht as e,v as f,L as g,$t as h};
55
- //# sourceMappingURL=chunk-57Y2WZT2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { claudeCliEnv } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle, WikiIndex } from \"./types\"\nimport type { WikiStore } from \"./store\"\nimport { claudeModelCall, type ModelCall } from \"./model-call\"\nimport type { FetchLike, LiveLine } from \"./live-read\"\nimport { DEFAULT_SUMMARIES_QUERY, collectSummaries, summariesQuery, type SummariesQuerySettings } from \"./query-summaries\"\nimport type { QueryMethod } from \"./query-settings\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n /** Other wikis to search besides `store`: the shared wiki (#824). Only\n * articles the requester may read are offered. Their paths come back\n * as `@<id>/<path>`. */\n shared?: SharedWikiStore[]\n /** How pages are picked (#855). `summaries`: from the one-line page\n * summaries, then a live read (query-summaries.ts). `auto`: that, once\n * most of the requester's own pages have a summary\n * (AUTO_SUMMARY_COVERAGE). Default \"catalog\". */\n method?: QueryMethod\n /** Settings of the summaries method. An explicit `selectorModel` or\n * `synthModel` overrides its models. */\n summaries?: SummariesQuerySettings\n /** Model call and HTTP GET of the summaries method; tests pass their own. */\n call?: ModelCall\n fetch?: FetchLike\n}\n\n/** Share of the requester's own pages that must have a summary before\n * `auto` picks pages from summaries. Below it, an unsummarised page\n * would be ranked on its title and tags alone, so the catalog walk is\n * kept: one `wiki summarize --agent <id>` or `--limit` run must not\n * switch every agent that can read that store. */\nexport const AUTO_SUMMARY_COVERAGE = 0.8\n\n/** Share of the pages in reach that have a summary: the requester's own\n * pages, or the shared pages when the requester has none. */\nfunction summaryCoverage(store: WikiStore, requesterId: string | undefined, view: ScopeView, summaries: Map<string, string>): number {\n if (summaries.size === 0) return 0\n let paths = store.listArticles(requesterId || \"\").map((a) => a.path).filter((p) => !p.includes(\"/_versions/\"))\n if (paths.length === 0) paths = view.sharedPool.map((e) => e.path)\n if (paths.length === 0) return 0\n return paths.filter((p) => summaries.has(p)).length / paths.length\n}\n\n/** A wiki searched alongside the requester's own. */\nexport interface SharedWikiStore {\n /** Shown in citations as `@<id>/<path>`: an agent id, or \"shared\". */\n id: string\n store: WikiStore\n /** Paths to leave out, e.g. the agents/ tree under the root store. */\n skip?: (path: string) => boolean\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** How the pages were picked. */\n method?: \"summaries\" | \"catalog\"\n /** Lines read at the source for this answer (summaries method). */\n live?: LiveLine[]\n /** Live reads the model named and the config allowed. */\n liveAsked?: number\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n planMs?: number\n liveMs?: number\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n const view = scopeView(store, requesterId, opts.shared)\n\n const method = opts.method ?? \"catalog\"\n if (method !== \"catalog\") {\n const summaries = collectSummaries(store, opts.shared)\n if (method === \"summaries\" || summaryCoverage(store, requesterId, view, summaries) >= AUTO_SUMMARY_COVERAGE) {\n const base = opts.summaries ?? DEFAULT_SUMMARIES_QUERY\n const out = await summariesQuery(question, view, summaries, {\n ...base,\n navigatorModel: opts.selectorModel ?? base.navigatorModel,\n answerModel: opts.synthModel ?? base.answerModel,\n }, { call: opts.call ?? claudeModelCall, fetch: opts.fetch, timeoutMs, log })\n const pages = out.picked.map((a) => ({ title: a.meta.title, path: a.path, type: a.meta.type, hop: a.hop }))\n return {\n answer: out.answer,\n citations: out.status === \"ok\" ? pages.map(({ title, path, type }) => ({ title, path, type })) : [],\n candidates: pages.filter((p) => p.hop === 0).map(({ title, path }) => ({ title, path })),\n walked: pages,\n status: out.status,\n method: \"summaries\",\n live: out.live,\n liveAsked: out.liveAsked,\n trace: out.trace,\n ...(out.error ? { error: out.error } : {}),\n }\n }\n }\n\n if (!existsSync(catalogPath) && view.sharedPool.length === 0) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const ownCatalog = existsSync(catalogPath) ? readFileSync(catalogPath, \"utf-8\") : \"\"\n const catalog = ownCatalog + renderSharedCatalog(question, view.sharedPool, messagePath, graphWeight)\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, view.pool, requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, view, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\nexport interface RetrieveOptions {\n /** Articles picked before the walk. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from the picked articles. Default 1. */\n maxHops?: number\n /** Hard cap on articles returned. Default 6. */\n maxArticles?: number\n messagePath?: string[]\n graphWeight?: number\n /** The catalog to pick from. Pass it when retrieving many times in a row,\n * so the index is not rebuilt for every call. */\n pool?: CatalogEntry[]\n /** Seat telemetry label. */\n stage?: string\n}\n\n/**\n * The retrieval half of agenticQuery, without the synthesis call: BM25\n * shortlist, rerank seat, then the `related` wikilink walk. Returns the\n * walked articles, hop 0 first.\n *\n * When the seat is off or fails, the BM25 order decides on its own, and\n * only articles the text matched are picked: an article chosen for\n * nothing but its catalog position is noise here, not a candidate. There\n * is no CLI fallback, so this never spends an LLM call.\n */\nexport async function retrieveArticles(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: RetrieveOptions = {},\n): Promise<Array<WikiArticle & { hop: number }>> {\n const maxCandidates = opts.maxCandidates ?? 3\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const pool = opts.pool ?? catalogPool(store)\n if (pool.length === 0 || !question.trim()) return []\n\n let candidates = await selectCandidatesViaSeat(\n question, pool, requesterId, maxCandidates, messagePath, graphWeight, opts.stage ?? \"retrieve\",\n )\n if (!candidates) {\n const matched = new Set(scoreAll(question, buildIndex(pool.map(catalogDoc))).map((r) => r.docIndex))\n candidates = rankCatalogPool(question, pool, messagePath, graphWeight)\n .filter((i) => matched.has(i))\n .slice(0, maxCandidates)\n .map((i) => ({ title: pool[i].title, path: pool[i].path }))\n }\n if (candidates.length === 0) return []\n return walkSubgraph(candidates, scopeView(store, requesterId), opts.maxHops ?? 1, opts.maxArticles ?? 6)\n}\n\nexport type CatalogEntry = WikiIndex[\"articles\"][number]\n\n/** The catalog retrieval picks from: every indexed article but old versions. */\nexport function catalogPool(store: WikiStore): CatalogEntry[] {\n try {\n return (store.rebuildIndex().articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n } catch {\n return []\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\n/**\n * The articles a query may open: the requester's own wiki first, then\n * each shared one. Shared paths carry an `@<id>/` prefix so the walk\n * knows which store to read; a title the own wiki has resolves there.\n */\ninterface ScopeView {\n /** Own catalog, then the shared articles. */\n pool: CatalogEntry[]\n sharedPool: CatalogEntry[]\n titleIndex: Map<string, string>\n /** Title (lowercased) → pages whose `related` names it, newest first.\n * Built only when shared wikis are searched. */\n backlinks: Map<string, string[]>\n /** Paths the requester may read, own and shared. */\n readable: Set<string>\n read(path: string): WikiArticle | null\n}\n\nfunction scopeView(store: WikiStore, requesterId: string | undefined, shared: SharedWikiStore[] = []): ScopeView {\n const titleIndex = new Map<string, string>()\n const linking: Array<{ path: string; related: string[]; lastUpdated: string }> = []\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n linking.push({ path: article.path, related: article.meta.related ?? [], lastUpdated: article.meta.lastUpdated ?? \"\" })\n }\n const sharedPool: CatalogEntry[] = []\n const byId = new Map<string, SharedWikiStore>()\n for (const s of shared) {\n if (s.store.baseDir === store.baseDir) continue\n byId.set(s.id, s)\n // listArticles is cached and already drops what the requester can't\n // read; rebuilding every agent's index per query would not be.\n for (const a of s.store.listArticles(requesterId || \"\")) {\n if (a.path.includes(\"/_versions/\") || s.skip?.(a.path)) continue\n const path = `@${s.id}/${a.path}`\n sharedPool.push(catalogEntry(a, path))\n linking.push({ path, related: a.meta.related ?? [], lastUpdated: a.meta.lastUpdated ?? \"\" })\n const key = a.meta.title.toLowerCase()\n if (!titleIndex.has(key)) titleIndex.set(key, path)\n }\n }\n // In a fleet's shared pool the page that answers a question often links\n // TO the page the selector picked (a decision about a person), and the\n // forward walk never reaches it (#824 review: ranked 103rd of ~5,700).\n const backlinks = new Map<string, string[]>()\n if (byId.size > 0) {\n for (const l of [...linking].sort((a, b) => b.lastUpdated.localeCompare(a.lastUpdated))) {\n for (const t of l.related) {\n const key = t.toLowerCase()\n const list = backlinks.get(key) ?? []\n if (!list.includes(l.path)) list.push(l.path)\n backlinks.set(key, list)\n }\n }\n }\n let pool: CatalogEntry[] | undefined\n return {\n backlinks,\n readable: new Set(linking.map((l) => l.path)),\n // Lazy: retrieveArticles brings its own pool, and building this one\n // rebuilds the index.\n get pool() { return (pool ??= [...catalogPool(store), ...sharedPool]) },\n sharedPool,\n titleIndex,\n read(path) {\n const m = path.match(/^@([^/]+)\\/(.+)$/)\n const target = m ? byId.get(m[1]) : undefined\n if (m && !target) return null\n const s = target?.store ?? store\n const rel = m ? m[2] : path\n const article = requesterId ? s.readArticleAs(rel, requesterId) : s.readArticle(rel)\n return article ? { ...article, path } : null\n },\n }\n}\n\nfunction catalogEntry(a: WikiArticle, path: string): CatalogEntry {\n return {\n path,\n title: a.meta.title,\n type: a.meta.type,\n related: a.meta.related,\n tags: a.meta.tags || [],\n owner: a.meta.owner,\n access: a.meta.access,\n sharedWith: a.meta.sharedWith,\n aliases: [a.meta.title.toLowerCase(), ...(a.meta.aliases ?? []).map((x) => x.toLowerCase())],\n backlinks: 0,\n sources: a.meta.sources,\n lastUpdated: a.meta.lastUpdated,\n graphPath: a.meta.graphPath,\n }\n}\n\n/** Shared articles most related to the question, for the CLI selector.\n * Capped: a fleet's shared catalog would not fit one prompt. */\nexport const SHARED_CATALOG_LINES = 150\n\nfunction renderSharedCatalog(question: string, pool: CatalogEntry[], messagePath: string[] | undefined, graphWeight: number): string {\n if (pool.length === 0) return \"\"\n const lines = rankCatalogPool(question, pool, messagePath, graphWeight)\n .slice(0, SHARED_CATALOG_LINES)\n .map((i) => `- ${pool[i].title}${pool[i].type ? ` [${pool[i].type}]` : \"\"} (${pool[i].path})`)\n return `\\n\\n## Shared wiki (other agents' articles)\\n\\n${lines.join(\"\\n\")}\\n`\n}\n\n/** Pages that link to a picked page, opened per picked page. */\nconst BACKLINKS_PER_PICK = 3\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n view: ScopeView,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n const titleIndex = view.titleIndex\n const isShared = (path: string) => path.startsWith(\"@\")\n\n // The agent's own pages come first, and shared pages may take at most\n // half the walk when it has any: in the #824 trial shared pages took\n // the slots of the agent's own correct pages and its score dropped.\n const ordered = [...candidates.filter((c) => !isShared(c.path)), ...candidates.filter((c) => isShared(c.path))]\n let sharedCap = ordered.length > 0 && !isShared(ordered[0].path) ? Math.floor(maxArticles / 2) : maxArticles\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let sharedOpened = 0\n let frontier: Array<{ path: string; hop: number }> = ordered.map((c) => ({ path: c.path, hop: 0 }))\n // Shared pages turned away by the cap, in walk order. When the agent's\n // own pages run out first they get the slots left: an own pick with no\n // own neighbours must not leave the walk short of shared pages that answer.\n const deferred: Array<{ path: string; hop: number }> = []\n\n while (opened.size < maxArticles) {\n if (!frontier.length) {\n if (!deferred.length || sharedCap >= maxArticles) break\n sharedCap = maxArticles\n frontier = deferred.splice(0)\n }\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n if (isShared(next.path) && sharedOpened >= sharedCap) { deferred.push(next); continue }\n\n const article = view.read(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (isShared(next.path)) sharedOpened++\n if (next.hop >= maxHops) continue\n\n if (next.hop === 0) {\n // Pages link to a subject by any of its names; skip what is already\n // open before taking the newest few, or an opened page uses a slot.\n const names = [article.meta.title, ...(article.meta.aliases ?? [])].map((n) => n.toLowerCase())\n const linking = [...new Set(names.flatMap((n) => view.backlinks.get(n) ?? []))]\n .filter((path) => path !== next.path && !opened.has(path))\n .slice(0, BACKLINKS_PER_PICK)\n for (const path of linking) frontier.push({ path, hop: 1 })\n }\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n pool: CatalogEntry[],\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n stage = \"catalog-selector\",\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const bm25 = scoreAll(question, buildIndex(pool.map(catalogDoc)))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\n/** What BM25 sees of a catalog entry: the catalog carries no body. */\nfunction catalogDoc(a: { title: string; tags?: string[]; related?: string[] }): string {\n return [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \")\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n // Owner and date let the answer say where a fact came from and pick\n // the newer page when two disagree (#824).\n const from = [a.meta.owner ? `owner: ${a.meta.owner}` : \"\", a.meta.lastUpdated ? `updated: ${a.meta.lastUpdated}` : \"\"].filter(Boolean).join(\", \")\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]${from ? ` {${from}}` : \"\"}`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: claudeCliEnv(), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n\n/** `wiki.query.shared` from agentx.json: whether a query also searches the\n * shared wiki. On when there is no config to read. The CLI and the\n * `agentx_wiki_query` tool both ask here, so the switch reaches both. */\nexport async function sharedQueryEnabled(configPath?: string): Promise<boolean> {\n try {\n const { loadDaemonConfig } = await import(\"@/daemon/config\")\n return loadDaemonConfig(configPath).wiki.query.shared\n } catch {\n return true\n }\n}\n"],"mappings":"gTAAA,OAAS,gBAAAA,GAAc,cAAAC,MAAkB,KAEzCC,KAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,OAAgB,gBAiElB,IAAMC,GAAwB,GAIrC,SAASC,GAAgBC,EAAkBC,EAAiCC,EAAiBC,EAAwC,CACnI,GAAIA,EAAU,OAAS,EAAG,MAAO,GACjC,IAAIC,EAAQJ,EAAM,aAAaC,GAAe,EAAE,EAAE,IAAKI,GAAMA,EAAE,IAAI,EAAE,OAAQC,GAAM,CAACA,EAAE,SAAS,aAAa,CAAC,EAE7G,OADIF,EAAM,SAAW,IAAGA,EAAQF,EAAK,WAAW,IAAKK,GAAMA,EAAE,IAAI,GAC7DH,EAAM,SAAW,EAAU,EACxBA,EAAM,OAAQE,GAAMH,EAAU,IAAIG,CAAC,CAAC,EAAE,OAASF,EAAM,MAC9D,CA2CA,eAAsBI,GACpBC,EACAT,EACAC,EACAS,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAaF,EAAK,YAAc,SAChCG,EAAgBH,EAAK,eAAiB,EACtCI,EAAUJ,EAAK,SAAW,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O,KAAMA,EAAE,IAAK,EAAE,EAHlB,CAAC,CAItC,MAAE,CACA,MAAO,CAAC,CACV,CACF,CAEA,eAAexC,EAAUkF,EAAgBC,EAAejH,EAAoC,CAG1F,GAAM,CAAE,cAAAkH,EAAe,UAAAC,EAAW,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EACxD,CAAE,OAAAC,CAAO,EAAI,KAAM,QAAO,IAAI,EAC9BC,EAAMhH,EAAQ+G,EAAO,EAAG,qBAAqB,QAAQ,KAAK,EAChEF,EAAUG,EAAK,CAAE,UAAW,EAAK,CAAC,EAClC,IAAMC,EAAajH,EAAQgH,EAAK,UAAU,KAAK,IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMY,GAASD,EAAK,CAAE,IAAKE,EAAa,EAAG,SAAU,QAAS,QAAS1H,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EACpH,GAAI,CACF,IAAM2H,EAAW,KAAK,MAAMd,CAAG,EAC/B,OAAO,OAAOc,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOd,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF,CAKA,eAAsBK,GAAmBC,EAAuC,CAC9E,GAAI,CACF,GAAM,CAAE,iBAAAC,CAAiB,EAAI,KAAM,QAAO,sBAAiB,EAC3D,OAAOA,EAAiBD,CAAU,EAAE,KAAK,MAAM,MACjD,MAAE,CACA,MAAO,EACT,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","AUTO_SUMMARY_COVERAGE","summaryCoverage","store","requesterId","view","summaries","paths","a","p","e","agenticQuery","question","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","resolve","scopeView","method","collectSummaries","base","DEFAULT_SUMMARIES_QUERY","out","summariesQuery","claudeModelCall","pages","title","path","type","existsSync","emptyResult","catalog","readFileSync","renderSharedCatalog","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","retrieveArticles","pool","catalogPool","matched","scoreAll","buildIndex","catalogDoc","r","rankCatalogPool","status","_question","error","shared","titleIndex","linking","article","sharedPool","byId","s","catalogEntry","key","backlinks","l","b","t","list","m","target","rel","x","SHARED_CATALOG_LINES","i","BACKLINKS_PER_PICK","isShared","ordered","sharedCap","opened","sharedOpened","frontier","deferred","next","names","n","stage","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","bm25","maxBm25","text","useGraph","branch","ancestryScore","byScore","y","branchOnly","ranked","articles","articlesBlock","from","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","execSync","claudeCliEnv","envelope","sharedQueryEnabled","configPath","loadDaemonConfig"]}
@@ -1,37 +0,0 @@
1
- import{b as bt,c as vt}from"./chunk-QSKG754X.js";import{b as $e}from"./chunk-AFRHKA7B.js";import{b as pt,e as ft,f as gt,i as wt,k as yt,l as kt,q as It}from"./chunk-S2UXDEGW.js";import{c as lt,e as ct,f as ut}from"./chunk-KA2UIZXG.js";import{e as st,g as at,h as dt,i as Ie}from"./chunk-GQ76J72O.js";import{a as mt}from"./chunk-GV7S5BAX.js";import{c as ht}from"./chunk-SZDACK6O.js";import{y as rt,z as Un}from"./chunk-F5PVUB4Y.js";import{b as nt,f as Ln}from"./chunk-72SZI2UW.js";import{a as ot,b as ke,c as be,d as it,e as ve}from"./chunk-QD6IICK7.js";import{c as et,d as tt}from"./chunk-QOYAX2FT.js";import{f as ye,n as _n}from"./chunk-UIBUZ2N3.js";import{existsSync as Hn,mkdirSync as $t,readFileSync as Bn,writeFileSync as Kn,renameSync as qn}from"fs";import{resolve as St,dirname as zn}from"path";var At=class{filePath;log;constructor(e={}){let t=e.baseDir??St(process.cwd(),".agentx");this.filePath=St(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),$t(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Hn(this.filePath))return{version:1,overrides:{}};try{let e=Bn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){$t(zn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Kn(t,JSON.stringify(e,null,2)),qn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Wt,writeFileSync as Se,appendFileSync as Vn,mkdirSync as Qn,existsSync as Nt,statSync as Zn}from"fs";import{resolve as Z}from"path";var Rt="[Agent Memory \u2014 persistent facts from past conversations]",Jn=2400;function xt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Yn(n,e=Date.now()){let t=ct(n,e),r=n.undated?"UNVERIFIED (never checked) ":xt(t,st(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Gn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=dt(n,e);return{line:`- [${n.category}] ${xt(o,at(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Pt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Rt.length,a=!1;for(let i of n){let d=e.length>0?ut(i.content,e):null,l,p,u=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!u){if(o.has(d.id))continue;o.add(d.id),l=Yn(d,t),p=d.id}else l=Gn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Ie.length:0;if(s+f+l.line.length>Jn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Tt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Ie]:[];return[Rt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
2
- `)}var Ot=200,Xn=7,Dt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=Z(e,".agentx/memory"),this.ledger=new lt(Z(e,".agentx/wiki")),Nt(this.memoryDir)||Qn(this.memoryDir,{recursive:!0})}filePath(e){return Z(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||ke(t.content))return!1;let r=t.source.trust??ot(t.source.channel),o=t.review??it(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Vn(this.filePath(e),JSON.stringify(s)+`
3
- `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Nt(t))return[];try{let{mtimeMs:r,size:o}=Zn(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Wt(t,"utf-8").split(`
4
- `).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(ve);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=Z(this.memoryDir,`${t}_bm25_cache.json`),i=tt(s,a),d=et(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),u=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(u.length===0)return o.slice(-r);let f=u.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Tt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Pt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Se(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
5
- `)+`
6
- `)}getDueForReview(e,t=5){let r=this.getAll(e).filter(ve),o=Date.now();return r.filter(s=>s.category==="task-state"?!1:s.nextReview?new Date(s.nextReview).getTime()<=o:!0).sort((s,a)=>!s.nextReview&&a.nextReview?-1:s.nextReview&&!a.nextReview?1:s.nextReview&&a.nextReview?new Date(s.nextReview).getTime()-new Date(a.nextReview).getTime():(s.accessCount||0)-(a.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let r=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let o of t){let s=Math.round((Date.now()-new Date(o.createdAt).getTime())/864e5);r.push(`- [${o.category}] ${o.content} (${s}d old, accessed ${o.accessCount||0}x)`)}return r.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),r.join(`
7
- `)}held(e){return this.getAll(e).filter(t=>t.review==="held"||t.review===void 0&&be(t)==="external")}review(e,t,r,o="operator"){let s=this.getAll(e),a=s.find(i=>i.id===t);return a?(a.review=r,a.reviewedBy=o,a.reviewedAt=new Date().toISOString(),this.rewrite(e,s),!0):!1}scrubSecrets(e,t=!1){let r=this.getAll(e),o=r.filter(a=>a.category!=="secret"&&!ke(a.content)),s=r.length-o.length;return t&&s>0&&this.rewrite(e,o),s}trustSummary(e){let t={};for(let r of this.getAll(e)){let o=`${be(r)}${r.review?`/${r.review}`:""}`;t[o]=(t[o]??0)+1}return t}fileFor(e){return this.filePath(e)}rewrite(e,t){let r=[];try{r=Wt(this.filePath(e),"utf-8").split(`
8
- `).filter(s=>{if(!s.trim())return!1;try{return JSON.parse(s),!1}catch{return!0}})}catch{}let o=[...t.map(s=>JSON.stringify(s)),...r];Se(this.filePath(e),o.join(`
9
- `)+(o.length?`
10
- `:""))}hasSimilar(e,t){let r=this.getAll(e),s=t.toLowerCase().split(/\s+/).filter(a=>a.length>3);return r.some(a=>{let i=a.content.toLowerCase();return s.filter(l=>i.includes(l)).length>=s.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let r=Date.now(),o=Xn*24*60*60*1e3;t=t.filter(a=>a.category==="task-state"&&a.expiresAt?new Date(a.expiresAt).getTime()>r:a.category==="task-state"&&!a.expiresAt?r-new Date(a.createdAt).getTime()<o:!0),t.length>Ot&&(t=t.slice(-Ot));let s=this.filePath(e);Se(s,t.map(a=>JSON.stringify(a)).join(`
11
- `)+`
12
- `)}};function Et(n){let e=(n||"").trim();for(let t=0;t<5;t++){let r=e;if(e=e.replace(/^Peer\s+"[^"]*"\s+\/task error:\s*\d{3}:\s*/i,"").replace(/^Peer\s+"[^"]*"\s+agent error:\s*/i,"").replace(/^mesh fallback failed:\s*/i,"").trim(),e===r)break}return e}var er="__queued__";function Ti(n,e){return`${er}:${n}:${e}`}var tr=/^__queued__(?::([A-Za-z-]+):(\d+))?$/;function nr(n){if(!n)return null;let e=tr.exec(Et(n));return e?{mode:e[1]||"collect",pending:e[2]?Number(e[2]):1}:null}function Wi(n){return nr(n)!==null}import{existsSync as S,mkdirSync as Ar,readdirSync as ne,readFileSync as re,statSync as Rr,unlinkSync as oe,writeFileSync as xe}from"fs";import{resolve as P,relative as Pe}from"path";import{z as c}from"zod";var rr=c.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","trigger.poll","agent","transform","classify","branch","gateway.parallel","rule","action.send","action.createIssue","action.setLabel","action.readLabel","action.react","action.editMessage","action.logTime","action.callHTTP","action.run","action.builtin","subProcess","signal.emit","signal.wait","timer.boundary","owner.notify","owner.ask","person.message","person.wait","checkpoint","end"]),or=c.enum(["equals","contains","matches","exists"]),Ae=c.object({kind:or,params:c.record(c.unknown()).default({})}),Ft=c.object({maxAttempts:c.number().int().min(1).max(10).default(1),backoffMs:c.number().int().min(0).max(6e4).default(1e3)}).default({maxAttempts:1,backoffMs:1e3}),jt=c.object({id:c.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:rr,config:c.record(c.unknown()).default({}),retry:Ft,position:c.object({x:c.number(),y:c.number()}).optional()}),Ct=c.object({from:c.string(),fromPort:c.string().optional(),to:c.string(),toPort:c.string().optional(),label:c.string().optional()}),Mt=c.union([c.string(),c.date().transform(n=>n.toISOString())]),x=c.object({id:c.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"workflow id must be lower-kebab"),version:c.literal(2).default(2),title:c.string().min(1),description:c.string().optional(),status:c.enum(["draft","review","active","deprecated"]).default("active"),tags:c.array(c.string()).default([]),project:c.string().optional(),entity:c.string().optional(),intentPath:c.array(c.string()).default([]),generatedFrom:c.string().optional(),sourceTaskIds:c.array(c.string()).default([]),confidence:c.number().min(0).max(1).optional(),workflowVersion:c.string().optional(),ownerAgent:c.string().optional(),lastMatchedAt:c.string().optional(),matchCount:c.number().int().min(0).default(0),state:c.enum(["active","disabled","quarantined"]).default("active"),priority:c.number().int().default(0),fanOut:c.boolean().default(!1),nodes:c.array(jt).refine(n=>n.length>0,{message:"workflow must have at least one node"}),edges:c.array(Ct).default([]),envAllow:c.array(c.string()).default([]),retention:c.object({maxRuns:c.number().int().positive().default(500),maxDays:c.number().int().positive().default(90)}).default({maxRuns:500,maxDays:90}),maxChildDepth:c.number().int().positive().default(5),mesh:c.object({allowRemote:c.boolean().default(!1),peers:c.array(c.string()).optional()}).default({allowRemote:!1}),created:Mt.optional(),updated:Mt.optional(),autoStart:c.boolean().default(!1),approval:c.enum(["start","step"]).optional(),followUp:c.object({stallMinutes:c.number().positive().max(7*24*60).optional(),maxNudges:c.number().int().min(0).max(20).optional()}).optional()}),X={"owner.ask":{main:"yes",other:["no","expired"]},"person.message":{main:"sent",other:["declined"]},"person.wait":{main:"reply",other:["timeout"]}};function q(n){let e=[],t=new Map(n.nodes.map(a=>[a.id,a])),r=n.nodes.filter(a=>a.type.startsWith("trigger."));r.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),r.length>1&&e.push(`workflow has ${r.length} trigger.* nodes; v1 supports exactly one`);for(let a of n.edges)t.has(a.from)||e.push(`edge references missing node: from="${a.from}"`),t.has(a.to)||e.push(`edge references missing node: to="${a.to}"`);let o=r[0];if(o){let a=new Map;for(let l of n.edges)a.has(l.from)||a.set(l.from,[]),a.get(l.from).push(l.to);let i=new Set,d=[o.id];for(;d.length;){let l=d.pop();if(!i.has(l)){i.add(l);for(let p of a.get(l)??[])d.push(p)}}for(let l of n.nodes)i.has(l.id)||e.push(`node "${l.id}" is unreachable from trigger "${o.id}"`);n.nodes.some(l=>i.has(l.id)&&ir(l.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let a of n.nodes){if(a.type!=="branch"&&a.type!=="rule")continue;let i=a.type==="branch"?a.config.cases??[]:(a.config.rules??[]).filter(u=>typeof u.to=="string"),d=a.type==="branch"?a.config.default:a.config.default?.to,l=new Set(i.map(u=>u.to));d&&l.add(d);let p=n.edges.filter(u=>u.from===a.id);for(let u of p){let f=u.fromPort??"";l.has(f)||e.push(`${a.type} "${a.id}" has outgoing edge with port "${f}" not declared in cases or default`)}}let s=ar(n);for(let a of s)e.push(`cycle without agent/checkpoint: ${a.join(" -> ")}`);return e}function ir(n){return n==="end"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function sr(n){return n==="agent"||n==="owner.ask"||n==="person.wait"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function ar(n){let e=new Map;for(let i of n.edges)e.has(i.from)||e.set(i.from,[]),e.get(i.from).push(i.to);let t=new Map(n.nodes.map(i=>[i.id,i])),r=[],o=new Map,s=[],a=i=>{if(o.get(i)===1){let d=s.indexOf(i);if(d>=0){let l=s.slice(d).concat(i);l.some(u=>{let f=t.get(u)?.type;return f?sr(f):!1})||r.push(l)}return}if(o.get(i)!==2){o.set(i,1),s.push(i);for(let d of e.get(i)??[])a(d);s.pop(),o.set(i,2)}};for(let i of n.nodes)o.get(i.id)!==2&&a(i.id);return r}var _t=c.enum(["running","paused","completed","failed","canceled"]),dr=c.enum(["ok","failed","timeout","skipped","paused","resumed"]),lr=c.object({at:c.string(),nodeId:c.string(),inputKeys:c.array(c.string()).default([]),status:dr,output:c.record(c.unknown()).optional(),idempotencyKey:c.string(),note:c.string().optional(),startedAt:c.string().optional(),durationMs:c.number().int().min(0).optional()}),cr=c.object({backend:c.string(),id:c.string()}),ur=c.discriminatedUnion("kind",[c.object({kind:c.literal("checkpoint"),nodeId:c.string(),checkpointName:c.string(),resumeMatch:c.record(c.unknown()).default({})}),c.object({kind:c.literal("subProcess"),nodeId:c.string(),childRunId:c.string(),childWorkflowId:c.string()}),c.object({kind:c.literal("signalWait"),nodeId:c.string(),signalName:c.string(),match:c.record(c.unknown()).default({}),scope:c.enum(["workflow","global"]).default("workflow")}),c.object({kind:c.literal("timerWait"),nodeId:c.string(),fireAt:c.string()}),c.object({kind:c.literal("ownerDecision"),nodeId:c.string(),cardId:c.string(),purpose:c.enum(["ask","send","start"]),message:c.object({channel:c.string(),chatId:c.string(),accountId:c.string().optional(),text:c.string(),to:c.string().optional()}).optional()}),c.object({kind:c.literal("replyWait"),nodeId:c.string(),channel:c.string(),chatId:c.string(),accountId:c.string().optional(),from:c.string().optional(),deadline:c.string(),nextRemindAt:c.string().optional(),remindEveryMs:c.number().optional(),reminders:c.number().int().default(0),maxReminders:c.number().int().default(0),reminds:c.string().optional()}),c.object({kind:c.literal("agentStep"),nodeId:c.string(),agentId:c.string(),nudges:c.number().int().default(0),maxNudges:c.number().int().default(0),stallMs:c.number(),nextNudgeAt:c.string().optional(),blocked:c.string().optional()})]),pr=c.object({id:c.string(),title:c.string()}),fr=c.object({at:c.string(),kind:c.enum(["plan","revise"]),reason:c.string().optional(),steps:c.array(c.string()),dropped:c.array(c.string()).default([])}),gr=c.object({steps:c.array(pr),current:c.object({id:c.string(),startedAt:c.string()}).optional(),revisions:c.array(fr).default([])}),mr=c.object({title:c.string().optional(),tags:c.array(c.string()).default([]),startedBy:c.string().optional(),requestId:c.string().optional(),followUp:c.boolean().default(!1),approvedAtStart:c.boolean().default(!1),approved:c.record(c.string()).optional(),blocked:c.object({nodeId:c.string(),reason:c.string(),at:c.string()}).optional(),endNotifiedAt:c.string().optional(),wrap:c.object({agentId:c.string(),channel:c.string(),mode:c.enum(["linear","plan"]),taskId:c.string().optional()}).optional(),plan:gr.optional()}),hr=c.object({id:c.string(),workflowId:c.string(),workflowVersion:c.literal(2),homeNode:c.string(),status:_t,pausedAt:ur.optional(),context:c.record(c.record(c.unknown())).default({}),pending:c.array(c.string()).default([]),joinCounters:c.record(c.array(c.string())).default({}),entityRef:cr,history:c.array(lr).default([]),parentRunId:c.string().nullable().default(null),parentNodeId:c.string().nullable().default(null),rootRunId:c.string().nullable().default(null),depth:c.number().int().min(0).default(0),eventRootId:c.string().optional(),meta:mr.optional(),createdAt:c.string(),updatedAt:c.string()});import Ut from"js-yaml";var wr=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),$=class extends Error{constructor(t,r){super(t);this.mark=r;this.name="WorkflowYamlError"}};function ee(n,e={}){if(!n||n.trim()==="")throw new $(`${N(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=Ut.loadAll(n)}catch(o){let s=o?.mark;throw new $(`${N(e)}YAML parse error: ${o?.reason??o?.message??o}`+(s?` (line ${s.line+1}, column ${s.column+1})`:""),s)}if(t.length===0||t.length===1&&t[0]==null)throw new $(`${N(e)}YAML produced no document.`);if(t.length>1)throw new $(`${N(e)}multi-document YAML is not supported in v1; one workflow per file.`);let r=t[0];if(typeof r!="object"||r===null||Array.isArray(r)){let o=Array.isArray(r)?"array":typeof r;throw new $(`${N(e)}top-level YAML must be a mapping (got ${o}).`)}return Ht(r,e)}function Ht(n,e={}){if(!("flow"in n))return n;let t=n.flow;if(t==null){let u={...n};return delete u.flow,u}if(!Array.isArray(t))throw new $(`${N(e)}flow must be an array of node ids (got ${typeof t}).`);for(let u of t)if(typeof u!="string")throw new $(`${N(e)}flow entries must be strings (got ${typeof u}).`);let r=t,o=Array.isArray(n.nodes)?n.nodes:[],s=new Map;for(let u of o)u&&typeof u=="object"&&typeof u.id=="string"&&typeof u.type=="string"&&s.set(u.id,u.type);for(let u of r){if(!s.has(u))throw new $(`${N(e)}flow references unknown node "${u}".`);let f=s.get(u);if(wr.has(f))throw new $(`${N(e)}flow cannot include ${f} node "${u}"; use explicit edges for ${f} nodes.`)}let a=[];for(let u=0;u<r.length-1;u++)a.push({from:r[u],to:r[u+1]});let i=Array.isArray(n.edges)?n.edges:[],d=new Set,l=[];for(let u of i){if(!u||typeof u!="object")continue;let f=Lt(u.from,u.fromPort,u.to);f&&!d.has(f)?(d.add(f),l.push(u)):f||l.push(u)}for(let u of a){let f=Lt(u.from,void 0,u.to);f&&!d.has(f)&&(d.add(f),l.push(u))}let p={...n,edges:l};return delete p.flow,p}function Lt(n,e,t){return typeof n!="string"||typeof t!="string"?null:`${n}::${typeof e=="string"?e:""}::${t}`}function N(n){return n.filePath?`${n.filePath}: `:""}function yr(n){return Ut.dump(n,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as kr,isMap as te,isSeq as br,isScalar as Bt,parseDocument as vr}from"yaml";function Kt(n,e){let t=vr(n);if(!t.contents||!te(t.contents)){let r=new kr(e);return t.commentBefore&&(r.commentBefore=t.commentBefore),String(r)}return Re(t,t.contents,e),String(t)}function Re(n,e,t){let r=Object.keys(t),o=new Set(r),s=new Map;for(let i of e.items){let d=Sr(i);d!==null&&s.set(d,i)}let a=[];for(let i of r){let d=t[i],l=s.get(i);l?(Ir(n,l,d),a.push(l)):a.push(n.createPair(i,d))}e.items=a}function Ir(n,e,t){let r=e.value;if(t==null){e.value=n.createNode(null);return}if(typeof t!="object"){e.value=n.createNode(t);return}if(Array.isArray(t)){br(r)?$r(n,r,t):e.value=n.createNode(t);return}te(r)?Re(n,r,t):e.value=n.createNode(t)}function $r(n,e,t){if(!(t.length>0&&t.every(a=>a&&typeof a=="object"&&typeof a.id=="string"))){let a=n.createNode(t);e.items=a.items;return}let o=new Map;for(let a of e.items)if(te(a)){let i=a.get("id",!0);Bt(i)&&typeof i.value=="string"&&o.set(i.value,a)}let s=[];for(let a of t){let i=a.id,d=o.get(i);d&&te(d)?(Re(n,d,a),s.push(d)):s.push(n.createNode(a))}e.items=s}function Sr(n){let e=n.key;return Bt(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var qt=new Map,Te=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/workflows"),Ar(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return P(this.baseDir,`${e}.json`)}pathForYaml(e){return P(this.baseDir,`${e}.yaml`)}isWorkflowFile(e){return e.startsWith("_")?!1:e.endsWith(".json")||e.endsWith(".yaml")||e.endsWith(".yml")}idFromFilename(e){return e.replace(/\.(json|ya?ml)$/,"")}readAndParse(e){let t=P(this.baseDir,e),r=re(t,"utf-8");return e.endsWith(".json")?JSON.parse(r):ee(r,{filePath:e})}list(){if(!S(this.baseDir))return[];let e=new Map,t=[];for(let i of ne(this.baseDir,{withFileTypes:!0})){if(!i.isFile()||!this.isWorkflowFile(i.name))continue;let d=this.idFromFilename(i.name),l=e.get(d)??[];l.push(i.name),e.set(d,l);try{let p=Rr(P(this.baseDir,i.name));t.push(`${i.name}:${p.mtimeMs}:${p.size}`)}catch{t.push(`${i.name}:?`)}}let r=t.sort().join("|"),o=qt.get(this.baseDir);if(o&&o.signature===r)return o.workflows.slice();let s=[];for(let[,i]of e)if(!(i.length>1))try{let d=this.readAndParse(i[0]),l=x.safeParse(d);l.success&&s.push(l.data)}catch{}let a=s.sort((i,d)=>i.id.localeCompare(d.id));return qt.set(this.baseDir,{signature:r,workflows:a}),a.slice()}validateAll(){let e=[];if(!S(this.baseDir))return e;let t=new Map;for(let r of ne(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),s=t.get(o)??[];s.push(r.name),t.set(o,s)}for(let[r,o]of t){if(o.length>1){let u=[...o].sort();for(let f of u)e.push({id:r,path:Pe(this.baseDir,P(this.baseDir,f)),issues:[`duplicate workflow id "${r}" \u2014 found ${u.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let s=o[0],a=P(this.baseDir,s),i=Pe(this.baseDir,a),d;try{d=this.readAndParse(s)}catch(u){let f=u instanceof $?u.message:`parse error: ${u?.message??u}`;e.push({id:r,path:i,issues:[f],isValid:!1});continue}let l=x.safeParse(d);if(!l.success){let u=l.error.issues.map(f=>`${f.path.join(".")||"<root>"}: ${f.message}`);e.push({id:String(d?.id??r),path:i,issues:u,isValid:!1});continue}let p=q(l.data);e.push({workflow:l.data,issues:p,isValid:p.length===0})}return e}get(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=P(this.baseDir,`${e}.yml`),s=S(t),a=S(r)||S(o);if(s&&a)return null;if(s)try{let d=JSON.parse(re(t,"utf-8")),l=x.safeParse(d);return l.success?l.data:null}catch{return null}let i=S(r)?r:S(o)?o:null;if(i)try{let d=re(i,"utf-8"),l=ee(d,{filePath:Pe(this.baseDir,i)}),p=x.safeParse(l);return p.success?p.data:null}catch{return null}if(!S(this.baseDir))return null;for(let d of ne(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name)||this.idFromFilename(d.name)===e))try{let p=this.readAndParse(d.name),u=x.safeParse(p);if(u.success&&u.data.id===e)return u.data}catch{}return null}save(e,t={}){let r=new Date().toISOString().slice(0,10),o=x.parse({...e,created:e.created||r,updated:r}),s=this.pathForYaml(o.id),a=P(this.baseDir,`${o.id}.yml`),i=S(s)?s:S(a)?a:null;if(!i&&S(this.baseDir)){for(let d of ne(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name))&&!d.name.endsWith(".json"))try{let l=this.readAndParse(d.name),p=x.safeParse(l);if(p.success&&p.data.id===o.id){i=P(this.baseDir,d.name);break}}catch{}}if(i&&t.convertFromYaml)return oe(i),xe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
13
- `),o;if(i){let d=re(i,"utf-8");try{let l=Kt(d,o);return xe(i,l),o}catch(l){let p=new Error(`yaml round-trip failed for "${o.id}" at ${i}: ${l?.message??l}`);throw p.yamlPath=i,p}}return xe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
14
- `),o}delete(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=P(this.baseDir,`${e}.yml`),s=!1;return S(t)&&(oe(t),s=!0),S(r)&&(oe(r),s=!0),S(o)&&(oe(o),s=!0),s}};import{createHash as xr,randomUUID as Pr}from"crypto";import{appendFileSync as zt,existsSync as C,mkdirSync as Jt,readdirSync as Yt,readFileSync as We,statSync as Gt,unlinkSync as Ne,writeFileSync as Tr}from"fs";import{resolve as F}from"path";function Wr(n){return n.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function I(n,e,t){return xr("sha1").update(`${n}|${e}|${t}`).digest("hex").slice(0,16)}var Oe=class{baseDir;runsDir;indexDir;nodeId;constructor(e){this.baseDir=e.baseDir??F(process.cwd(),".agentx/workflows"),this.runsDir=F(this.baseDir,"_runs"),this.indexDir=F(this.baseDir,"_index"),this.nodeId=e.nodeId,Jt(this.runsDir,{recursive:!0}),Jt(this.indexDir,{recursive:!0})}runPath(e){return F(this.runsDir,`${e}.jsonl`)}indexPath(e){return F(this.indexDir,`${e.backend}__${Wr(e.id)}.json`)}create(e){let t=new Date().toISOString(),r=e.id??Pr(),o={id:r,workflowId:e.workflowId,workflowVersion:2,homeNode:this.nodeId,status:"running",pausedAt:void 0,context:e.initialContext??{},pending:e.initialPending,entityRef:e.entityRef,history:[],parentRunId:e.parentRunId??null,parentNodeId:e.parentNodeId??null,rootRunId:e.rootRunId??r,depth:e.depth??0,eventRootId:e.eventRootId??ft()?.rootId,joinCounters:{},...e.meta?{meta:e.meta}:{},createdAt:t,updatedAt:t};return this.appendSnapshot(o),this.writeIndex(e.entityRef,o.id),o}get(e){let t=this.runPath(e);if(!C(t))return null;let r=We(t,"utf-8").trim();if(!r)return null;let o=null;for(let s of r.split(`
15
- `)){let a;try{a=JSON.parse(s)}catch{continue}if(a.v===2){if(a.kind==="snapshot")o=a.run;else if(a.kind==="exec"&&o&&o.id===a.runId){let i=o;o={...i,history:[...i.history,a.entry],pending:a.pending,status:a.status??i.status,pausedAt:a.pausedAt===null?void 0:a.pausedAt??i.pausedAt,context:a.context??i.context,joinCounters:a.joinCounters??i.joinCounters,updatedAt:a.entry.at}}}}return o}getActiveByEntity(e){let t=this.indexPath(e);if(!C(t))return null;try{return JSON.parse(We(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!C(t))return null;try{return JSON.parse(We(t,"utf-8")).homeNode}catch{return null}}recordExecution(e){let t=this.get(e.runId);if(!t)return null;if(t.history.some(s=>s.idempotencyKey===e.entry.idempotencyKey))return t;let r={v:2,kind:"exec",runId:e.runId,entry:e.entry,pending:e.nextPending,status:e.status,pausedAt:e.pausedAt===null?null:e.pausedAt,context:e.context,joinCounters:e.joinCounters};zt(this.runPath(e.runId),JSON.stringify(r)+`
16
- `);let o=e.status??t.status;return o==="completed"||o==="failed"||o==="canceled"?this.clearIndex(t.entityRef):this.writeIndex(t.entityRef,t.id),this.get(e.runId)}setStatus(e,t){let r=this.get(e);if(!r)return null;let o={...r,status:t,updatedAt:new Date().toISOString()};return this.appendSnapshot(o),t!=="running"&&t!=="paused"&&this.clearIndex(o.entityRef),o}setMeta(e,t){let r=this.get(e);if(!r)return null;let o={tags:[],followUp:!1,approvedAtStart:!1,...r.meta,...t},s={...r,meta:o,updatedAt:new Date().toISOString()};return this.appendSnapshot(s),s}patch(e,t){let r=this.get(e);if(!r)return null;let o={...r,...t.meta?{meta:{tags:[],followUp:!1,approvedAtStart:!1,...r.meta,...t.meta}}:{},...t.pending?{pending:t.pending}:{},updatedAt:new Date().toISOString()};return this.appendSnapshot(o),o}discard(e){let t=this.get(e);if(!t)return!1;this.clearIndex(t.entityRef);try{return Ne(this.runPath(e)),!0}catch{return!1}}list(e={}){if(!C(this.runsDir))return[];let t=Yt(this.runsDir).filter(o=>o.endsWith(".jsonl")).map(o=>({name:o,mtime:Gt(F(this.runsDir,o)).mtimeMs})).sort((o,s)=>s.mtime-o.mtime),r=[];for(let o of t){let s=this.get(o.name.replace(/\.jsonl$/,""));if(s&&!(e.workflowId&&s.workflowId!==e.workflowId)&&(r.push(s),e.limit&&r.length>=e.limit))break}return r}prune(e){if(!C(this.runsDir))return 0;let t=Date.now()-e.maxDays*24*60*60*1e3,r=[];for(let s of Yt(this.runsDir)){if(!s.endsWith(".jsonl"))continue;let a=F(this.runsDir,s),i=Gt(a).mtimeMs,d=this.get(s.replace(/\.jsonl$/,""));d&&(d.status==="running"||d.status==="paused"||r.push({file:a,run:d,mtime:i}))}r.sort((s,a)=>a.mtime-s.mtime);let o=0;for(let s=0;s<r.length;s++){let a=r[s],i=a.mtime<t,d=s>=e.maxRuns;if(i||d)try{Ne(a.file),o++}catch{}}return o}appendSnapshot(e){let t={v:2,kind:"snapshot",run:e};zt(this.runPath(e.id),JSON.stringify(t)+`
17
- `)}writeIndex(e,t){Tr(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
18
- `)}clearIndex(e){let t=this.indexPath(e);if(C(t))try{Ne(t)}catch{}}};import{existsSync as Vt,mkdirSync as Nr,readFileSync as Or,unlinkSync as Dr,writeFileSync as Er}from"fs";import{resolve as De}from"path";import{z as _}from"zod";var Qt=_.object({version:_.literal(1),nodes:_.record(_.object({x:_.number(),y:_.number()}))}),Ee=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??De(process.cwd(),".agentx/workflows"),this.layoutsDir=De(this.baseDir,"_layouts"),Nr(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return De(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!Vt(t))return null;try{let r=Qt.safeParse(JSON.parse(Or(t,"utf-8")));return r.success?r.data:null}catch{return null}}save(e,t){let r=Qt.parse(t);return Er(this.pathFor(e),JSON.stringify(r,null,2)+`
19
- `),r}sync(e,t){let r=this.get(e);if(!r)return null;let o={};for(let a of t)r.nodes[a]&&(o[a]=r.nodes[a]);let s={version:1,nodes:o};return this.save(e,s)}delete(e){let t=this.pathFor(e);return Vt(t)?(Dr(t),!0):!1}};function Zt(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Mr(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&t++;return t/Math.max(n.size,e.size)}function Fr(n,e){let t=Zt(n.message),r=e.filter(s=>s.state==="active"&&(s.status??"active")==="active"),o=null;for(let s of r){let a=0,i=[];if(s.ownerAgent&&s.ownerAgent===n.agentId&&(a+=.25,i.push("owner-agent")),n.channel&&s.tags.includes(n.channel)&&(a+=.15,i.push("channel-tag")),n.intentPath?.length&&s.intentPath.length){let u=n.intentPath.filter((f,g)=>s.intentPath[g]===f).length;u>0&&(a+=Math.min(.3,u*.1),i.push("intent-path"))}let d=[s.id,s.title,s.description??"",...s.tags].join(" "),l=Mr(t,Zt(d));l>0&&(a+=Math.min(.35,l),i.push("text-similarity")),(s.matchCount??0)>0&&(a+=Math.min(.1,s.matchCount*.01),i.push("prior-matches"));let p=Math.max(0,Math.min(1,a));(!o||p>o.confidence)&&(o={workflow:s,confidence:p,reasons:i})}return o&&o.confidence>0?o:null}function ie(n){let{workflow:e,fromNodeId:t,selectedPort:r}=n,o=e.nodes.find(d=>d.id===t);if(!o)return{nextPending:[]};let s=e.edges.filter(d=>d.from===t),a=X[o.type];return{nextPending:(o.type==="branch"?s.filter(d=>(d.fromPort??"")===(r??"")):a?s.filter(d=>(d.fromPort??a.main)===(r??a.main)):s).map(d=>d.to)}}function Me(n,e){let t=n.config.cases??[],r=n.config.default??"";for(let o of t)if(se(o.when,e))return o.to;return r}function se(n,e){let t=n.params??{},r=String(t.path??""),o=L(e,r);switch(n.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(s=>s===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function L(n,e){if(!e)return;let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function z(n){let e=n.nodes.find(r=>r.type.startsWith("trigger."));if(!e)return null;let t=n.edges.filter(r=>r.from===e.id).map(r=>r.to);return{triggerId:e.id,pending:t}}function T(n,e){return n.nodes.find(t=>t.id===e)}import{randomUUID as ko}from"crypto";Ln();Un();function jr(n,e,t){let r=n.split(".");if(r[0]==="env"){if(r.length!==2)return"";let s=r[1];if(!t.has(s))return"";let a=process.env[s];return typeof a=="string"?a:""}let o=e;for(let s of r){if(o==null||typeof o!="object")return"";o=o[s]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function R(n,e,t={}){let r=new Set(t.envAllow||[]);return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,s)=>jr(s,e,r))}function v(n,e,t={}){let r={};for(let[o,s]of Object.entries(n))typeof s=="string"?r[o]=R(s,e,t):Array.isArray(s)?r[o]=s.map(a=>typeof a=="string"?R(a,e,t):a):s&&typeof s=="object"?r[o]=v(s,e,t):r[o]=s;return r}var Xt="workflow-classify",ae="unsure",en=async n=>{let e=n.node.config,t=n.run.context,r={envAllow:n.workflow.envAllow},o=R(String(e.input??""),t,r).trim();if(!o)return{error:`classify node "${n.node.id}" missing config.input`};let s=e.labels,a=Array.isArray(s)?Object.fromEntries(s.map(y=>[String(y),null])):typeof s=="object"&&s?Object.fromEntries(Object.entries(s).map(([y,k])=>[y,k==null?null:String(k)])):{},i=Object.keys(a);if(i.length<2)return{error:`classify node "${n.node.id}" needs at least two labels`};if(i.includes(ae))return{error:`classify node "${n.node.id}": "${ae}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,l=e.instructions?R(String(e.instructions),t,r):void 0,p={input:o};if(e.state&&typeof e.state=="object")for(let[y,k]of Object.entries(e.state)){let w=typeof k=="string"?R(k,t,r):k;(w===null||["string","number","boolean"].includes(typeof w))&&(p[y]=w)}let u=await rt(Xt,p,{label:nt(a,l)},{features:{workflow:n.workflow.id,node:n.node.id}});if(!u)return{error:`classify node "${n.node.id}": decision seat unavailable (set decisions.seats.${Xt}.mode)`};let f=u.answers.label,g=f.confidence>=d,m=g?f.choice:ae;return n.log(`[node:${n.node.id}] classify \u2192 ${f.choice} (${f.confidence.toFixed(2)})${g?"":` \u2014 below ${d}, routing to ${ae}`}`),{output:{result:f.choice,label:f.choice,confidence:f.confidence,probabilities:f.probabilities,unsure:!g,port:m},port:m}};var Fe=class{active=new Map;waiters=new Map;async acquire(e,t){let r=this.active.get(e)??0;if(r<t){this.active.set(e,r+1);return}return new Promise(o=>{let s=this.waiters.get(e)??[];s.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,s)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let r=this.waiters.get(e);r&&r.length>0&&r.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},de=new Fe;function tn(n,e){return`${n}:${e}`}var le={stallMinutes:30,maxNudges:2,approval:"step"};var ce=n=>n.run.context;function nn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?n*6e4:null;if(typeof n!="string"||!n.trim())return null;let e=n.trim(),t=/^(\d+(?:\.\d+)?)\s*(m|min|h|d)$/i.exec(e);if(t){let o=Number(t[1]),s=t[2].toLowerCase(),a=o*(s==="d"?864e5:s==="h"?36e5:6e4);return a>0?a:null}let r=/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/i.exec(e);if(r){let o=(((Number(r[1]??0)*24+Number(r[2]??0))*60+Number(r[3]??0))*60+Number(r[4]??0))*1e3;return o>0?o:null}return/^\d+$/.test(e)&&Number(e)*6e4||null}function Cr(n){let e=n.followUp??le,t=n.node.config,r=n.workflow.followUp??{},o=s=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return{stallMinutes:o(t.stallMinutes)||r.stallMinutes||e.stallMinutes,maxNudges:o(t.maxNudges)??r.maxNudges??e.maxNudges,approval:n.workflow.approval??e.approval}}function rn(n){let e=n.node.config.supervise;return typeof e=="boolean"?e:n.run.meta?.followUp===!0}function on(n,e){return["",`[agentx:workflow-step run=${n.id} step=${e}]`,"This is one step of a workflow AgentX is following. When the step is finished, end your reply with a line `RESULT: done` and say what proves it (a link, an id, the text you checked).",`If it will finish later (a deploy still running, an answer still due), say so and report it when it is done with agentx_workflow: {action:"done", runId:"${n.id}", step:"${e}", evidence:"<proof>"}. You will be reminded if nothing happens.`,"If you cannot do it without the owner, end with `RESULT: blocked` and the reason in one line."].join(`
20
- `)}function je(n){return n?["done","approved","skipped","ok","complete","completed"].includes(n)?"done":["blocked","failed","rejected","changes-requested"].includes(n)?"blocked":"wait":"wait"}function Ce(n,e,t){let{stallMinutes:r,maxNudges:o}=Cr(n),s=r*6e4,a=d=>({kind:"agentStep",nodeId:n.node.id,agentId:e,nudges:0,maxNudges:o,stallMs:s,...d?{blocked:d}:{nextNudgeAt:new Date(Date.now()+s).toISOString()}}),i=t.error?"wait":je(t.result);if(i==="blocked"){let d=_r(t.reply)||`${e} says the step is ${t.result}`;return{paused:!0,pausedAt:a(d),blocked:d,output:t.output}}return i==="done"?{output:t.output}:{paused:!0,pausedAt:a(),output:t.output}}function _r(n){return n?(n.split(`
21
- `).map(t=>t.trim()).filter(t=>t&&!/^RESULT:/i.test(t)).at(-1)??"").slice(0,300):""}function sn(n,e,t,r,o){let s=Math.max(1,Math.round(o/6e4));return[`[agentx:workflow-nudge run=${n.id} step=${e} nudge=${t}/${r}]`,`Reminder ${t} of ${r}: the workflow step "${e}"${n.meta?.title?` of "${n.meta.title}"`:""} has shown no progress for ${s} minute(s).`,"Check where it stands and finish it now if you can.",`When it is done, end your reply with \`RESULT: done\` and the proof, or call agentx_workflow {action:"done", runId:"${n.id}", step:"${e}", evidence:"<proof>"}.`,"If you cannot finish it without the owner, end with `RESULT: blocked` and the reason.",t>=r?"This is the last reminder: after it the owner is told the step is blocked.":""].filter(Boolean).join(`
22
- `)}var Lr=async n=>{let e=R(String(n.node.config.text??""),ce(n),{envAllow:n.workflow.envAllow}).trim();if(!e)return{error:`owner.notify "${n.node.id}" needs config.text`};if(!n.owner)return{error:`owner.notify "${n.node.id}": no owner to tell on this node`};try{await n.owner.notify(e,n.run)}catch(t){return{error:`owner.notify "${n.node.id}" failed: ${t?.message??t}`}}return{output:{text:e,sentAt:new Date().toISOString()}}},Ur=async n=>{let e=v(n.node.config,ce(n),{envAllow:n.workflow.envAllow}),t=String(e.ask??e.question??"").trim();if(!t)return{error:`owner.ask "${n.node.id}" needs config.ask (the yes/no question)`};if(!n.owner)return{error:`owner.ask "${n.node.id}": no owner to ask on this node`};let r=Array.isArray(e.choices)?e.choices.map(String).filter(Boolean):void 0;try{let{cardId:o}=await n.owner.ask({title:j(String(e.title??n.run.meta?.title??n.workflow.title),120),ask:j(t,300),recommend:j(String(e.recommend??"Your call."),300),...typeof e.draft=="string"&&e.draft.trim()?{draft:e.draft}:{},...r?.length?{choices:r}:{},...typeof e.context=="string"&&e.context.trim()?{context:j(e.context,600)}:{},...typeof e.expires=="string"&&e.expires.trim()?{expires:e.expires}:{}},n.run,n.node.id);return{paused:!0,pausedAt:{kind:"ownerDecision",nodeId:n.node.id,cardId:o,purpose:"ask"}}}catch(o){return{error:`owner.ask "${n.node.id}": could not raise the card: ${o?.message??o}`}}};function _e(n){let e=v(n.node.config,ce(n),{envAllow:n.workflow.envAllow});return{channel:String(e.channel??"").trim(),chatId:String(e.chatId??"").trim(),...typeof e.accountId=="string"&&e.accountId?{accountId:e.accountId}:{},text:String(e.text??"").trim(),...typeof e.to=="string"&&e.to.trim()?{to:e.to.trim()}:{}}}var Hr=async n=>{let e=_e(n);if(!e.channel||!e.chatId||!e.text)return{error:`person.message "${n.node.id}" needs channel, chatId and text`};if(n.run.meta?.approved?.[n.node.id]===Le(e)){let r=await ue(n,e);return"error"in r?{error:r.error}:{output:{...e,messageId:r.messageId,approved:"start"},port:"sent"}}if(!n.owner)return{error:`person.message "${n.node.id}": no owner to approve it on this node`};let t=e.to?`${e.to} (${e.channel} ${e.chatId})`:`${e.channel} ${e.chatId}`;try{let{cardId:r}=await n.owner.ask({title:j(`Send to ${t}`,120),ask:j(`Send this message to ${t}?`,300),recommend:j(`It is step "${n.node.id}" of ${n.run.meta?.title?`"${n.run.meta.title}"`:`workflow ${n.workflow.id}`}. Edit it if needed, then say yes.`,300),draft:e.text},n.run,n.node.id);return{paused:!0,pausedAt:{kind:"ownerDecision",nodeId:n.node.id,cardId:r,purpose:"send",message:e}}}catch(r){return{error:`person.message "${n.node.id}": could not ask the owner: ${r?.message??r}`}}};function Le(n){return`${n.channel}
23
- ${n.chatId}
24
- ${n.text}`}async function ue(n,e){let t=n.channels[e.channel],r={channel:e.channel,chatId:e.chatId,text:e.text,...e.accountId?{accountId:e.accountId}:{}};if(t?.send)try{return{messageId:await t.send(r)??null}}catch(o){return{error:`send on ${e.channel} failed: ${o?.message??o}`}}if(n.forwardChannelSend)try{return{messageId:(await n.forwardChannelSend(r)).messageId}}catch(o){return{error:`send on ${e.channel} via the mesh failed: ${o?.message??o}`}}return{error:`channel "${e.channel}" is not available here or on a peer`}}var Br=async n=>{let e=v(n.node.config,ce(n),{envAllow:n.workflow.envAllow}),t=typeof e.reminds=="string"&&e.reminds?e.reminds:void 0,r=t?n.run.context[t]:void 0,o=String(e.channel??r?.channel??"").trim(),s=String(e.chatId??r?.chatId??"").trim();if(!o||!s)return{error:`person.wait "${n.node.id}" needs channel and chatId (or reminds: a person.message step)`};let a=nn(e.timeout??"P1D");if(!a)return{error:`person.wait "${n.node.id}": timeout must be minutes, "4h", "2d" or "P2D"`};let i=e.remindAfter===void 0?null:nn(e.remindAfter);if(e.remindAfter!==void 0&&!i)return{error:`person.wait "${n.node.id}": remindAfter must be minutes, "4h", "2d" or "P2D"`};let d=typeof e.maxReminders=="number"?Math.max(0,Math.floor(e.maxReminders)):i?1:0,l=Date.now(),p=typeof e.accountId=="string"&&e.accountId?e.accountId:typeof r?.accountId=="string"&&r.accountId?r.accountId:void 0;return{paused:!0,pausedAt:{kind:"replyWait",nodeId:n.node.id,channel:o,chatId:s,...p?{accountId:p}:{},...typeof e.from=="string"&&e.from?{from:e.from}:{},deadline:new Date(l+a).toISOString(),...i&&d>0?{nextRemindAt:new Date(l+i).toISOString(),remindEveryMs:i}:{},reminders:0,maxReminders:d,...t?{reminds:t}:{}}}};function an(n){if(n.kind==="replyWait"){let e=n.nextRemindAt&&n.reminders<n.maxReminders?n.nextRemindAt:null;return e&&Date.parse(e)<Date.parse(n.deadline)?e:n.deadline}return n.kind==="agentStep"?n.blocked?null:n.nextNudgeAt??null:null}var j=(n,e)=>{let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t},dn={"owner.notify":Lr,"owner.ask":Ur,"person.message":Hr,"person.wait":Br};var U=async n=>({output:n.run.context[n.node.id]??{}}),Kr=async n=>{let e=n.node.config,t=String(e.agentId??""),r=String(e.prompt??"");if(!t)return{error:`agent node "${n.node.id}" missing config.agentId`};let o=rn(n),s=R(r,n.run.context,{envAllow:n.workflow.envAllow})+(o?on(n.run,n.node.id):""),a=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,i=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(i!==void 0&&i!=="report"&&i!=="propose"&&i!=="act")return{error:`agent node "${n.node.id}" has invalid autonomy "${i}" (expected report, propose or act)`};let d=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,l=d?tn(n.workflow.id,n.node.id):null;if(l&&d){let u=de.stats(l);u.active>=d&&n.log(`[node:${n.node.id}] gated: ${u.active} active (cap ${d}), ${u.waiting+1} waiting`),await de.acquire(l,d)}let p=Date.now();try{let u=await n.agents.execute({agentId:t,message:s,workflowRunId:n.run.id,timeoutMinutes:a,...i?{autonomy:i}:{}}),f=Date.now()-p;if(u.error){let k=u.errorKind??"unknown";return n.log(`[node:${n.node.id}] agent "${t}" failed (${k}): ${u.error}`),o?Ce(n,t,{error:`[${k}] ${u.error}`,output:{error:`[${k}] ${u.error}`}}):{error:`[${k}] ${u.error}`}}let m=String(e.resultParser??"acme-result-token")==="json"?mo(u.content):pe(u.content),y={reply:u.content,result:m.result,json:m.json,taskId:u.taskId,durationMs:f,...u.autonomyBlocks?.length?{autonomyBlocks:u.autonomyBlocks}:{}};return o?Ce(n,t,{output:y,result:m.result,reply:u.content}):{output:y}}catch(u){return n.log(`[node:${n.node.id}] agent "${t}" threw: ${u.message}`),{error:u.message}}finally{l&&de.release(l)}},qr=async n=>{let e=Me(n.node,n.run.context);return e?{output:{port:e},port:e}:(n.log(`[node:${n.node.id}] branch matched no case and no default port`),{output:{port:null}})},zr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.text??"");if(!t||!r){let i=String(n.node.config.chatId??""),d=String(n.node.config.channel??""),l=[];return t||l.push(`channel config="${d}" rendered=""`),r||l.push(`chatId config="${i}" rendered=""`),(/\{\{\s*env\./.test(i)||/\{\{\s*env\./.test(d))&&l.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${n.node.id}" needs channel + chatId \u2014 ${l.join("; ")}`}}let s=He(n,e.accountId),a=n.channels[t];if(a?.send)try{return{output:{messageId:await a.send({channel:t,chatId:r,text:o,...s?{accountId:s}:{}})??null}}}catch(i){return{error:`action.send failed: ${i.message}`}}if(n.forwardChannelSend)try{return{output:{messageId:(await n.forwardChannelSend({channel:t,chatId:r,text:o,accountId:s})).messageId,viaMesh:!0}}}catch(i){return n.log(`[node:${n.node.id}] mesh-forward of "${t}" send failed: ${i.message}`),{error:`action.send via mesh failed: ${i.message}`}}return n.log(`[node:${n.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},Jr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.title??""),s=String(e.description??""),a=Array.isArray(e.labels)?e.labels.map(String):[],i=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!r||!o)return{error:`action.createIssue "${n.node.id}" needs project + title`};let d=Be(n),l=n.channels[t];if(!l?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let p=await l.createIssue({project:r,title:o,description:s,labels:a,assignees:i,agentId:d});return p?{output:{issue:{iid:p.iid,url:p.url,webUrl:p.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(p){return{error:`action.createIssue failed: ${p.message}`}}},Yr=async()=>({output:{}}),Gr=async n=>{let e=n.node.config,t=String(e.name??n.node.id),r=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:n.node.id,checkpointName:t,resumeMatch:{...r,...o}}}},Vr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??""),s=Array.isArray(e.add)?e.add.map(String):[],a=Array.isArray(e.remove)?e.remove.map(String):[];if(!r||!o)return{error:`action.setLabel "${n.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(s.length===0&&a.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let i=n.channels[t];if(!i?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=Be(n),l=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.setLabels({project:r,kind:l,iid:o,add:s,remove:a,agentId:d})??[],add:s,remove:a}}},Qr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??"");if(!r||!o)return{error:`action.readLabel "${n.node.id}" needs project + iid`};let s=n.channels[t];if(!s?.getLabels)return{error:`channel "${t}" does not support getLabels`};let a=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await s.getLabels({project:r,kind:a,iid:o})??[]}}},Zr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),s=String(e.emoji??"\u{1F440}");if(!t||!r||!o)return{error:`action.react "${n.node.id}" needs channel + chatId + messageId`};let a=He(n,e.accountId),i=n.channels[t];if(!i?.react)return{error:`channel "${t}" does not support react`};try{return await i.react(r,o,s,a),{output:{emoji:s}}}catch(d){return{error:`action.react failed: ${d.message}`}}},Xr=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),s=String(e.text??""),a=e.parseMode?String(e.parseMode):void 0;if(!t||!r||!o||!s)return{error:`action.editMessage "${n.node.id}" needs channel + chatId + messageId + text`};let i=He(n,e.accountId),d=n.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(r,o,s,a,i)}}}catch(l){return{error:`action.editMessage failed: ${l.message}`}}},eo=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.chatId??""),o=Number(e.durationMs??0);if(!r||!o)return{error:`action.logTime "${n.node.id}" needs chatId + durationMs`};let s=n.channels[t];if(!s?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let a=Be(n);try{return await s.logTimeSpent(r,o,a),{output:{durationMs:o}}}catch(i){return{error:`action.logTime failed: ${i.message}`}}},to=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${n.node.id}" needs url`};let r=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},s;e.body!==void 0&&(s=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let a=await fetch(t,{method:r,headers:o,body:s}),i=await a.text(),d=i;try{d=JSON.parse(i)}catch{}return{output:{ok:a.ok,status:a.status,body:d}}}catch(a){return{error:`action.callHTTP failed: ${a.message}`}}},no=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${n.node.id}" needs actionId`};let r=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:s}=await import("./runner-56G3N7M4.js"),a=new o().get(t);if(!a)return{error:`action.run "${n.node.id}": no action "${t}" in registry`};try{let i=await s(a,r),d={ok:i.ok,output:i.output,status:i.status,durationMs:i.durationMs};return i.errors!==void 0&&(d.errors=i.errors),i.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${i.status})`}}catch(i){return{error:`action.run failed: ${i.message}`}}},ro=async n=>{let e=v(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${n.node.id}" needs a "name" (e.g. "http.fetch")`};let r=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:s}=await import("./builtin-YD7MC572.js");if(!s(t))return{error:`action.builtin "${n.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,r)}}catch(a){let i=a?.name==="ZodError"?`validation: ${a.message}`:a?.message||String(a);return{error:`action.builtin "${t}" failed: ${i}`}}},oo=async n=>{let e=n.node.config,t=n.run.context;return typeof e.path=="string"&&e.path?{output:{value:L(t,e.path)}}:e.template&&typeof e.template=="object"?{output:v(e.template,t,{envAllow:n.workflow.envAllow})}:{output:{}}};function io(n){if(n!=null){if(typeof n=="number")return new Date(Date.now()+n*6e4).toISOString();if(typeof n=="object"&&n&&"minutes"in n){let e=Number(n.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof n=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(n);if(e){let t=Number(e[1]??0),r=Number(e[2]??0),o=Number(e[3]??0),s=Number(e[4]??0),a=((t*24+r)*60+o)*6e4+s*1e3;if(a>0)return new Date(Date.now()+a).toISOString()}}}}var so=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.workflowId??"");if(!r)return{error:`subProcess "${n.node.id}" missing config.workflowId`};let o=n.run.depth??0,s=n.workflow.maxChildDepth??5;if(o+1>=s)return{error:`max child workflow depth ${s} exceeded at ${n.workflow.id} \u2192 ${r} (parent depth ${o})`};let a=e.inputMap,i={};if(a==="*")i={...n.run.context};else if(a&&typeof a=="object")for(let[d,l]of Object.entries(a))l&&typeof l=="object"&&!Array.isArray(l)?i[d]=v(l,n.run.context,{envAllow:n.workflow.envAllow}):typeof l=="string"&&(i[d]={value:R(l,n.run.context,{envAllow:n.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:n.node.id,childRunId:"",childWorkflowId:r},spawnChild:{workflowId:r,input:i}}},ao=U,lo=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.emit "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",s=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:r,scope:o,payload:s},emitSignal:{name:r,scope:o,payload:s}}},co=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.wait "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",s=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:n.node.id,signalName:r,match:s,scope:o}}},uo=async n=>{let e=n.node.config,t=v(e,n.run.context,{envAllow:n.workflow.envAllow}),r=io(t.after??e.after);return r?{paused:!0,pausedAt:{kind:"timerWait",nodeId:n.node.id,fireAt:r}}:{error:`timer.boundary "${n.node.id}" needs config.after (duration or minutes)`}},po=async()=>({output:{}}),fo=async n=>{let e=n.node.config,r=(Array.isArray(e.inputs)?e.inputs:[]).map(a=>typeof a=="string"?R(a,n.run.context,{envAllow:n.workflow.envAllow}):a),o=Array.isArray(e.rules)?e.rules:[];for(let a of o){let i=Array.isArray(a.when)?a.when:[];if(i.length!==r.length)continue;let d=!0;for(let l=0;l<i.length;l++)if(!go(i[l],r[l])){d=!1;break}if(d)return{output:{...a.output??{},matchedPort:a.to??""},port:a.to}}let s=e.default;return{output:{...s?.output??{},matchedPort:s?.to??""},port:s?.to}};function go(n,e){if(n==null||n==="*")return!0;let t=String(n),r=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let s=o[1],a=Number(o[2]),i=typeof r=="number"?r:Number(r);if(Number.isNaN(i))return!1;switch(s){case">":return i>a;case"<":return i<a;case">=":return i>=a;case"<=":return i<=a}}if(t.startsWith("!="))return String(r)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(r))}catch{return!1}return String(r)===t}var ln={"trigger.channel":U,"trigger.manual":U,"trigger.cron":U,"trigger.hook":U,"trigger.form":ao,"trigger.poll":U,agent:Kr,classify:en,branch:qr,transform:oo,"gateway.parallel":po,rule:fo,"action.send":zr,"action.createIssue":Jr,"action.setLabel":Vr,"action.readLabel":Qr,"action.react":Zr,"action.editMessage":Xr,"action.logTime":eo,"action.callHTTP":to,"action.run":no,"action.builtin":ro,subProcess:so,"signal.emit":lo,"signal.wait":co,"timer.boundary":uo,checkpoint:Gr,end:Yr,...dn};function Ue(n){return ln[n]}function He(n,e){if(typeof e=="string"&&e)return e;let t=n.workflow.nodes.find(s=>s.type.startsWith("trigger."));if(!t)return;let o=n.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function Be(n){for(let e=n.run.history.length-1;e>=0;e--){let t=n.run.history[e],r=n.workflow.nodes.find(o=>o.id===t.nodeId);if(r?.type==="agent")return r.config.agentId??void 0}}function pe(n){if(!n)return{};let e=n.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=n.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function mo(n){let{result:e}=pe(n);if(!n)return{result:e};let t=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var J=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function fe(n,e){if(n.name!==e.name||n.scope==="workflow"&&n.workflowId!==e.workflowId)return!1;for(let[t,r]of Object.entries(n.match??{}))if(!(r===void 0||r===""||r==="*")&&e.payload[t]!==r)return!1;return!0}function ho(n,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${n.workflowId}:${n.eventId}`,project:n.project,subject:`workflow:${n.workflowId}:entity:${n.entityRef.backend}:${n.entityRef.id}`,intent:`workflow.${n.triggerSource}`,rawJson:e}}function wo(n){return n.claimed&&n.runId?{agentId:`workflow-run:${n.runId}`,outcome:"dispatched",reason:n.reason??"claimed"}:n.claimed&&!n.runId?{agentId:null,outcome:"halted",reason:n.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:n.reason??"not-claimed"}}function yo(n){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:n.agentId,outcome:n.outcome==="deduped"?"halted":n.outcome,reason:n.outcome==="deduped"?`legacy-dedup: ${n.reason??""}`.trim():n.reason??null})}}function cn(n,e,t,r,o=Date.now){let s=ho(e,t,o),a=wo(r),i=yo(a),d=yt(n,s,i,o);return kt(n,"workflow",d,a,o),d}_n();var Ke=new Set(["completed","failed","canceled"]),bo=4e3,vo=8,qe=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;owner;followUpDefaults;onRunEnded;onBlocked;replyWaiters=null;earlyDone=new Map;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new $e({log:t=>this.log(t)}),this.signals=e.signals??new J,this.events=e.events,this.owner=e.owner,this.followUpDefaults=e.followUp??(()=>le),this.onRunEnded=e.onRunEnded,this.onBlocked=e.onBlocked,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode,rootId:e.rootId})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let r of t){if(r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="signalWait")continue;let o={name:r.pausedAt.signalName,scope:r.pausedAt.scope,workflowId:r.workflowId,match:r.pausedAt.match??{}};if(!fe(o,e))continue;let s=this.store.list().find(a=>a.id===r.workflowId);s&&(await this.commit(r.id,()=>{let a=this.runs.get(r.id);if(!a||a.status!=="paused"||!a.pausedAt||a.pausedAt.kind!=="signalWait"||!fe({name:a.pausedAt.signalName,scope:a.pausedAt.scope,workflowId:a.workflowId,match:a.pausedAt.match??{}},e))return;let i=T(s,a.pausedAt.nodeId),d=i?s.edges.filter(p=>p.from===i.id).map(p=>p.to):[],l={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:a.id,entry:{at:l.receivedAt,nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:l,idempotencyKey:I(a.id,a.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...a.context,[a.pausedAt.nodeId]:l}}),this.log(`[workflow:${s.id}] run ${a.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:a.id,workflowId:s.id,nodeId:a.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:a.eventRootId})}),this.walk(s,r.id,`signal:${e.name}`).catch(a=>this.log(`[workflow:${s.id}] walk-after-signal failed: ${a.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(o=>o.id===(this.runs.get(e.runId)?.workflowId??""));if(!t)return;let r=this.runs.get(e.runId)?.pausedAt?.kind;if(r==="replyWait"||r==="agentStep"){await this.followUpTimer(t,e);return}await this.commit(e.runId,()=>{let o=this.runs.get(e.runId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="timerWait"||o.pausedAt.nodeId!==e.nodeId)return;let s=T(t,e.nodeId),a=s?t.edges.filter(l=>l.from===s.id).map(l=>l.to):[],i=new Date().toISOString(),d={firedAt:i,scheduledFor:e.fireAt};this.runs.recordExecution({runId:o.id,entry:{at:i,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:d,idempotencyKey:I(o.id,e.nodeId,`timer:${e.id}`)},nextPending:a,status:"running",pausedAt:null,context:{...o.context,[e.nodeId]:d}}),this.log(`[workflow:${t.id}] run ${o.id} resumed from timer "${e.nodeId}" (fired ${i})`),this.emitRunEvent({runId:o.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`,rootId:o.eventRootId})}),this.walk(t,e.runId,`timer:${e.id}`).catch(o=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${o.message}`))}async dispatchWorkflow(e){let t=this.store.list().find(d=>d.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let r=this.runs.getActiveByEntity(e.entityRef),o=r?this.runs.get(r):null;if(o&&o.workflowId!==t.id)return this.log(`[workflow:${t.id}] entity ${e.entityRef.id} has run ${o.id} of workflow "${o.workflowId}" \u2014 not dispatching`),{claimed:!1,run:null};let a=t.nodes.find(d=>d.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??a.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let r=String(t.channel??""),o=String(t.chatId??"");if(!r||!o)return;let s=this.channels[r];if(!s)return;let a=typeof t.accountId=="string"?t.accountId:void 0,i=t.event,d=typeof i?.id=="string"?i.id:i?.id!=null?String(i.id):void 0;if(d&&s.react)try{Promise.resolve(s.react(o,d,"\u{1F440}",a)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!s.sendTyping)return;let l=()=>{try{Promise.resolve(s.sendTyping(o,a)).catch(()=>{})}catch{}};l();let p=setInterval(l,bo);this.ackTypingTimers.set(e,p)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(i=>i.fanOut)?t:t.slice(0,1),s=[],a=[];for(let i of o){let d=await this.dispatchOne(i,e.entityRef,e.event,e.trigger);d.claimed&&s.push(i),d.run&&a.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(i=>this.log(`[mesh-broadcast] ${i?.message??i}`)),{claimed:s,runs:a}}matchByTrigger(e,t){let r=this.store.list(),o=[];for(let s of r){if(s.state&&s.state!=="active")continue;if(t){if(!s.mesh?.allowRemote)continue;let l=s.mesh.peers;if(l&&l.length>0&&!l.includes(t.peer))continue}let a=s.nodes.find(l=>l.type.startsWith("trigger."));if(!a)continue;let i=a.config;if(i.source!==e.source||s.project&&e.project&&s.project!==e.project)continue;let d=i.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&E(e.source,d.chat)!==E(e.source,e.chat))continue;if(d.labels?.length){let l=new Set(e.labels??[]);if(!d.labels.some(u=>l.has(u)))continue}}o.push(s)}return o.sort((s,a)=>a.priority-s.priority||s.id.localeCompare(a.id))}async dispatchOne(e,t,r,o){let s=await this.dispatchOneLegacy(e,t,r,o);if(wt("workflow")!=="off")try{cn(pt(),{workflowId:e.id,eventId:r.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:r,trigger:o,entityRef:t}),{claimed:s.claimed,runId:s.run?.id??null})}catch(a){this.log(`[ledger] workflow ${e.id} run ${s.run?.id??"?"} record failed: ${a?.message??a}`)}return s}async dispatchOneLegacy(e,t,r,o){let s=this.runs.getActiveByEntity(t),a=s?this.runs.getHomeNodeByEntity(t):null;if(s&&a&&a!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${s} home'd on "${a}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(a,{workflowId:e.id,event:r,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${a}" failed: ${d.message}`)}return{claimed:!0,run:null}}let i=s?this.runs.get(s):null;if(i)if(i.status==="paused"&&i.pausedAt){if(i.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${i.id} paused on ${i.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!$o(i.pausedAt.resumeMatch,o,r))return this.log(`[workflow:${e.id}] run ${i.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=T(e,i.pausedAt.nodeId),l=d?e.edges.filter(m=>m.from===d.id).map(m=>m.to):[],p={at:new Date().toISOString(),nodeId:i.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:r.payload},idempotencyKey:I(i.id,i.pausedAt.nodeId,`resume:${r.id}`)},u={...i.context,[i.pausedAt.nodeId]:{event:r.payload}},f=i.pausedAt.checkpointName,g=this.runs.recordExecution({runId:i.id,entry:p,nextPending:l,status:"running",pausedAt:null,context:u});g&&(i=g),this.log(`[workflow:${e.id}] run ${i.id} resumed from checkpoint "${f}"`),o.source.endsWith("-message")&&this.startChannelAck(i.id,r.payload)}else return i.status==="running"?(this.log(`[workflow:${e.id}] run ${i.id} already running; dropping concurrent event ${r.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${i.id} is ${i.status}; dropping event ${r.id}`),{claimed:!1,run:null});else{let d=z(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};i=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:r.payload}}),this.log(`[workflow:${e.id}] run ${i.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:i.id,workflowId:e.id,phase:"created",status:i.status,homeNode:i.homeNode,rootId:i.eventRootId}),o.source.endsWith("-message")&&this.startChannelAck(i.id,r.payload)}return this.walk(e,i.id,r.id),{claimed:!0,run:i}}async walk(e,t,r){let o=this.runs.get(t)?.eventRootId,s=()=>this.walkInner(e,t,r);try{await(o?gt({rootId:o},s):s())}finally{this.stopChannelAck(t),await this.settle(t)}}async walkInner(e,t,r){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let s=o.pending.slice(0,vo);await Promise.allSettled(s.map(i=>this.executeNodeAndCommit(e,t,i,r)));let a=this.runs.get(t);if(!a||(o=a,o.status!=="running"))return}}async executeNodeAndCommit(e,t,r,o){let s=I(t,r,o),a=await this.commit(t,()=>{let h=this.runs.get(t);if(!h)return{kind:"done"};if(h.status!=="running")return{kind:"done"};let A=T(e,r);if(!A)return this.log(`[workflow:${e.id}] missing node "${r}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:s,note:"node definition missing from workflow"},nextPending:h.pending.filter(W=>W!==r),status:"failed"}),{kind:"done"};let O=Ue(A.type);return O?h.history.some(W=>W.idempotencyKey===s)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"skipped",idempotencyKey:s+"_dedup",note:"duplicate execution dropped"},nextPending:h.pending.filter(W=>W!==r)}),{kind:"done"}):{kind:"go",run:h,node:A,handler:O}:(this.log(`[workflow:${e.id}] no handler for node type "${A.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:s,note:`no handler for node type "${A.type}"`},nextPending:h.pending.filter(W=>W!==r),status:"failed"}),{kind:"done"})});if(a.kind==="done")return;let{run:i,node:d,handler:l}=a,p=e.edges.filter(h=>h.to===r).map(h=>h.from),u;if(d.type!=="agent"){let h=ye();if(h)try{u=bt(h,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${r}`,workflowRunId:t,workflowId:e.id,workflowNodeId:r,messagePreview:`${d.type} ${r}`})}catch{}}let f=d.retry??{maxAttempts:1,backoffMs:1e3},g={error:"retry-loop did not run"},m=0,y=Date.now(),k=()=>({startedAt:new Date(y).toISOString(),durationMs:Math.max(0,Date.now()-y)});for(;m<f.maxAttempts;){m++;try{g=await l({workflow:e,run:i,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log,owner:this.owner,followUp:this.followUpDefaults()})}catch(h){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${h.message}`),g={error:h.message}}if(!g.error||g.paused)break;if(m<f.maxAttempts){let h=f.backoffMs*Math.pow(2,m-1);this.log(`[workflow:${e.id}] node "${r}" failed (attempt ${m}/${f.maxAttempts}): ${g.error.slice(0,120)} \u2014 retrying in ${h}ms`),await new Promise(A=>setTimeout(A,h))}}let w=this.earlyDone.get(`${t}:${r}`);if(w&&(this.earlyDone.delete(`${t}:${r}`),g.paused&&g.pausedAt?.kind==="agentStep"&&!g.blocked&&(g={output:{...g.output??{},...w}})),u){let h=ye();if(h)try{vt(h,u,{status:g.error?"error":"ok",error:g.error??null})}catch{}}await this.commit(t,async()=>{let h=this.runs.get(t);if(!h)return;let A=new Date().toISOString(),O=h.pending.filter(b=>b!==r);if(g.error){let b=h.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:A,nodeId:r,inputKeys:p,status:"failed",idempotencyKey:s,note:g.error.slice(0,200),...k()},nextPending:O,status:b}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"failed",status:b??h.status,note:g.error.slice(0,200)});return}if(g.paused&&g.pausedAt&&Ke.has(h.status)){this.runs.recordExecution({runId:t,entry:{at:A,nodeId:r,inputKeys:p,status:"skipped",idempotencyKey:s,note:`step ended after the run was ${h.status}`},nextPending:O});return}if(g.paused&&g.pausedAt){let b=g.pausedAt,D=null;if(g.spawnChild&&b.kind==="subProcess"){if(D=await this.spawnChild({parent:h,parentNodeId:r,childWorkflowId:g.spawnChild.workflowId,input:g.spawnChild.input}),!D){this.runs.recordExecution({runId:t,entry:{at:A,nodeId:r,inputKeys:p,status:"failed",idempotencyKey:s,note:`subProcess: child workflow "${g.spawnChild.workflowId}" not found`},nextPending:O,status:"failed"});return}b={...b,childRunId:D.id}}if(this.runs.recordExecution({runId:t,entry:{at:A,nodeId:r,inputKeys:p,status:"paused",idempotencyKey:s,...k(),...g.blocked?{note:`blocked: ${g.blocked}`.slice(0,200)}:{}},nextPending:O,status:"paused",pausedAt:b,...g.output?{context:{...h.context,[r]:g.output}}:{}}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"paused",status:"paused",note:b.kind}),this.scheduleWake(t,e.id,b),g.blocked&&this.markBlocked(t,e,r,g.blocked),D&&this.kickChildWalk(D),b.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:b.nodeId,fireAt:b.fireAt,cancelKey:`${t}:${b.nodeId}`})}catch(Xe){this.log(`[workflow:${e.id}] timer schedule failed: ${Xe.message}`)}return}let W=g.output??{},Dn={...h.context,[r]:W},{nextPending:En}=ie({workflow:e,fromNodeId:r,selectedPort:g.port}),we=[],G={...h.joinCounters??{}};for(let b of En){let D=T(e,b);if(!(D?.type==="gateway.parallel"&&String(D.config?.mode??"fanOut")==="join")){we.push(b);continue}let Q=G[b]??[];Q.includes(r)||Q.push(r),G[b]=Q;let jn=e.edges.filter(Cn=>Cn.to===b).length;Q.length>=jn&&(we.push(b),delete G[b])}let Mn=[...O,...we],V=d.type==="end",Fn=h.status==="running"?V?String(d.config.status??"completed"):"running":void 0,M=this.runs.recordExecution({runId:t,entry:{at:A,nodeId:r,inputKeys:p,status:"ok",output:W,idempotencyKey:s,...k()},nextPending:V?[]:Mn,status:Fn,context:Dn,joinCounters:G});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:V?"completed":"ok",status:M?.status??h.status}),g.emitSignal&&this.emitSignal({name:g.emitSignal.name,scope:g.emitSignal.scope,workflowId:e.id,payload:g.emitSignal.payload}),V&&M&&M.parentRunId&&M.parentNodeId&&this.resumeParent({parentRunId:M.parentRunId,parentNodeId:M.parentNodeId,childRun:M}).catch(b=>this.log(`[workflow:${e.id}] resumeParent failed: ${b.message}`))})}async startRun(e){let t=this.store.get(e.workflowId);if(!t)return{run:null,error:`workflow "${e.workflowId}" not found`};let r=z(t);if(!r)return{run:null,error:`workflow "${t.id}" has no trigger node`};let o=e.entityRef??{backend:"follow-up",id:`${t.id}:${ko()}`},s={tags:[],approvedAtStart:!1,...e.meta,followUp:e.meta?.followUp??!0},a=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:o,initialContext:{[r.triggerId]:e.inputs??{}},meta:s});this.log(`[workflow:${t.id}] follow-up run ${a.id} started${s.startedBy?` by ${s.startedBy}`:""}`),this.emitRunEvent({runId:a.id,workflowId:t.id,phase:"created",status:a.status,homeNode:a.homeNode,rootId:a.eventRootId});let i=this.startMessages(t,a);if((t.approval??this.followUpDefaults().approval)==="start"&&i.some(l=>l.msg)&&!s.approvedAtStart){let l=async u=>(this.runs.setStatus(a.id,"failed"),await this.settle(a.id),{run:this.runs.get(a.id),error:u});if(!this.owner)return l("this workflow needs the owner's approval at start, and there is no owner to ask on this node");let p=i.map(({nodeId:u,msg:f})=>f?`- ${u} to ${f.to?`${f.to} `:""}(${f.channel} ${f.chatId}): ${f.text.replace(/\s+/g," ").slice(0,160)}`:`- ${u}: asked again before it is sent (it uses what an earlier step produces)`);try{let{cardId:u}=await this.owner.ask({title:(s.title??t.title).slice(0,120),ask:`Start "${t.title}" and let it send the message(s) below without asking again?`.slice(0,300),recommend:"Yes if the recipients and the text below are right.",context:p.join(`
25
- `).slice(0,600)},a,r.triggerId);return this.runs.recordExecution({runId:a.id,entry:{at:new Date().toISOString(),nodeId:r.triggerId,inputKeys:[],status:"paused",idempotencyKey:I(a.id,r.triggerId,"start-approval"),note:"waiting for the owner's approval at start"},nextPending:r.pending,status:"paused",pausedAt:{kind:"ownerDecision",nodeId:r.triggerId,cardId:u,purpose:"start"}}),{run:this.runs.get(a.id),awaitingApproval:!0}}catch(u){return l(`could not ask the owner: ${u?.message??u}`)}}return this.walk(t,a.id,`start:${a.id}`).catch(l=>this.log(`[workflow:${t.id}] walk after start failed: ${l.message}`)),{run:a}}startMessages(e,t){let r=e.nodes.find(o=>o.type.startsWith("trigger."))?.id??"";return e.nodes.filter(o=>o.type==="person.message").map(o=>{let s=o.config;if([s.channel,s.chatId,s.text,s.to,s.accountId].flatMap(d=>typeof d=="string"?[...d.matchAll(/\{\{\s*([A-Za-z_][\w-]*)/g)].map(l=>l[1]):[]).some(d=>d!==r&&d!=="env"))return{nodeId:o.id,msg:null};let i=_e({node:o,run:t,workflow:e});return{nodeId:o.id,msg:i.channel&&i.chatId&&i.text?i:null}})}async resumeFromCard(e){let t=e.origin?.kind==="workflow"?e.origin.runId:void 0;if(!t||e.status==="pending")return!1;let r=this.runs.get(t),o=r?this.store.get(r.workflowId):null;if(!r||!o)return!1;let s=e.status==="decided"?e.verdict==="yes"?"yes":"no":"expired",a=!1,i=!1,d,l=r.pausedAt,p=null;return l?.kind==="ownerDecision"&&l.cardId===e.id&&l.purpose==="send"&&s==="yes"&&l.message&&(p=await ue({channels:this.channels,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder)},{...l.message,text:e.text?.trim()||l.message.text})),await this.commit(t,()=>{let u=this.runs.get(t),f=u?.pausedAt;if(!u||u.status!=="paused"||f?.kind!=="ownerDecision"||f.cardId!==e.id)return;a=!0;let g=new Date().toISOString(),m=I(u.id,f.nodeId,`card:${e.id}`);if(f.purpose==="start"){if(s==="yes"){let k={};for(let{nodeId:w,msg:h}of this.startMessages(o,u))h&&(k[w]=Le(h));this.runs.setMeta(u.id,{approvedAtStart:!0,approved:k}),this.runs.recordExecution({runId:u.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"resumed",idempotencyKey:m,note:"approved at start"},nextPending:u.pending,status:"running",pausedAt:null}),i=!0}else this.runs.recordExecution({runId:u.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"failed",idempotencyKey:m,note:s==="no"?"the owner said no at start":"the owner did not answer before the start card expired"},nextPending:[],status:"canceled",pausedAt:null});return}let y={cardId:e.id,verdict:e.verdict??null,status:e.status,choice:e.choice??null,text:e.text??null,note:e.note??null};if(f.purpose==="send"){if(s==="yes"&&p&&"error"in p){d=p.error,this.runs.recordExecution({runId:u.id,entry:{at:g,nodeId:f.nodeId,inputKeys:[],status:"failed",idempotencyKey:m,note:p.error.slice(0,200)},nextPending:[],status:"failed",pausedAt:null});return}let k=s==="yes"?{...y,...f.message,text:e.text?.trim()||f.message?.text,messageId:p&&"messageId"in p?p.messageId:null,approved:"step"}:{...y,...f.message,declined:!0};i=this.resumeOn(o,u,f.nodeId,k,s==="yes"?"sent":"declined",m,s==="yes"?"sent after approval":`not sent: ${s==="no"?"the owner said no":"the card expired"}`);return}i=this.resumeOn(o,u,f.nodeId,y,s,m,`owner answered: ${s}`)}),d&&this.log(`[workflow:${o.id}] run ${t}: approved message not sent: ${d}`),i?this.walk(o,t,`card:${e.id}`).catch(u=>this.log(`[workflow:${o.id}] walk after card failed: ${u.message}`)):a&&await this.settle(t),a}async resumeFromReply(e){let t=`${e.channel}-message`;if(!this.replyWaiters){this.replyWaiters=new Map;for(let s of this.runs.list({limit:500}))s.status==="paused"&&s.pausedAt?.kind==="replyWait"&&this.noteReplyWaiter(s.id,s.pausedAt.channel)}let r=this.replyWaiters.get(e.channel);if(!r?.size)return null;let o=[...r].map(s=>this.runs.get(s)).filter(s=>s?.status==="paused"&&s.pausedAt?.kind==="replyWait"?!0:(s&&r.delete(s.id),!1)).filter(s=>{let a=s.pausedAt;return!(a.channel!==e.channel||E(t,a.chatId)!==E(t,e.chatId)||a.accountId&&e.accountId&&a.accountId!==e.accountId||a.from&&E(t,a.from)!==E(t,e.senderId??""))}).sort((s,a)=>s.createdAt.localeCompare(a.createdAt));for(let s of o){let a=this.store.get(s.workflowId);if(!a)continue;let i=!1;if(await this.commit(s.id,()=>{let d=this.runs.get(s.id),l=d?.pausedAt;if(!d||d.status!=="paused"||l?.kind!=="replyWait"||l.nodeId!==s.pausedAt.nodeId)return;i=!0;let p={text:e.text,from:e.senderId??null,fromName:e.senderName??null,media:e.media??null,channel:e.channel,chatId:e.chatId,at:new Date().toISOString(),reminders:l.reminders};this.timers.cancel({cancelKey:`${d.id}:${l.nodeId}`}),this.resumeOn(a,d,l.nodeId,p,"reply",I(d.id,l.nodeId,`reply:${e.messageId??p.at}`),"reply received")}),!!i)return r.delete(s.id),this.walk(a,s.id,`reply:${e.messageId??Date.now()}`).catch(d=>this.log(`[workflow:${a.id}] walk after reply failed: ${d.message}`)),s.id}return null}async stepDone(e){let t=this.runs.get(e.runId);if(!t)return{ok:!1,error:`no run "${e.runId}"`};let r=this.store.get(t.workflowId);if(!r)return{ok:!1,error:`workflow "${t.workflowId}" is gone`};let o,s=!1;return await this.commit(e.runId,()=>{let a=this.runs.get(e.runId),i=a?.pausedAt;if(a?.status==="running"&&!e.blocked){let l=e.nodeId??a.pending.find(f=>T(r,f)?.type==="agent"),p=l?T(r,l):void 0,u=p?String(p.config.agentId??""):"";if(p?.type==="agent"&&a.pending.includes(p.id)&&(!e.agentId||e.agentId===u||e.agentId===a.meta?.startedBy)){this.earlyDone.set(`${a.id}:${p.id}`,{...e.output??{},result:e.output?.result??"done",doneAt:new Date().toISOString()});return}}if(!a||a.status!=="paused"||i?.kind!=="agentStep"){o=`run ${e.runId} is not waiting on an agent step (it is ${a?.status??"gone"}${i?`, on ${i.kind} ${i.nodeId}`:""})`;return}if(e.nodeId&&e.nodeId!==i.nodeId){o=`run ${e.runId} waits on step "${i.nodeId}", not "${e.nodeId}"`;return}if(e.agentId&&e.agentId!==i.agentId&&e.agentId!==a.meta?.startedBy){o=`step "${i.nodeId}" belongs to ${i.agentId}`;return}if(e.blocked){i.blocked||this.blockStep(r,a,i,e.blocked);return}this.timers.cancel({cancelKey:`${a.id}:${i.nodeId}`}),a.meta?.blocked&&this.runs.setMeta(a.id,{blocked:void 0});let d={...a.context[i.nodeId]??{},...e.output??{},result:e.output?.result??"done",doneAt:new Date().toISOString()};s=this.resumeOn(r,this.runs.get(a.id),i.nodeId,d,void 0,I(a.id,i.nodeId,`done:${d.doneAt}`),"reported done")}),o?{ok:!1,error:o}:(s?this.walk(r,e.runId,`done:${e.runId}`).catch(a=>this.log(`[workflow:${r.id}] walk after step done failed: ${a.message}`)):await this.settle(e.runId),{ok:!0})}async cancelRun(e,t="canceled by the owner"){let r=!1;return await this.commit(e,()=>{let o=this.runs.get(e);if(!o||Ke.has(o.status))return;let s=o.pausedAt?.nodeId??o.pending[0]??"run";this.timers.cancel({runId:e}),this.runs.recordExecution({runId:e,entry:{at:new Date().toISOString(),nodeId:s,inputKeys:[],status:"skipped",idempotencyKey:I(e,s,`cancel:${Date.now()}`),note:t.slice(0,200)},nextPending:[],status:"canceled",pausedAt:null}),r=!0}),r&&await this.settle(e),r}resumeOn(e,t,r,o,s,a,i){let d=T(e,r),{nextPending:l}=d?ie({workflow:e,fromNodeId:r,selectedPort:s}):{nextPending:[]},p=d?X[d.type]:void 0,u=!!p&&s!==void 0&&s!==p.main&&l.length===0,f=[...t.pending.filter(g=>g!==r),...l];return this.runs.recordExecution({runId:t.id,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:u?"failed":"resumed",output:s?{...o,port:s}:o,idempotencyKey:a,note:u?`stopped: ${i}`:i},nextPending:u?[]:f,status:u?"failed":"running",pausedAt:null,context:{...t.context,[r]:s?{...o,port:s}:o}}),this.emitRunEvent({runId:t.id,workflowId:e.id,nodeId:r,phase:u?"failed":"resumed",status:u?"failed":"running",note:i,rootId:t.eventRootId}),!u}async followUpTimer(e,t){let r={};if(await this.commit(t.runId,()=>{let a=this.runs.get(t.runId),i=a?.pausedAt;if(!a||a.status!=="paused"||!i||i.nodeId!==t.nodeId)return;let d=Date.now(),l=new Date(d).toISOString();if(i.kind==="replyWait"){if(d>=Date.parse(i.deadline)){r.walk=this.resumeOn(e,a,i.nodeId,{timedOut:!0,reminders:i.reminders,deadline:i.deadline},"timeout",I(a.id,i.nodeId,`deadline:${i.deadline}`),"no reply before the deadline");return}if(!i.nextRemindAt||d<Date.parse(i.nextRemindAt)||i.reminders>=i.maxReminders){this.scheduleWake(a.id,e.id,i);return}let p=i.reminders+1,u={...i,reminders:p,...p<i.maxReminders&&i.remindEveryMs?{nextRemindAt:new Date(d+i.remindEveryMs).toISOString()}:{nextRemindAt:void 0}},f=i.reminds?a.context[i.reminds]:void 0,g=f&&typeof f.text=="string"&&f.text?{to:"person",msg:{channel:i.channel,chatId:i.chatId,...i.accountId?{accountId:i.accountId}:{},text:`Reminder: ${f.text}`}}:{to:"owner",text:`Still waiting for a reply on ${i.channel} (${i.chatId}) for step "${i.nodeId}" of ${a.meta?.title?`"${a.meta.title}"`:`workflow ${e.id}`}. Deadline: ${i.deadline.slice(0,16).replace("T"," ")} UTC.`};this.runs.recordExecution({runId:a.id,entry:{at:l,nodeId:i.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(a.id,i.nodeId,`remind:${p}`),note:`reminder ${p}/${i.maxReminders} to ${g.to}`},nextPending:a.pending,status:"paused",pausedAt:u}),this.scheduleWake(a.id,e.id,u),r.reminder=g;return}if(i.kind==="agentStep"){if(i.blocked||!i.nextNudgeAt)return;if(d<Date.parse(i.nextNudgeAt)){this.scheduleWake(a.id,e.id,i);return}if(i.nudges>=i.maxNudges){this.blockStep(e,a,i,i.maxNudges?`no progress after ${i.maxNudges} reminder(s) to ${i.agentId}`:`no progress from ${i.agentId} for ${Math.round(i.stallMs/6e4)} minute(s)`);return}let p=i.nudges+1,u={...i,nudges:p,nextNudgeAt:new Date(d+i.stallMs).toISOString()};this.runs.recordExecution({runId:a.id,entry:{at:l,nodeId:i.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(a.id,i.nodeId,`nudge:${p}`),note:`nudge ${p}/${i.maxNudges} to ${i.agentId}`},nextPending:a.pending,status:"paused",pausedAt:u}),this.scheduleWake(a.id,e.id,u),r.nudge={agentId:i.agentId,text:sn(a,i.nodeId,p,i.maxNudges,i.stallMs*p)},this.log(`[workflow:${e.id}] run ${a.id}: nudge ${p}/${i.maxNudges} to ${i.agentId} on step "${i.nodeId}"`)}}),r.walk){this.walk(e,t.runId,`timer:${t.id}`).catch(a=>this.log(`[workflow:${e.id}] walk after deadline failed: ${a.message}`));return}await this.settle(t.runId);let o=r.reminder;if(o?.to==="person"){let a=await ue({channels:this.channels,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder)},o.msg);"error"in a&&this.log(`[workflow:${e.id}] run ${t.runId}: reminder not sent: ${a.error}`)}else if(o?.to==="owner"){let a=this.runs.get(t.runId);a&&await this.owner?.notify(o.text,a).catch(i=>this.log(`[workflow:${e.id}] run ${t.runId}: reminder to the owner failed: ${i?.message??i}`))}let s=r.nudge;s&&this.agents.execute({agentId:s.agentId,message:s.text,workflowRunId:t.runId}).then(async a=>{if(a.error){this.log(`[workflow:${e.id}] run ${t.runId}: nudge turn on ${s.agentId} failed: ${a.error}`);return}let i=pe(a.content).result,d=je(i);d==="blocked"?await this.stepDone({runId:t.runId,nodeId:t.nodeId,blocked:So(a.content)||`${s.agentId} says the step is ${i}`}):d==="done"&&await this.stepDone({runId:t.runId,nodeId:t.nodeId,output:{reply:a.content,result:i,via:"nudge"}})}).catch(a=>this.log(`[workflow:${e.id}] run ${t.runId}: nudge turn failed: ${a?.message??a}`))}blockStep(e,t,r,o){let s={...r,blocked:o.slice(0,300),nextNudgeAt:void 0};this.timers.cancel({cancelKey:`${t.id}:${r.nodeId}`}),this.runs.recordExecution({runId:t.id,entry:{at:new Date().toISOString(),nodeId:r.nodeId,inputKeys:[],status:"paused",idempotencyKey:I(t.id,r.nodeId,`blocked:${Date.now()}`),note:`blocked: ${o}`.slice(0,200)},nextPending:t.pending,status:"paused",pausedAt:s}),this.markBlocked(t.id,e,r.nodeId,o)}markBlocked(e,t,r,o){let s=this.runs.setMeta(e,{blocked:{nodeId:r,reason:o.slice(0,300),at:new Date().toISOString()}});this.log(`[workflow:${t.id}] run ${e} blocked on "${r}": ${o}`),!(!s||!this.onBlocked)&&Promise.resolve(this.onBlocked(s,t,r,o)).catch(a=>this.log(`[workflow:${t.id}] blocked notice failed: ${a?.message??a}`))}noteReplyWaiter(e,t){this.replyWaiters&&(this.replyWaiters.has(t)||this.replyWaiters.set(t,new Set),this.replyWaiters.get(t).add(e))}scheduleWake(e,t,r){r.kind==="replyWait"&&this.noteReplyWaiter(e,r.channel);let o=an(r);if(o)try{this.timers.cancel({cancelKey:`${e}:${r.nodeId}`}),this.timers.schedule({runId:e,workflowId:t,nodeId:r.nodeId,fireAt:o,cancelKey:`${e}:${r.nodeId}`})}catch(s){this.log(`[workflow:${t}] timer schedule failed: ${s.message}`)}}async settle(e){let t=this.runs.get(e);if(t?.meta?.followUp&&(t.status==="running"&&t.pending.length===0&&(t=this.runs.setStatus(e,"completed")??t),!(!Ke.has(t.status)||t.meta?.endNotifiedAt)&&(t=this.runs.setMeta(e,{endNotifiedAt:new Date().toISOString()})??t,this.timers.cancel({runId:e}),this.emitRunEvent({runId:e,workflowId:t.workflowId,phase:"ended",status:t.status,rootId:t.eventRootId}),!!this.onRunEnded)))try{await this.onRunEnded(t,this.store.get(t.workflowId))}catch(r){this.log(`[workflow:${t.workflowId}] end notice for ${e} failed: ${r?.message??r}`)}}async spawnChild(e){let t=this.store.list().find(i=>i.id===e.childWorkflowId);if(!t)return null;let r=z(t);if(!r)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[r.triggerId]={...o[r.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let s={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},a=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:s,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${a.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${a.depth})`),a}kickChildWalk(e){let t=this.store.list().find(r=>r.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(r=>this.log(`[workflow:${t.id}] child walk failed: ${r.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let r=this.store.list().find(o=>o.id===t.workflowId);r&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let s=T(r,e.parentNodeId),a=s?r.edges.filter(d=>d.from===s.id).map(d=>d.to):[],i={childRunId:e.childRun.id,status:e.childRun.status,output:Io(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:i,idempotencyKey:I(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:a,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:i}}),this.log(`[workflow:${r.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:r.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(r,e.parentRunId,`child:${e.childRun.id}`))}};function Io(n){for(let e=n.history.length-1;e>=0;e--){let t=n.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function $o(n,e,t){let r=s=>{let a=n[s];if(a===void 0||a===""||a==="*")return!0;if(Array.isArray(a)){let i=new Set(e.labels??[]);return a.some(d=>i.has(String(d)))}return s==="chat"?E(e.source,String(a))===E(e.source,e.chat):e[s]===a};if(!r("source")||!r("project")||!r("repo")||!r("chat"))return!1;let o=n.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function E(n,e){return e==null?"":n==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function So(n){return n?(n.split(`
26
- `).map(t=>t.trim()).filter(t=>t&&!/^RESULT:/i.test(t)).at(-1)??"").slice(0,300):""}function Ao(n){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let r=t.group?.id??t.sender.id,o=await n.resumeFromReply({channel:t.channel,chatId:r,accountId:t.accountId,senderId:t.sender.id,senderName:t.sender.name,text:t.text,media:t.media,messageId:t.id});if(o)return{blocked:!0,message:`reply taken by workflow run ${o}`};let s=Ro(t.channel);if(!s)return{};let a={backend:t.channel,id:`${t.channel}:${r}`},{claimed:i}=await n.dispatch({trigger:{source:s,chat:r},entityRef:a,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:xo(t)}});return i.length===0?{}:i.every(l=>l.nodes.find(u=>u.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${i.length>1?"s":""}: ${i.map(l=>l.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,r=e.iid,o=e.issueEvent;if(!t||r===void 0)return{};let s=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],a=o?.assignees??o?.object_attributes?.assignee_ids??[],i={backend:"gitlab",id:`${t}#${r}`};return await n.dispatch({trigger:{source:"gitlab-issue",project:t,labels:s},entityRef:i,event:{id:`gitlab-issue:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:r,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:s,assignees:a},project:t,channel:"gitlab",chatId:`${t}:issue:${r}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,r=e.iid,o=e.mrEvent;if(!t||r===void 0)return{};let s=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(l=>typeof l=="string"?l:l?.title).filter(Boolean):[],a=o?.assignees??o?.object_attributes?.assignee_ids??[],i=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${r}`};return await n.dispatch({trigger:{source:"gitlab-mr",project:t,labels:s},entityRef:d,event:{id:`gitlab-mr:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:s,assignees:a,reviewers:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${r}`,iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:s}}}),{}},"on:gitlab-note":async e=>{let t=e.project,r=e.noteId,o=e.noteableType,s=e.noteableIid,a=e.text,i=e.authorUsername,d=e.mentions??[];if(!t||!r||!o||!s)return{};let l=o==="merge_request"?{backend:"gitlab",id:`${t}!${s}`}:{backend:"gitlab",id:`${t}#${s}`};return await n.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:l,event:{id:`gitlab-note:${t}:${o}:${s}:${r}`,payload:{note:{id:r,text:a,author:i,mentions:d,noteableType:o,noteableIid:s,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${s}`,noteId:r,noteableType:o,noteableIid:s,text:a,author:i,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,r=e.pipelineId,o=e.status,s=e.ref;if(!t||!o)return{};let i=e.raw?.merge_request?.iid;if(!i)return{};let d={backend:"gitlab",id:`${t}!${i}`};return await n.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${r}:${o}`,payload:{pipeline:{id:r,status:o,ref:s},project:t,channel:"gitlab",chatId:`${t}:merge_request:${i}`}}}),{}}}}function Ro(n){switch(n){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function xo(n){let e=n.group?.id??n.sender.id;return{channel:n.channel,chatId:e,accountId:n.accountId,text:n.text,fromJid:n.sender.id,sender:{id:n.sender.id,name:n.sender.name,username:n.sender.username},contact:n.channelMeta?.facts?{facts:n.channelMeta.facts}:void 0,group:n.group?{id:n.group.id,name:n.group.name}:void 0,channelMeta:n.channelMeta,replyTo:n.replyTo,replyToText:n.replyToText,media:n.media,event:{id:n.id,timestamp:n.timestamp?.toISOString?.()??new Date().toISOString()}}}var ge=n=>n.trim().toLowerCase().replace(/^@/,"");function Po(n){let e=typeof n.author=="string"?n.author:typeof n.authorUsername=="string"?n.authorUsername:void 0;if(e)return ge(e);let r=n.payload?.sender?.login;return typeof r=="string"&&r?ge(r):void 0}function To(n,e){let t=typeof e.project=="string"?e.project:"";if(n==="on:gitlab-issue"||n==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${n==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(n==="on:gitlab-note"){let r=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!r||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${r}`}if(n==="on:github-issue"||n==="on:github-pr"){let r=e.payload??{},o=typeof e.repo=="string"?e.repo:r.repository?.full_name,s=e.number??r.issue?.number??r.pull_request?.number;return typeof o!="string"||!o||s==null?void 0:`github:${o}#${String(s)}`}}function Wo(n){let e=new Set;for(let t of n.nodes){let r=t.type==="agent"?t.config.agentId:void 0;typeof r=="string"&&r&&e.add(r)}return[...e]}var me=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,r,o=Date.now()){let s=(this.fires.get(e)??[]).filter(a=>o-a<r);if(s.length>=t)return this.fires.set(e,s),!1;for(s.push(o),this.fires.delete(e),this.fires.set(e,s);this.fires.size>this.maxKeys;){let a=this.fires.keys().next().value;if(a===void 0)break;this.fires.delete(a)}return!0}get size(){return this.fires.size}};function ze(n,e,t){let r=n.logged??(n.logged=new Set);r.has(e)||(r.add(e),n.log(t))}function un(n,e,t,r,o){let s=Po(t);if(s&&Array.isArray(r?.ignoreAuthors)&&r.ignoreAuthors.length>0&&r.ignoreAuthors.map(ge).includes(s))return{skip:!0,reason:"ignored-author",detail:`author @${s} is in filter.ignoreAuthors`};if(r?.skipSelfAuthored===!0){let i=Wo(n),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&i.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${s??"?"} is agent "${d}" which this workflow runs`};if(s){let l=new Set(i.flatMap(p=>(o.forgeUsernames?.(p)??[]).map(ge)));if(l.has(s))return{skip:!0,reason:"self-authored",detail:`author @${s} is this workflow's own bot identity`};i.length===0?ze(o,`noagents:${n.id}`,`[workflows] ${n.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):l.size===0&&!("authorAgent"in t)&&ze(o,`noident:${n.id}:${e}`,`[workflows] ${n.id} no forge username known for agent(s) ${i.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let a=r?.maxFiresPerTarget;if(a&&typeof a.count=="number"&&a.count>0){let i=To(e,t);if(i){let d=typeof a.windowMinutes=="number"&&a.windowMinutes>0?a.windowMinutes:60,l=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${n.id}|${i}`,a.count,d*6e4,l))return{skip:!0,reason:"chain-limit",detail:`${i} already fired ${a.count}x within ${d}m (filter.maxFiresPerTarget)`}}else ze(o,`notarget:${n.id}:${e}`,`[workflows] ${n.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function No(n){let e=n.store.list(),t={fireWindow:new me,log:n.log,forgeUsernames:n.forgeUsernames,logged:new Set},r=0,o=0;for(let s of e){if(s.state&&s.state!=="active"){n.log(`[workflows] ${s.id} state=${s.state} \u2014 skipping trigger registration`);continue}let a=s.nodes.find(i=>i.type.startsWith("trigger."));if(a){if(a.type==="trigger.cron"){let i=a.config;if(!i.spec){n.log(`[workflows] ${s.id} trigger.cron missing config.spec \u2014 skipping`);continue}Do({workflowId:s.id,triggerNodeId:a.id,spec:i.spec,timezone:i.timezone??"UTC"},n.dispatcher,n.log),r++}else if(a.type==="trigger.hook"){let i=a.config;if(!i.event||!i.event.startsWith("on:")){n.log(`[workflows] ${s.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}n.hooks.registerHandler(i.event,`workflows:${s.id}`,async d=>{try{let l=typeof d.project=="string"?d.project:void 0;if(s.project&&l&&s.project!==l)return{};if(i.filter){if(Array.isArray(i.filter.topic)&&i.filter.topic.length>0){let m=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!m||!i.filter.topic.map(y=>y.toLowerCase()).includes(m))return{}}if(Array.isArray(i.filter.action)&&i.filter.action.length>0){let m=typeof d.action=="string"?d.action:void 0;if(!m||!i.filter.action.includes(m))return{}}if(Array.isArray(i.filter.mentions)&&i.filter.mentions.length>0){let m=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!i.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(i.filter.noteableType)&&i.filter.noteableType.length>0){let m=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,y=i.filter.noteableType.map(k=>k.toLowerCase());if(!m||!y.includes(m))return{}}if(Array.isArray(i.filter.assigneesAdded)&&i.filter.assigneesAdded.length>0){let m=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!i.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(i.filter.reviewersAdded)&&i.filter.reviewersAdded.length>0){let m=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!i.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>m.includes(w)))return{}}if(Array.isArray(i.filter.labelsAdded)&&i.filter.labelsAdded.length>0){let m=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!i.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>m.includes(w)))return{}}}let p=un(s,i.event,d,i.filter,t);if(p.skip){if(n.log(`[workflows] ${s.id} skipping ${i.event} (${p.reason}): ${p.detail}`),i.passthrough)return{};let m=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(m)?m:[],s.id]}}}let u=Oo(s.id,i.event,d);if(await n.dispatcher.dispatchWorkflow({workflowId:s.id,entityRef:{backend:"hook",id:u},event:{id:`hook:${i.event}:${Date.now().toString(36)}`,payload:{hookEvent:i.event,...d}}}),i.passthrough)return{};let f=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(f)?f:[],s.id]}}}catch(l){return n.log(`[workflows] ${s.id} hook dispatch failed: ${l.message}`),{}}},60),o++}}}return{cronTimers:r,hookSubscribers:o}}function Oo(n,e,t){let r=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&r&&o)return`${n}:${e}:${r}#${o}`;if(e==="on:gitlab-mr"&&r&&o)return`${n}:${e}:${r}!${o}`;if(e==="on:gitlab-pipeline"&&r){let s=t.pipelineId!=null?String(t.pipelineId):"";if(s)return`${n}:${e}:${r}@pipeline:${s}`}return`${n}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Do(n,e,t){let r=()=>{let o;try{o=It(n.spec,new Date,n.timezone)}catch(a){t(`[workflows] ${n.workflowId} cron spec invalid: ${a.message}`);return}let s=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let a=`cron:${n.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:n.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${n.workflowId}@${o.toISOString()}`},event:{id:a,payload:{now:o.toISOString(),spec:n.spec,workflowId:n.workflowId}}})}catch(i){t(`[workflows] ${n.workflowId} cron dispatch failed: ${i.message}`)}finally{r()}})()},s)};r()}import{createHash as Eo}from"crypto";import{existsSync as Mo,mkdirSync as Fo,readFileSync as jo,renameSync as Co,writeFileSync as _o}from"fs";import{resolve as pn}from"path";import{z as H}from"zod";var fn=H.object({actionId:H.string().min(1),everySeconds:H.number().int().min(5).max(86400).default(60),key:H.string().min(1).default("id"),filter:H.array(Ae).default([]),maxPerPoll:H.number().int().min(1).max(500).default(20)}),Lo=5e3,Uo=30;async function Ho(n){let e=new mt().get(n);if(!e)throw new Error(`no action "${n}" in registry`);return ht(e)}function gn(n,e){let t=[],r=0;for(let o of n.split(`
27
- `)){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{r++;continue}if(!a||typeof a!="object"||Array.isArray(a)){r++;continue}let i=L(a,e);if((typeof i!="string"||!i)&&typeof i!="number"){r++;continue}t.push({key:String(i),value:a})}return{items:t,skipped:r}}function Bo(n,e){let t=`${n}:${e}`;return/^[a-zA-Z0-9._:@-]+$/.test(e)&&t.length<=200?t:`${n}:#${Eo("sha256").update(e).digest("hex").slice(0,32)}`}var Je=class{constructor(e){this.opts=e;this.stateDir=pn(e.store.baseDir,"_poll"),this.runAction=e.runAction??Ho}timers=new Map;warned=new Map;stateDir;runAction;resync;start(){return this.resync??=setInterval(()=>{try{this.sync()}catch(e){this.opts.log(`[workflows] poll sync failed: ${e.message}`)}},Uo*1e3),this.sync()}sync(){let e=new Map;for(let t of this.opts.store.list()){let r=this.configOf(t);r&&e.set(t.id,r)}for(let[t,r]of this.timers)e.has(t)||(clearTimeout(r),this.timers.delete(t),this.opts.log(`[workflows] ${t} poll stopped`));for(let[t,r]of e)this.timers.has(t)||(this.schedule(t,r.everySeconds),this.opts.log(`[workflows] ${t} polls action "${r.actionId}" every ${r.everySeconds}s`));return this.timers.size}stop(){this.resync&&clearInterval(this.resync),this.resync=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}async pollOnce(e){let t=this.opts.store.get(e),r=t?this.configOf(t):null;if(!r)return 0;let o;try{o=await this.runAction(r.actionId)}catch(f){return this.warnOnce(e,`poll failed: ${f.message}`),0}if(!o.ok)return this.warnOnce(e,`poll failed (status=${o.status??"?"}): ${(o.errors??"").slice(0,200)}`),0;let{items:s,skipped:a}=gn(o.output,r.key);this.warnOnce(e,a>0?`poll skipped ${a} line(s) that are not a JSON object with "${r.key}"`:"");let i=new Set(s.map(f=>f.key)),d=this.readState(e);if(!d||d.actionId!==r.actionId||d.key!==r.key)return this.writeState(e,{actionId:r.actionId,key:r.key,seen:[...i]},i),this.opts.log(`[workflows] ${e} poll baseline: ${i.size} existing item(s) recorded, no runs started`),0;let l=new Set(d.seen),p=0,u=!1;for(let f of s){if(l.has(f.key))continue;let g=r.filter.every(m=>se(m,f.value));if(!(g&&p>=r.maxPerPoll)){if(l.add(f.key),d.seen.push(f.key),!g){u=!0;continue}this.writeState(e,d,i),u=!1;try{let{run:m}=await this.opts.dispatcher.dispatchWorkflow({workflowId:e,trigger:{source:"poll"},entityRef:{backend:"poll",id:Bo(e,f.key)},event:{id:`poll:${e}:${f.key}`,payload:f.value}});m?p++:this.opts.log(`[workflows] ${e} poll item "${f.key}" started no run`)}catch(m){this.opts.log(`[workflows] ${e} poll dispatch failed for "${f.key}": ${m.message}`)}}}return u&&this.writeState(e,d,i),p}schedule(e,t){let r=setTimeout(()=>{(async()=>{try{await this.pollOnce(e)}catch(a){this.opts.log(`[workflows] ${e} poll failed: ${a.message}`)}if(this.timers.get(e)!==r)return;let o=this.opts.store.get(e),s=o?this.configOf(o):null;s?this.schedule(e,s.everySeconds):this.timers.delete(e)})()},t*1e3);this.timers.set(e,r)}configOf(e){if(e.state&&e.state!=="active")return null;let t=e.nodes.find(o=>o.type.startsWith("trigger."));if(!t||t.type!=="trigger.poll")return null;let r=fn.safeParse(t.config);if(!r.success){let o=r.error.issues.map(s=>`${s.path.join(".")||"config"}: ${s.message}`).join("; ");return this.warnOnce(e.id,`trigger.poll config invalid, not polling (${o})`),null}return r.data}warnOnce(e,t){this.warned.get(e)!==t&&(this.warned.set(e,t),t&&this.opts.log(`[workflows] ${e} ${t}`))}statePath(e){return pn(this.stateDir,`${e}.json`)}readState(e){let t=this.statePath(e);if(!Mo(t))return null;try{let r=JSON.parse(jo(t,"utf-8"));return typeof r.actionId!="string"||typeof r.key!="string"||!Array.isArray(r.seen)?null:{actionId:r.actionId,key:r.key,seen:r.seen.map(String)}}catch{return null}}writeState(e,t,r){let o=t.seen.length-Lo;o>0&&(t.seen=t.seen.filter(a=>r.has(a)||o--<=0)),Fo(this.stateDir,{recursive:!0});let s=this.statePath(e);_o(`${s}.tmp`,JSON.stringify(t)),Co(`${s}.tmp`,s)}};function mn(n){return n.nodes.find(r=>r.type.startsWith("trigger."))?.config?.inputSchema??null}function hn(n,e){if(!n||!e?.properties)return{};let t=n.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,r,o,s]=t,a={};if(e.properties.project&&(a.project=r),o==="push"){let i=s.match(/^refs\/heads\/(.+)$/);i&&e.properties.ref&&(a.ref=i[1])}else{let i=Number(s);Number.isFinite(i)&&(e.properties.id&&(a.id=i),e.properties.iid&&(a.iid=i),e.properties.mrId&&(a.mrId=i),e.properties.issueId&&(a.issueId=i),e.properties.prId&&(a.prId=i))}return a}function wn(n,e){if(!n?.properties)return e;let t={...e};for(let[r,o]of Object.entries(n.properties))t[r]===void 0&&o&&"default"in o&&(t[r]=o.default);return t}function yn(n,e){return!n?.required||!Array.isArray(n.required)?[]:n.required.filter(t=>{let r=e[t];return r===void 0||r===""||r===null})}function qo(n,e){let t=mn(n);if(!t?.properties){let d={};for(let[l,p]of Object.entries(e))p!==void 0&&(d[l]=p);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let r={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(r[d]=e[d]);let o=hn(e.chatId,t),s={...r,...o},a={...s};s=wn(t,s);let i=Object.keys(s).filter(d=>a[d]===void 0&&s[d]!==void 0);return{inputs:s,missing:yn(t,s),filledFrom:{passthrough:Object.keys(r),chatId:Object.keys(o),defaults:i}}}var kn=new Set(["agent","owner.notify","owner.ask","person.message","person.wait","branch","transform","timer.boundary","end"]);function Pa(n){return[`[Saved workflow] This request looks like the saved workflow "${n.title}" (${n.id}).`,`If it is, start it with agentx_workflow {action:"start", workflowId:"${n.id}", title:"<the request in a few words>", tags:["client:<name>"]} instead of doing the steps by hand: AgentX then follows each step, reminds whoever is slow and tells the owner when it is done.`,n.autoStart?"It is marked to start without asking.":"AgentX tells the owner which workflow you chose when you start it."].join(" ")}function Ta(n){if(!Array.isArray(n.steps)||n.steps.length===0)return{ok:!1,error:"steps must be a non-empty list of {id, type, config}"};if(n.steps.length>40)return{ok:!1,error:"a workflow has at most 40 steps"};let e=[{id:"start",type:"trigger.manual",config:{}}];for(let[a,i]of n.steps.entries()){let d=typeof i?.id=="string"&&i.id?i.id:`step${a+1}`,l=typeof i?.type=="string"?i.type:"";if(!kn.has(l))return{ok:!1,error:`step "${d}": type "${l}" is not one an agent may use (${[...kn].join(", ")})`};if(d==="start"||e.some(p=>p.id===d))return{ok:!1,error:`step id "${d}" is used twice (or is "start")`};e.push({id:d,type:l,config:i.config&&typeof i.config=="object"&&!Array.isArray(i.config)?i.config:{}})}let t=!e.some(a=>a.type==="end");t&&e.push({id:"done",type:"end",config:{}});let r=n.edges;if(r===void 0)r=e.slice(0,-1).flatMap((a,i)=>a.type==="end"?[]:[{from:a.id,to:e[i+1].id}]);else if(Array.isArray(r)){let a=r,i=t?e.slice(1,-1).filter(d=>d.type!=="end"&&!a.some(l=>l?.from===d.id)):[];r=[{from:"start",to:e[1].id},...a,...i.map(d=>({from:d.id,to:"done"}))]}let o=x.safeParse({id:n.id,title:n.title,...n.description?{description:n.description}:{},nodes:e,edges:r,tags:n.tags??[],...n.ownerAgent?{ownerAgent:n.ownerAgent}:{},...n.approval==="start"||n.approval==="step"?{approval:n.approval}:{},autoStart:n.autoStart===!0});if(!o.success)return{ok:!1,error:o.error.issues.map(a=>`${a.path.join(".")||"workflow"}: ${a.message}`).join("; ").slice(0,600)};let s=q(o.data);return s.length?{ok:!1,error:s.join("; ").slice(0,600)}:{ok:!0,workflow:o.data}}function Wa(n,e="wf"){let t=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${e}-${t||"run"}-${Date.now().toString(36)}`}function Na(n){let e=Array.isArray(n)?n:typeof n=="string"?n.split(","):[],t=[];for(let r of e){if(typeof r!="string")continue;let o=r.trim().toLowerCase().replace(/\s+/g,"-").slice(0,60);o&&!t.includes(o)&&t.push(o)}return t.slice(0,10)}function Oa(n){if(n?.kind!=="ownerDecision"||!n.message)return n;let{text:e,...t}=n.message;return{...n,message:{...t,text:""}}}function zo(n){let e=n.pausedAt;if(n.status==="running")return n.pending.length?`running ${n.pending.join(", ")}`:"finishing";if(n.status!=="paused"||!e)return n.status;switch(e.kind){case"ownerDecision":return e.purpose==="start"?"your approval to start":e.purpose==="send"?`your approval to send to ${e.message?.to??e.message?.chatId??"a person"}`:"your answer";case"replyWait":return`a reply on ${e.channel} (${e.chatId}) until ${e.deadline.slice(0,16).replace("T"," ")} UTC${e.reminders?`, ${e.reminders} reminder(s) sent`:""}`;case"agentStep":return e.blocked?`blocked: ${e.blocked}`:`${e.agentId} to finish${e.nudges?` (${e.nudges}/${e.maxNudges} reminder(s) sent)`:""}`;case"timerWait":return`a timer until ${e.fireAt.slice(0,16).replace("T"," ")} UTC`;case"signalWait":return`the signal "${e.signalName}"`;case"subProcess":return`the child workflow ${e.childWorkflowId}`;case"checkpoint":return`an event at checkpoint ${e.checkpointName}`}}function Jo(n){return n.pausedAt?.nodeId??n.pending[0]??n.history.at(-1)?.nodeId??"-"}function Da(n,e){let t=n.meta?.title??e?.title??n.workflowId,r=n.status==="completed"?"done":n.status==="canceled"?"stopped":"did not finish",o=[],s=new Set;for(let i of n.history){if(i.status!=="ok"&&i.status!=="resumed"&&i.status!=="failed"||s.has(i.nodeId)&&i.status!=="failed")continue;s.add(i.nodeId);let d=i.output&&typeof i.output.evidence=="string"?` (${i.output.evidence})`:"";o.push(`${i.status==="failed"?"\u2717":"\u2713"} ${i.nodeId}${d}${i.status==="failed"&&i.note?`: ${i.note}`:""}`)}let a=n.history.at(-1);return{title:`Workflow ${r}: ${t}`.slice(0,120),message:[`"${t}" is ${r}${n.meta?.startedBy?` (started by ${n.meta.startedBy})`:""}.`,...n.meta?.tags?.length?[`About: ${n.meta.tags.join(", ")}`]:[],...o.slice(-12),...n.status!=="completed"&&a?.note?[`Why: ${a.note}`]:[],`Run ${n.id}`].join(`
28
- `)}}function Ea(n){let e=n.history.map(t=>t.output&&typeof t.output.evidence=="string"?t.output.evidence:null).filter(t=>!!t);return e.length?e.join(" "):`workflow run ${n.id} (${n.workflowId}) completed`}function Ma(n,e,t,r){let o=n.meta?.title??e?.title??n.workflowId;return{title:`Workflow blocked: ${o}`.slice(0,120),message:[`Step "${t}" of "${o}" cannot go on without you.`,`Why: ${r}`,`When it is sorted, the agent can report it done, or you can stop it: agentx workflow cancel ${n.id}`].join(`
29
- `)}}function Fa(n,e=()=>{}){let t=n.filter(o=>o.meta?.followUp&&(o.status==="running"||o.status==="paused")&&!o.parentRunId).sort((o,s)=>o.createdAt.localeCompare(s.createdAt)),r=new Map;for(let o of t){let s={runId:o.id,workflowId:o.workflowId,title:o.meta?.title??e(o.workflowId)??o.workflowId,status:o.status,step:Jo(o),waitingOn:zo(o),since:o.updatedAt,...o.meta?.startedBy?{startedBy:o.meta.startedBy}:{},blocked:!!o.meta?.blocked,tags:o.meta?.tags??[]},a=s.tags.length?s.tags:["untagged"];for(let i of a)r.has(i)||r.set(i,[]),r.get(i).push(s)}return[...r.entries()].sort(([o],[s])=>o==="untagged"?1:s==="untagged"?-1:o.localeCompare(s)).map(([o,s])=>({tag:o,rows:s}))}var Yo="task",K={start:"start",reply:"reply",done:"done"},_a={enabled:!1,agents:{},exemptQuestions:!0};function La(n,e){if(!n?.enabled)return!1;let t=n.required;return t?.agents?.[e]??t?.enabled??!1}function Ua(n){return!n.workflowRunId&&n.context?.channel!=="workflow"}function Ha(n){return[`[Workflow run ${n}] This task runs inside a workflow run (workflows.required).`,`If it takes more than one step, write your plan first: agentx_workflow {action:"plan", runId:"${n}", steps:["\u2026","\u2026"]}.`,`Report each step: {action:"step", runId:"${n}", step:"<id>", status:"started"|"done"|"failed", note}.`,"If the plan changes, call plan again with the steps left and a reason; steps done stay.","A one-step task needs none of this: your reply is the run's one step."].join(" ")}var Ba="plan / step: when your task names a [Workflow run <id>], write your plan first (runId, steps: short titles) and report each step (runId, step, status started|done|failed, note); call plan again with the steps left and a reason to change it.",Go=new Set(["Read","Grep","Glob","LS","NotebookRead","WebSearch","WebFetch","TodoWrite","TodoRead","ToolSearch","ListMcpResourcesTool","ReadMcpResourceTool"]),bn=/^(get|list|search|read|query|find|show|status|describe|fetch|view|lookup|recall|whoami|check)(_|-|$|[A-Z])/,Vo=new Set(["list","match","status"]),Qo=/^(set|update|delete|clear|create|add|remove|send|post|put|patch|write|run|start|stop|cancel|edit|move|rename|reset|save|upload|merge|close|open|approve|reject|assign|mark)$/;function Ka(n,e){if(Go.has(n))return!0;let t=n.startsWith("mcp__")?n.split("__").slice(2).join("__"):n;if(t==="agentx_workflow")return Vo.has(String(e?.action??"list").toLowerCase());let r=t.replace(/^agentx_/,""),o=r.split(/[_-]/);return Qo.test(o[0].toLowerCase())?!1:bn.test(r)||o.length>1&&bn.test(o.at(-1)??"")}function qa(n){if(!n||typeof n!="object"||n.type!=="assistant")return[];let e=n.message?.content;return Array.isArray(e)?e.filter(t=>t?.type==="tool_use"&&typeof t.name=="string"&&t.name).map(t=>({name:t.name,input:t.input&&typeof t.input=="object"?t.input:void 0})):[]}function za(n,e){let t=e.message.replace(/\s+/g," ").trim().slice(0,80)||`${e.agentId} task`;return n.create({id:e.runId,workflowId:Yo,initialPending:[K.reply],entityRef:{backend:"task",id:e.runId},initialContext:{[K.start]:{agentId:e.agentId,channel:e.channel,...e.chatId?{chatId:e.chatId}:{},preview:e.message.slice(0,200)}},meta:{title:t,tags:[`agent:${e.agentId}`],startedBy:e.agentId,followUp:!1,approvedAtStart:!1,wrap:{agentId:e.agentId,channel:e.channel,mode:"linear",...e.taskId?{taskId:e.taskId}:{}}}})}function Y(n){return new Set(n.history.filter(e=>e.status==="ok"||e.status==="failed").map(e=>e.nodeId))}function Zo(n){if(typeof n=="string")return n.trim();if(n&&typeof n=="object"){let e=n;for(let t of["title","name","step","id"])if(typeof e[t]=="string"&&e[t].trim())return e[t].trim()}return""}function Ja(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return{ok:!1,error:`no wrapped task run "${e}"`};if(r.status!=="running")return{ok:!1,error:`run ${e} is ${r.status}`};if(!Array.isArray(t.steps)||t.steps.length===0)return{ok:!1,error:"plan needs steps: a list of short step titles"};if(t.steps.length>30)return{ok:!1,error:"a plan has at most 30 steps"};let o=t.steps.map(Zo);if(o.some(g=>!g))return{ok:!1,error:"every step needs a title"};let s=r.meta.plan,a=Y(r),i=(s?.steps??[]).filter(g=>a.has(g.id)),d=(s?.steps??[]).reduce((g,m)=>Math.max(g,Number(m.id.replace(/^step/,""))||0),0),l=o.map(g=>({id:`step${++d}`,title:g.slice(0,160)})),p=(s?.steps??[]).filter(g=>!a.has(g.id)).map(g=>g.id),u={steps:[...i,...l],revisions:[...s?.revisions??[],{at:new Date().toISOString(),kind:s?"revise":"plan",...t.reason?{reason:String(t.reason).slice(0,300)}:{},steps:l.map(g=>g.id),dropped:p}]},f=n.patch(e,{meta:{plan:u,wrap:{...r.meta.wrap,mode:"plan"}},pending:l.map(g=>g.id)});return f?{ok:!0,run:f}:{ok:!1,error:`run ${e} vanished`}}function Xo(n,e){let t=e.trim();return n.steps.find(r=>r.id===t)??n.steps.find(r=>r.title.toLowerCase()===t.toLowerCase())??(/^\d+$/.test(t)?n.steps[Number(t)-1]:void 0)}function Ye(n,e){let t=n.meta?.plan?.current;return t?.id===e?t.startedAt:n.history.at(-1)?.at??n.createdAt}function B(n,e,t,r,o={}){let s=new Date().toISOString();return{at:s,nodeId:e,inputKeys:[],status:t,startedAt:r,durationMs:Math.max(0,Date.parse(s)-Date.parse(r)),idempotencyKey:I(n.id,e,`wrap:${t}:${n.history.length}`),...o}}function Ya(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return{ok:!1,error:`no wrapped task run "${e}"`};if(r.status!=="running")return{ok:!1,error:`run ${e} is ${r.status}`};let o=r.meta.plan;if(!o)return{ok:!1,error:'write a plan first: {action:"plan", runId, steps:[\u2026]}'};let s=String(t.status??"done").toLowerCase();if(!["started","done","failed"].includes(s))return{ok:!1,error:"status is started, done or failed"};let a=typeof t.step=="string"||typeof t.step=="number"?String(t.step):"",i=a?Xo(o,a):o.steps.find(f=>!Y(r).has(f.id));if(!i)return{ok:!1,error:`no step "${a}" in the plan (${o.steps.map(f=>`${f.id} ${f.title}`).join("; ")})`};let d=typeof t.note=="string"&&t.note.trim()?t.note.trim().slice(0,300):void 0;if(s==="started"){let f=[i.id,...r.pending.filter(m=>m!==i.id)],g=n.patch(e,{meta:{plan:{...o,current:{id:i.id,startedAt:new Date().toISOString()}}},pending:f});return g?{ok:!0,run:g}:{ok:!1,error:`run ${e} vanished`}}let l=B(r,i.id,s==="done"?"ok":"failed",Ye(r,i.id),d?{note:d}:{}),p=n.recordExecution({runId:e,entry:l,nextPending:r.pending.filter(f=>f!==i.id)});if(!p)return{ok:!1,error:`run ${e} vanished`};let u=o.current?.id===i.id?n.patch(e,{meta:{plan:{...o,current:void 0}}}):p;return u?{ok:!0,run:u}:{ok:!1,error:`run ${e} vanished`}}function ei(n,e,t){let r=n.get(e);if(!r?.meta?.wrap)return null;if(r.status!=="running")return r;let o=r.meta.plan;if(!o&&!t.error&&t.readOnly&&t.exemptQuestions)return n.discard(e),"discarded";let s={turnMs:t.durationMs,...t.inputTokens!==void 0?{inputTokens:t.inputTokens}:{},...t.outputTokens!==void 0?{outputTokens:t.outputTokens}:{}},a=t.error?t.error.slice(0,300):void 0,i=r;if(a&&t.canceled){let d=Y(i),l=o?o.steps.filter(u=>!d.has(u.id)).map(u=>u.id):[K.reply],p=o?.current&&l.includes(o.current.id)?o.current.id:l[0];for(let u of l){let f=u===p?`stopped: ${a}`:"not reached: the turn was stopped",g=B(i,u,"skipped",u===p?Ye(i,u):i.history.at(-1)?.at??i.createdAt,{note:f,...u===p&&!o?{output:s}:{}});i=n.recordExecution({runId:e,entry:g,nextPending:[]})??i}return n.setStatus(e,"canceled")??i}if(o){let d=Y(i),l=o.steps.filter(p=>!d.has(p.id));if(a){let p=(o.current&&l.find(u=>u.id===o.current.id))??l[0];if(p){let u=B(i,p.id,"failed",Ye(i,p.id),{note:a});i=n.recordExecution({runId:e,entry:u,nextPending:[]})??i}}for(let p of l){if(a&&Y(i).has(p.id))continue;let u=B(i,p.id,"skipped",i.history.at(-1)?.at??i.createdAt,{note:a?"not reached: the turn failed":"not reported before the turn ended"});i=n.recordExecution({runId:e,entry:u,nextPending:[]})??i}a&&(i=n.setStatus(e,"failed")??i)}else{let d=B(i,K.reply,a?"failed":"ok",i.createdAt,{output:s,...a?{note:a}:{}});i=n.recordExecution({runId:e,entry:d,nextPending:a?[]:[K.done],...a?{status:"failed"}:{}})??i}if(a)i.status==="running"&&(i=n.setStatus(e,"failed")??i);else{let d=B(i,K.done,"ok",i.history.at(-1)?.at??i.createdAt,{output:s});i=n.recordExecution({runId:e,entry:d,nextPending:[],status:"completed"})??i}return n.get(e)??i}var ti=new Set(["stopped","cancelled","interrupted"]);function Ga(n){return typeof n=="string"&&ti.has(n)}function Va(n,e="interrupted: the daemon stopped during the turn"){let t=0;for(let r of n.list()){if(r.status!=="running"||!r.meta?.wrap)continue;let o=ei(n,r.id,{error:e,canceled:!0,durationMs:Math.max(0,Date.now()-Date.parse(r.createdAt)),readOnly:!1,exemptQuestions:!1});o&&o!=="discarded"&&t++}return t}var ni=new Set(["completed","failed","canceled"]);function Qa(n){let e=n.meta?.plan,t=new Map((e?.steps??[]).map(i=>[i.id,i.title])),r=[],o=n.createdAt;for(let i of n.history){if(i.status==="paused"||i.status==="resumed"){o=i.at;continue}let d=i.durationMs??Math.max(0,Date.parse(i.at)-Date.parse(o));r.push({id:i.nodeId,...t.has(i.nodeId)?{title:t.get(i.nodeId)}:{},status:i.status,startedAt:i.startedAt??o,durationMs:d,...i.note?{note:i.note.slice(0,200)}:{}}),o=i.at}let s=ni.has(n.status)?n.updatedAt:void 0,a=[...n.history].reverse().find(i=>i.output&&typeof i.output.turnMs=="number")?.output;return{v:1,runId:n.id,workflowId:n.workflowId,title:n.meta?.title??n.workflowId,mode:n.meta?.wrap?n.meta.wrap.mode:"workflow",...n.meta?.wrap?.agentId??n.meta?.startedBy?{agentId:n.meta?.wrap?.agentId??n.meta?.startedBy}:{},status:n.status,startedAt:n.createdAt,...s?{endedAt:s,durationMs:Math.max(0,Date.parse(s)-Date.parse(n.createdAt))}:{},steps:r,failedAt:r.find(i=>i.status==="failed"||i.status==="timeout")?.id??null,revisions:Math.max(0,(e?.revisions.length??0)-1),tags:n.meta?.tags??[],...a&&(a.inputTokens!==void 0||a.outputTokens!==void 0)?{tokens:{...a.inputTokens!==void 0?{input:a.inputTokens}:{},...a.outputTokens!==void 0?{output:a.outputTokens}:{}}}:{}}}function Za(n){let e=n.meta?.plan,t=n.meta?.plan?.current?.id??n.pausedAt?.nodeId??n.pending[0]??n.history.at(-1)?.nodeId??"-";if(!e)return t;let r=e.steps.findIndex(o=>o.id===t);return r>=0?`${e.steps[r].title} (${r+1}/${e.steps.length})`:t}import{existsSync as Ge,mkdirSync as vn,readFileSync as Ve,renameSync as In,writeFileSync as $n,appendFileSync as ri}from"fs";import{dirname as Sn,resolve as An}from"path";import{randomBytes as Rn}from"crypto";var oi=".agentx/members.json",ii=".agentx/members-log.jsonl",xn=class{constructor(e=process.cwd(),t=Date.now,r=90){this.now=t;this.retentionDays=r;this.file=An(e,oi),this.logFile=An(e,ii)}file;logFile;prunedAt=0;devices(e){let t=this.load().devices;return e?t.filter(r=>r.personId===e):t}byToken(e){return this.load().devices.find(t=>t.tokenId===e)??null}add(e){let t=this.load();t.devices=t.devices.filter(r=>r.tokenId!==e.tokenId),t.devices.push(e),this.save(t)}update(e,t){let r=this.load(),o=r.devices.find(s=>s.tokenId===e);return o?(Object.assign(o,t),this.save(r),o):null}log(e){try{this.prune()}catch{}try{vn(Sn(this.logFile),{recursive:!0}),ri(this.logFile,JSON.stringify({at:new Date(this.now()).toISOString(),...e})+`
30
- `,{mode:384})}catch{}}prune(e=!1){let t=this.now();if(!e&&t-this.prunedAt<36e5||(this.prunedAt=t,!Ge(this.logFile)))return 0;let r=t-this.retentionDays*864e5,o=Ve(this.logFile,"utf-8").split(`
31
- `).filter(Boolean),s=o.filter(i=>{try{return Date.parse(JSON.parse(i).at)>=r}catch{return!1}});if(s.length===o.length)return 0;let a=`${this.logFile}.${process.pid}.${Rn(4).toString("hex")}.tmp`;return $n(a,s.length?s.join(`
32
- `)+`
33
- `:"",{encoding:"utf-8",mode:384}),In(a,this.logFile),o.length-s.length}events(e,t=50){if(!Ge(this.logFile))return[];let r=Ve(this.logFile,"utf-8").split(`
34
- `).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Ge(this.file))try{let e=JSON.parse(Ve(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){vn(Sn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Rn(4).toString("hex")}.tmp`;$n(t,JSON.stringify(e,null,2)+`
35
- `,{encoding:"utf-8",mode:384}),In(t,this.file)}};import{extname as si}from"path";var Pn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Tn=/<agentx-artifact>[\s\S]*$/i;function id(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Pn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Tn,""):s).trim(),artifacts:r}}function sd(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Pn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Tn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ai={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},ad={bytes:20*1024*1024,perMessage:20,pathChars:512};function dd(n){return ai[si(n).toLowerCase()]??null}var di=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ![what it shows](https://...)."].join(`
36
- `);function ld(n,e,t){return n==="app"&&e&&t!==!1?di:void 0}import{lstatSync as Ze,mkdirSync as li,readdirSync as ci,realpathSync as Qe,unlinkSync as ui}from"fs";import{join as he,resolve as Wn}from"path";var Nn=".agentx/outbox",pi=7*24*60*60*1e3;function fi(n,e){try{let t=Qe(Wn(e,n)),r=he(t,Nn);return Qe(r)===r&&Ze(r).isDirectory()?r:null}catch{return null}}function fd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=Qe(Wn(t,n));Ze(he(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||li(he(o,Nn),{recursive:!0})}catch{return 0}let r=fi(n,t);return r?On(r,(e.now??Date.now())-(e.maxAgeMs??pi)):0}function On(n,e){let t=0;for(let r of ci(n)){let o=he(n,r);try{let s=Ze(o);s.isDirectory()?t+=On(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(ui(o),t++)}catch{}}return t}export{At as a,Dt as b,Et as c,Ti as d,nr as e,Wi as f,x as g,q as h,$ as i,ee as j,yr as k,Te as l,Oe as m,Ee as n,qe as o,Ao as p,No as q,Je as r,Fr as s,qo as t,Pa as u,Ta as v,Wa as w,Na as x,Oa as y,zo as z,Jo as A,Da as B,Ea as C,Ma as D,Fa as E,Yo as F,_a as G,La as H,Ua as I,Ha as J,Ba as K,Ka as L,qa as M,za as N,Ja as O,Ya as P,ei as Q,Ga as R,Va as S,Qa as T,Za as U,xn as V,id as W,sd as X,ad as Y,dd as Z,ld as _,Nn as $,fd as aa};
37
- //# sourceMappingURL=chunk-BI6VG4DV.js.map