agentix-cli 0.114.0 → 0.115.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 (100) hide show
  1. package/dist/{App-Q4UAYL2V.js → App-6OMMZW2M.js} +2 -2
  2. package/dist/{ChatApp-6KGP57OP.js → ChatApp-EDDROHNA.js} +2 -2
  3. package/dist/{agent-5F4EKGQN.js → agent-VPM3EEUB.js} +2 -2
  4. package/dist/{board-dashboard-GGW5ZZLT.js → board-dashboard-4GQ7RTH3.js} +244 -244
  5. package/dist/{board-dashboard-GGW5ZZLT.js.map → board-dashboard-4GQ7RTH3.js.map} +1 -1
  6. package/dist/{chunk-6WNQY6K2.js → chunk-2QSG53RN.js} +2 -2
  7. package/dist/{chunk-YU5NDKPA.js → chunk-4STXRZZS.js} +2 -2
  8. package/dist/{chunk-J3GXZQXY.js → chunk-5FY7PWXW.js} +2 -2
  9. package/dist/{chunk-LP227A6L.js → chunk-7T7IXLLA.js} +2 -2
  10. package/dist/chunk-BU4LE2RT.js +6 -0
  11. package/dist/chunk-BU4LE2RT.js.map +1 -0
  12. package/dist/{chunk-VGI4EZTP.js → chunk-BXYKFWAI.js} +2 -2
  13. package/dist/{chunk-HPY54DU6.js → chunk-CJJULHPJ.js} +2 -2
  14. package/dist/{chunk-QQIWLN3H.js → chunk-ECBVOIIK.js} +8 -8
  15. package/dist/{chunk-QQIWLN3H.js.map → chunk-ECBVOIIK.js.map} +1 -1
  16. package/dist/{chunk-XTO4GRGN.js → chunk-EVXL6X2R.js} +69 -69
  17. package/dist/{chunk-XTO4GRGN.js.map → chunk-EVXL6X2R.js.map} +1 -1
  18. package/dist/{chunk-Y5HBYSJW.js → chunk-IGORU3XR.js} +9 -9
  19. package/dist/{chunk-Y5HBYSJW.js.map → chunk-IGORU3XR.js.map} +1 -1
  20. package/dist/{chunk-YLKCFW2R.js → chunk-J5TZ6QGD.js} +2 -2
  21. package/dist/{chunk-VQM77L54.js → chunk-K3BG77KK.js} +2 -2
  22. package/dist/{chunk-O2RVUM2B.js → chunk-KTF4YF4M.js} +2 -2
  23. package/dist/{chunk-4COYYJJY.js → chunk-MG5LRE5B.js} +2 -2
  24. package/dist/{chunk-VTWSW4KB.js → chunk-PITMPRVP.js} +2 -2
  25. package/dist/{chunk-CYKPDILL.js → chunk-PX2AOZ5G.js} +2 -2
  26. package/dist/{chunk-XX7NXI3Y.js → chunk-QLB76BGE.js} +2 -2
  27. package/dist/{chunk-FDCTFT2Q.js → chunk-S4XSVAAG.js} +2 -2
  28. package/dist/{chunk-HG6QA6EU.js → chunk-SDOSQ6TJ.js} +2 -2
  29. package/dist/chunk-SDOSQ6TJ.js.map +1 -0
  30. package/dist/{chunk-A35RTVMM.js → chunk-UQX2HY5M.js} +2 -2
  31. package/dist/{chunk-C4S5XQKD.js → chunk-YE4HKOS5.js} +2 -2
  32. package/dist/cli.js +1 -1
  33. package/dist/{client-QTXWO46T.js → client-VUNPLVCG.js} +2 -2
  34. package/dist/{config-4XGZYYQP.js → config-HE2LGTTG.js} +2 -2
  35. package/dist/config-mutator-22AVTST2.js +2 -0
  36. package/dist/{doctor-DO262COW.js → doctor-6RDRST4G.js} +2 -2
  37. package/dist/index.d.ts +69 -0
  38. package/dist/index.js +1 -1
  39. package/dist/{program-IEMICVO3.js → program-53CQJEUZ.js} +14 -14
  40. package/dist/{promote-S7SKOKX2.js → promote-4PPJJ6AW.js} +2 -2
  41. package/dist/{query-GOBQ3GL5.js → query-ETDKC7WC.js} +2 -2
  42. package/dist/{registry-HUJEORRW.js → registry-AMETOJ3S.js} +2 -2
  43. package/dist/{request-planner-RYWFGBGK.js → request-planner-VFWWT5XR.js} +2 -2
  44. package/dist/{review-candidates-TXX532LY.js → review-candidates-2PI4CGZO.js} +2 -2
  45. package/dist/routing-M7MDLD7Q.js +2 -0
  46. package/dist/schedule-tool-2EQ53IOQ.js +2 -0
  47. package/dist/scheduler-YGVINPZF.js +2 -0
  48. package/dist/{seat-LK45MTVI.js → seat-TVNR245I.js} +2 -2
  49. package/dist/{select-4LAHUZ74.js → select-KY7B4HAS.js} +2 -2
  50. package/dist/{set-enabled-F2K56HQZ.js → set-enabled-NEINY2I2.js} +2 -2
  51. package/dist/{tool-J4VHHZWN.js → tool-5JGMWH62.js} +2 -2
  52. package/dist/{tool-W3ODKQM2.js → tool-MQQ2W5LJ.js} +2 -2
  53. package/dist/wiki-COAUQ6TQ.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/chunk-HG6QA6EU.js.map +0 -1
  56. package/dist/chunk-ILGLEA3I.js +0 -6
  57. package/dist/chunk-ILGLEA3I.js.map +0 -1
  58. package/dist/config-mutator-QLSA6JOY.js +0 -2
  59. package/dist/routing-IT4YS6X3.js +0 -2
  60. package/dist/schedule-tool-FJKH2ERY.js +0 -2
  61. package/dist/scheduler-ALPDUE4H.js +0 -2
  62. package/dist/wiki-FZHSX4K3.js +0 -2
  63. /package/dist/{App-Q4UAYL2V.js.map → App-6OMMZW2M.js.map} +0 -0
  64. /package/dist/{ChatApp-6KGP57OP.js.map → ChatApp-EDDROHNA.js.map} +0 -0
  65. /package/dist/{agent-5F4EKGQN.js.map → agent-VPM3EEUB.js.map} +0 -0
  66. /package/dist/{chunk-6WNQY6K2.js.map → chunk-2QSG53RN.js.map} +0 -0
  67. /package/dist/{chunk-YU5NDKPA.js.map → chunk-4STXRZZS.js.map} +0 -0
  68. /package/dist/{chunk-J3GXZQXY.js.map → chunk-5FY7PWXW.js.map} +0 -0
  69. /package/dist/{chunk-LP227A6L.js.map → chunk-7T7IXLLA.js.map} +0 -0
  70. /package/dist/{chunk-VGI4EZTP.js.map → chunk-BXYKFWAI.js.map} +0 -0
  71. /package/dist/{chunk-HPY54DU6.js.map → chunk-CJJULHPJ.js.map} +0 -0
  72. /package/dist/{chunk-YLKCFW2R.js.map → chunk-J5TZ6QGD.js.map} +0 -0
  73. /package/dist/{chunk-VQM77L54.js.map → chunk-K3BG77KK.js.map} +0 -0
  74. /package/dist/{chunk-O2RVUM2B.js.map → chunk-KTF4YF4M.js.map} +0 -0
  75. /package/dist/{chunk-4COYYJJY.js.map → chunk-MG5LRE5B.js.map} +0 -0
  76. /package/dist/{chunk-VTWSW4KB.js.map → chunk-PITMPRVP.js.map} +0 -0
  77. /package/dist/{chunk-CYKPDILL.js.map → chunk-PX2AOZ5G.js.map} +0 -0
  78. /package/dist/{chunk-XX7NXI3Y.js.map → chunk-QLB76BGE.js.map} +0 -0
  79. /package/dist/{chunk-FDCTFT2Q.js.map → chunk-S4XSVAAG.js.map} +0 -0
  80. /package/dist/{chunk-A35RTVMM.js.map → chunk-UQX2HY5M.js.map} +0 -0
  81. /package/dist/{chunk-C4S5XQKD.js.map → chunk-YE4HKOS5.js.map} +0 -0
  82. /package/dist/{client-QTXWO46T.js.map → client-VUNPLVCG.js.map} +0 -0
  83. /package/dist/{config-4XGZYYQP.js.map → config-HE2LGTTG.js.map} +0 -0
  84. /package/dist/{config-mutator-QLSA6JOY.js.map → config-mutator-22AVTST2.js.map} +0 -0
  85. /package/dist/{doctor-DO262COW.js.map → doctor-6RDRST4G.js.map} +0 -0
  86. /package/dist/{program-IEMICVO3.js.map → program-53CQJEUZ.js.map} +0 -0
  87. /package/dist/{promote-S7SKOKX2.js.map → promote-4PPJJ6AW.js.map} +0 -0
  88. /package/dist/{query-GOBQ3GL5.js.map → query-ETDKC7WC.js.map} +0 -0
  89. /package/dist/{registry-HUJEORRW.js.map → registry-AMETOJ3S.js.map} +0 -0
  90. /package/dist/{request-planner-RYWFGBGK.js.map → request-planner-VFWWT5XR.js.map} +0 -0
  91. /package/dist/{review-candidates-TXX532LY.js.map → review-candidates-2PI4CGZO.js.map} +0 -0
  92. /package/dist/{routing-IT4YS6X3.js.map → routing-M7MDLD7Q.js.map} +0 -0
  93. /package/dist/{schedule-tool-FJKH2ERY.js.map → schedule-tool-2EQ53IOQ.js.map} +0 -0
  94. /package/dist/{scheduler-ALPDUE4H.js.map → scheduler-YGVINPZF.js.map} +0 -0
  95. /package/dist/{seat-LK45MTVI.js.map → seat-TVNR245I.js.map} +0 -0
  96. /package/dist/{select-4LAHUZ74.js.map → select-KY7B4HAS.js.map} +0 -0
  97. /package/dist/{set-enabled-F2K56HQZ.js.map → set-enabled-NEINY2I2.js.map} +0 -0
  98. /package/dist/{tool-J4VHHZWN.js.map → tool-5JGMWH62.js.map} +0 -0
  99. /package/dist/{tool-W3ODKQM2.js.map → tool-MQQ2W5LJ.js.map} +0 -0
  100. /package/dist/{wiki-FZHSX4K3.js.map → wiki-COAUQ6TQ.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{q as Xt}from"./chunk-S2GAEH2F.js";import{a as Re}from"./chunk-GTJIKXDB.js";import{a as re,b as w}from"./chunk-BGG3ZSMW.js";import{t as Gt,u as Kt}from"./chunk-4COYYJJY.js";import{d as zt,e as qt}from"./chunk-AQASR6KR.js";import{b as Jt,c as Ie,e as B,f as H,h as Yt}from"./chunk-JIT5GPTX.js";import{A as Ae,b as ve,v as Lt,x as ne,y as $e}from"./chunk-J3GXZQXY.js";import{a as Mt,b as Nt}from"./chunk-SHEUCITK.js";import{a as Ut,b as Bt,d as Ht}from"./chunk-Y4CYQV7G.js";import{g as Ot,h as jt,i as Vt,k as Wt,l as Ft}from"./chunk-YLKCFW2R.js";import{q as Et}from"./chunk-VGI4EZTP.js";import{a as Pt,b as Tt}from"./chunk-CYKPDILL.js";import{A as Xr,ba as Se,ia as _t,ja as Ct,ma as Dt,n as te,o as vt,p as $t,q as qr,y as It,z as Rt}from"./chunk-Y5HBYSJW.js";import{f as At,n as Kr}from"./chunk-UIBUZ2N3.js";import{a as xe,h as Gr}from"./chunk-BRK6M6LA.js";import{existsSync as Jr,readdirSync as Yr,readFileSync as Zr,statSync as Qr}from"fs";import{resolve as ei}from"path";function Zt(t,e,n=Date.now(),r=7){let i=r*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(f=>n-f.at<=i),l=a.filter(f=>n-f.at>i&&n-f.at<=i*2),u=c.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ie=new Map;function _a(t,e=1e3){if(!Jr(t))return[];let n=Yr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ei(t,s);return{path:o,mtime:Qr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ie.keys())r.has(s)||ie.delete(s);let i=[];for(let{path:s,mtime:o}of n){let a=ie.get(s);if(a&&a.mtime===o){a.summary&&i.push(a.summary);continue}let c=ti(s,o);ie.set(s,{mtime:o,summary:c}),c&&i.push(c)}return i}function ti(t,e){try{let n=Zr(t,"utf-8").split(`
1
+ import{q as Xt}from"./chunk-S2GAEH2F.js";import{a as Re}from"./chunk-GTJIKXDB.js";import{a as re,b as w}from"./chunk-BGG3ZSMW.js";import{t as Gt,u as Kt}from"./chunk-MG5LRE5B.js";import{d as zt,e as qt}from"./chunk-AQASR6KR.js";import{b as Jt,c as Ie,e as B,f as H,h as Yt}from"./chunk-JIT5GPTX.js";import{A as Ae,b as ve,v as Lt,x as ne,y as $e}from"./chunk-5FY7PWXW.js";import{a as Mt,b as Nt}from"./chunk-SHEUCITK.js";import{a as Ut,b as Bt,d as Ht}from"./chunk-Y4CYQV7G.js";import{g as Ot,h as jt,i as Vt,k as Wt,l as Ft}from"./chunk-J5TZ6QGD.js";import{q as Et}from"./chunk-BXYKFWAI.js";import{a as Pt,b as Tt}from"./chunk-PX2AOZ5G.js";import{A as Xr,ba as Se,ia as _t,ja as Ct,ma as Dt,n as te,o as vt,p as $t,q as qr,y as It,z as Rt}from"./chunk-IGORU3XR.js";import{f as At,n as Kr}from"./chunk-UIBUZ2N3.js";import{a as xe,h as Gr}from"./chunk-BRK6M6LA.js";import{existsSync as Jr,readdirSync as Yr,readFileSync as Zr,statSync as Qr}from"fs";import{resolve as ei}from"path";function Zt(t,e,n=Date.now(),r=7){let i=r*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(f=>n-f.at<=i),l=a.filter(f=>n-f.at>i&&n-f.at<=i*2),u=c.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ie=new Map;function _a(t,e=1e3){if(!Jr(t))return[];let n=Yr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ei(t,s);return{path:o,mtime:Qr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ie.keys())r.has(s)||ie.delete(s);let i=[];for(let{path:s,mtime:o}of n){let a=ie.get(s);if(a&&a.mtime===o){a.summary&&i.push(a.summary);continue}let c=ti(s,o);ie.set(s,{mtime:o,summary:c}),c&&i.push(c)}return i}function ti(t,e){try{let n=Zr(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),i=r.run?.workflowId;if(!i)return null;let s=r.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:i,status:s,at:e}}catch{return null}}var ni={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},ri=(t,e,n)=>{try{return Et(t,e,n)}catch{return null}},Qt=864e5;function Ta(t){let e=t.now??Date.now(),n={...ni,...t.thresholds},r=t.nextFire??ri,i=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(r(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:li(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:en(u),sampledRuns:c.length,flags:[],attention:null};p.flags=tn(p,u,a.schedule,l,null,e,n,r),i.push(nn(p))}let s=new Map(Zt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(_=>_.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((_,ke)=>ke.at-_.at),g=p.map(_=>({at:_.at,status:oi(_.status)})),f=g[0],m=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",P=typeof l.timezone=="string"?l.timezone:"UTC",j={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:$(a.title||a.id,k.text),trigger:m?{schedule:$(y,k.text),timezone:P}:{event:$(typeof l.event=="string"?l.event:"",k.text),filters:ci(l.filter,a)},agent:ai(a),enabled:d,state:u,nextRunAt:m&&d&&y?_e(r(y,new Date(e),P)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let _=g.find(ke=>ke.status==="success");return _?new Date(_.at).toISOString():null})(),consecutiveFailures:en(g),sampledRuns:p.length,flags:[],attention:null},ee=Date.parse(a.updated||a.created||"");j.flags=m?tn(j,g,y,P,Number.isFinite(ee)?ee:null,e,n,r):ii(j,s.get(a.id)?.state==="dormant",Number.isFinite(ee)?ee:null,e,n),i.push(nn(j))}return i.sort(si).slice(0,k.routines)}function en(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function tn(t,e,n,r,i,s,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=sn(l,i,s,o);return p&&c.push(p),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,r),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function ii(t,e,n,r,i){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=sn(o,n,r,i);return a&&s.push(a),s}return t.consecutiveFailures>=i.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function sn(t,e,n,r){let i=Math.max(t??0,e??0);return i&&n-i<r.disabledDays*Qt?null:{reason:"disabled-long",detail:i?`Disabled; no activity for ${Math.floor((n-i)/Qt)} days`:"Disabled and never ran"}}function nn(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var rn={critical:0,warning:1,info:2};function si(t,e){let n=t.attention?rn[t.attention]:3,r=e.attention?rn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function oi(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ai(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function ci(t,e){let n=[],r=e?.project;if(r&&n.push($(`project=${r}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[i,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${i}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function li(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as ae,readdirSync as Ri,readFileSync as _i}from"fs";import{resolve as T}from"path";import{randomBytes as cn}from"crypto";import{existsSync as di,mkdirSync as pi,readdirSync as gi,readFileSync as fi,renameSync as ln,unlinkSync as mi,writeFileSync as hi}from"fs";import{resolve as un}from"path";function on(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ui=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function an(t,e,n,r=Re){let i=await r(t.bin,[...on(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return i.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ui(i.stderr||i.stdout)}`}}async function Ma(t,e,n,r,i=Re){return(await i(t.bin,[...on(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var yi=2e3,bi=t=>an(t.wacli,t.to,t.text);function Ce(t){return un(t,".agentx","whatsapp-triage","drafts")}var wi=t=>/^[a-z0-9-]{8,64}$/.test(t),se=(t,e)=>un(Ce(t),`${e}.json`);function dn(t,e){pi(Ce(t),{recursive:!0});let n=se(t,e.id),r=`${n}.${process.pid}.tmp`;hi(r,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),ln(r,n)}function Fa(t,e,n=Date.now()){let r=e.text.trim().slice(0,yi);if(!r)throw new Error("empty draft");let i={...e,text:r,id:`${n.toString(36)}-${cn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return dn(t,i),i}function oe(t,e){if(!wi(e))return null;try{return JSON.parse(fi(se(t,e),"utf-8"))}catch{return null}}function pn(t,e){let n=Ce(t);return di(n)?gi(n).filter(r=>r.endsWith(".json")).map(r=>oe(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,i)=>r.created_at.localeCompare(i.created_at)):[]}async function gn(t,e,n,r={}){let i=oe(t,e);if(!i||i.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${se(t,e)}.${process.pid}.${cn(3).toString("hex")}.claim`;try{ln(se(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...i,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(r.send??bi)(i).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}dn(t,o);try{mi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as ki,readFileSync as xi,renameSync as Si,writeFileSync as vi}from"fs";import{resolve as $i}from"path";function fn(t){return $i(Ie(t),"_state.json")}function A(t){try{let e=JSON.parse(xi(fn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function z(t,e){ki(Ie(t),{recursive:!0});let n=fn(t),r=`${n}.${process.pid}.tmp`;vi(r,JSON.stringify(e,null,2)+`
@@ -479,4 +479,4 @@ Document the arguments, commands, or files the skill expects. Example:
479
479
  claude-code ${St(t)} --arg value
480
480
  \`\`\`
481
481
  `}Dt();var Ur={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Br(t){return{...Ur,...t??{},regions:{...t?.regions??{}},buffer:{...Ur.buffer,...t?.buffer??{}}}}function Ju(t){try{return Br(Ct(t).screen)}catch{return Br(void 0)}}var Aa=/^[a-z][\w-]*$/,Hr=["window","screen","menubar","notifications"];function Q(t,e,n,r){let i=Number(t);if(t===""||t===null||!Number.isFinite(i)||!n(i))throw new Error(`${e} must be ${r}`);return i}var we=(t,e)=>Q(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function zr(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Yu(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=we(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=we(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=we(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Q(e.stableMs,"stableMs",i=>Number.isInteger(i)&&i>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Q(e.changeThreshold,"changeThreshold",i=>i>=0&&i<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let i={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Aa.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete i[s]:i[s]=zr(o)}n.regions=i}if(e.buffer&&typeof e.buffer=="object"){let i=e.buffer,s={...n.buffer??{}};"enabled"in i&&(s.enabled=!!i.enabled),"seconds"in i&&(s.seconds=Q(i.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in i&&(s.fps=Q(i.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in i&&(s.maxPixels=we(i.maxPixels,"buffer.maxPixels")),"region"in i&&(s.region=String(i.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!Hr.includes(r)&&!n.regions?.[r])try{zr(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Hr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Zt as a,_a as b,tt as c,Bs as d,Hs as e,cl as f,ll as g,ul as h,rr as i,pl as j,fl as k,E as l,ir as m,k as n,Ta as o,Ma as p,bi as q,Fa as r,gn as s,A as t,qa as u,Ga as v,bn as w,Qa as x,q as y,gc as z,vn as A,hl as B,nt as C,sr as D,wl as E,Sl as F,wr as G,Xl as H,Jl as I,nu as J,Uo as K,ru as L,mc as M,hc as N,yc as O,bc as P,wc as Q,kc as R,Sc as S,vc as T,Tc as U,Oe as V,Ec as W,Lc as X,G as Y,K as Z,Ko as _,pu as $,gu as aa,fu as ba,mu as ca,ut as da,hu as ea,We as fa,Fe as ga,ge as ha,ls as ia,ds as ja,Vc as ka,Be as la,He as ma,ps as na,gs as oa,Bn as pa,Gn as qa,Wc as ra,hs as sa,Fc as ta,$s as ua,Rs as va,ze as wa,Cs as xa,Kn as ya,L as za,Pr as Aa,Tr as Ba,Er as Ca,Su as Da,ra as Ea,Mr as Fa,Nr as Ga,Eu as Ha,Lu as Ia,wa as Ja,Mu as Ka,jr as La,fe as Ma,Qc as Na,er as Oa,qe as Pa,Qe as Qa,ol as Ra,Vu as Sa,Wu as Ta,Fu as Ua,Uu as Va,Bu as Wa,Hu as Xa,zu as Ya,qu as Za,Gu as _a,Ur as $a,Br as ab,Ju as bb,Hr as cb,Yu as db};
482
- //# sourceMappingURL=chunk-6WNQY6K2.js.map
482
+ //# sourceMappingURL=chunk-2QSG53RN.js.map
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
48
48
  ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
49
49
  ${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
50
50
  ${c.join(`
51
- `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-HUJEORRW.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
51
+ `)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-AMETOJ3S.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
52
52
 
53
53
  ${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
54
54
  Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
123
123
  Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
124
124
 
125
125
  `)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
126
- //# sourceMappingURL=chunk-YU5NDKPA.js.map
126
+ //# sourceMappingURL=chunk-4STXRZZS.js.map
@@ -1,4 +1,4 @@
1
- import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-VGI4EZTP.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{y as Ce,z as hn}from"./chunk-A35RTVMM.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{f as ie,n as gn}from"./chunk-UIBUZ2N3.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(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){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
1
+ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-BXYKFWAI.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{y as Ce,z as hn}from"./chunk-UQX2HY5M.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{f as ie,n as gn}from"./chunk-UIBUZ2N3.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(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){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var ft=200,Pn=7,gt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=U(e,".agentx/memory"),this.ledger=new Ke(U(e,".agentx/wiki")),pt(this.memoryDir)||$n(this.memoryDir,{recursive:!0})}filePath(e){return U(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||oe(t.content))return!1;let n=t.source.trust??_e(t.source.channel),i=t.review??Le(n),o={...t,source:{...t.source,trust:n},...i?{review:i}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Rn(this.filePath(e),JSON.stringify(o)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!pt(t))return[];try{let{mtimeMs:n,size:i}=xn(t),o=this.parsedCache.get(t);if(o&&o.mtimeMs===n&&o.size===i)return o.facts.slice();let a=ut(t,"utf-8").split(`
4
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:n,size:i,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,n=8){let i=this.getAll(t).filter(ae);if(i.length===0)return[];let o=i.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=U(this.memoryDir,`${t}_bm25_cache.json`),a=je(o,s),d=We(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=i.map((g,h)=>{let m=c.get(h)??0;return g.category==="commitment"&&(m+=1),{memory:g,score:m}}).filter(g=>g.score>0);if(p.length===0)return i.slice(-n);let f=p.sort((g,h)=>h.score-g.score).slice(0,n).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return lt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return ct(e,t)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),i=new Set(t),o=!1;for(let s of n)if(i.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),o=!0}o&&le(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
@@ -25,4 +25,4 @@ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7
25
25
  `).filter(Boolean),i=[];for(let o=n.length-1;o>=0&&i.length<t;o--)try{let s=JSON.parse(n[o]);(!e||s.person===e)&&i.push(s)}catch{}return i}load(){if(Oe(this.file))try{let e=JSON.parse(Ne(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Gt(Qt(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${en(4).toString("hex")}.tmp`;Zt(t,JSON.stringify(e,null,2)+`
26
26
  `,{encoding:"utf-8",mode:384}),Vt(t,this.file)}};import{extname as ui}from"path";var nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,rn=/<agentx-artifact>[\s\S]*$/i;function Ps(r,e=1/0,t=!1){let n=[],i=String(r??"");if(!/<agentx-artifact>/i.test(i))return{text:i,artifacts:n};let o=i.replace(nn,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&n.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";n.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?o.replace(rn,""):o).trim(),artifacts:n}}function Ts(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let i=t.replace(nn,(o,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?i.replace(rn,""):i).trim()}return n.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(i,o,s)=>o===void 0||s===void 0?i:`[${o||s}](${s})`)}var pi={".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"}},Os={bytes:20*1024*1024,perMessage:20,pathChars:512};function Ns(r){return pi[ui(r).toLowerCase()]??null}var fi=["[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(`
27
27
  `);function Ds(r,e,t){return r==="app"&&e&&t!==!1?fi:void 0}import{lstatSync as Ee,mkdirSync as gi,readdirSync as mi,realpathSync as De,unlinkSync as hi}from"fs";import{join as ne,resolve as on}from"path";var sn=".agentx/outbox",yi=7*24*60*60*1e3;function wi(r,e){try{let t=De(on(e,r)),n=ne(t,sn);return De(n)===n&&Ee(n).isDirectory()?n:null}catch{return null}}function js(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let i=De(on(t,r));Ee(ne(i,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||gi(ne(i,sn),{recursive:!0})}catch{return 0}let n=wi(r,t);return n?an(n,(e.now??Date.now())-(e.maxAgeMs??yi)):0}function an(r,e){let t=0;for(let n of mi(r)){let i=ne(r,n);try{let o=Ee(i);o.isDirectory()?t+=an(i,e):Math.max(o.mtimeMs,o.ctimeMs)<e&&(hi(i),t++)}catch{}}return t}export{st as a,gt as b,mt as c,Fi as d,Nn as e,Wi as f,$ as g,pe as h,v as i,B as j,Bn as k,he as l,we as m,be as n,xe as o,Hr as p,qr as q,Te as r,ar as s,ai as t,tn as u,Ps as v,Ts as w,Os as x,Ns as y,Ds as z,sn as A,js as B};
28
- //# sourceMappingURL=chunk-J3GXZQXY.js.map
28
+ //# sourceMappingURL=chunk-5FY7PWXW.js.map
@@ -1,7 +1,7 @@
1
- import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{ja as S,ma as L}from"./chunk-Y5HBYSJW.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
1
+ import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{ja as S,ma as L}from"./chunk-IGORU3XR.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
2
2
  `):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
3
3
  `)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
4
4
  `),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
5
5
  `)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
6
6
  `))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,J as b,ke as c,G as d,V as e,ne as f};
7
- //# sourceMappingURL=chunk-LP227A6L.js.map
7
+ //# sourceMappingURL=chunk-7T7IXLLA.js.map
@@ -0,0 +1,6 @@
1
+ import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-UQX2HY5M.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-FX3D7YON.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
+ `,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
+ `).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
+ `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
+ `),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
6
+ //# sourceMappingURL=chunk-BU4LE2RT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/decisions/seats/wiki-rerank.ts","../src/graph/starter-schema.ts","../src/graph/store.ts","../src/graph/classifier.ts","../src/decisions/seats/intent-path.ts"],"sourcesContent":["import { choice, noul } from \"../questions\"\nimport type { AnswersFor, ChoiceAnswer, NoulAnswer, StateValue } from \"../types\"\n\n// Re-ranking a BM25 shortlist.\n//\n// Measured on the operator's own wiki (11,656 articles, 12 queries):\n// BM25 alone gets R@1 33.3%, R@3 41.7%. Two thirds of queries do not put\n// the right article first. BM25 is a bag-of-words match, so it does well\n// on \"gitlab token expired\" and badly on \"the bot keeps repeating itself\n// what is wrong\" — the synonym cases score 33% / 33%.\n//\n// Shape follows TypeSafe's semantic_find cookbook rather than their\n// rerank one. Rerank scores each query-candidate pair separately, which\n// is N calls; semantic_find scores 218 line ids against one query with a\n// single Choice, and the per-option probabilities ARE the ranking. One\n// call for the whole shortlist, and the candidates are compared against\n// each other rather than each judged alone — which is what ranking means.\n//\n// The companion Noul is the part that keeps this honest. A Choice must\n// return something: asked which of 30 articles answers a question the\n// wiki has no answer to, it will still name one, with a confident-looking\n// probability. `answerable` is the question that can say no, and code\n// reads it first.\n\nexport const WIKI_RERANK_SEAT = \"wiki-rerank\"\n\n// Measured on the 12-query eval, sweeping candidate count against\n// excerpt length under a fixed state budget:\n//\n// k=120 x 150 chars R@1 25.0% (worse than BM25's 33.3%)\n// k=60 x 300 chars R@1 41.7%\n// k=30 x 600 chars R@1 41.7%\n// k=30 x 900 chars R@1 50.0% <- default\n// k=20 x 1100 chars R@1 50.0%\n//\n// Candidates and excerpt trade against one another, and excerpt wins.\n// More candidates raises the ceiling — what the shortlist could contain —\n// while starving the re-ranker of the text it needs to rank with. At 150\n// characters a candidate is barely more than its title, and the result is\n// worse than no re-ranking at all. Raise k only alongside the state\n// budget, never instead of the excerpt.\nexport const DEFAULT_SHORTLIST = 30\nexport const DEFAULT_EXCERPT_CHARS = 900\n\nexport interface RerankCandidate {\n id: string\n title: string\n tags?: string[]\n excerpt: string\n}\n\nexport interface RerankInput {\n query: string\n candidates: RerankCandidate[]\n /** Per-candidate excerpt budget. See DEFAULT_EXCERPT_CHARS — this is\n * the lever that actually moves accuracy. */\n excerptChars?: number\n}\n\nexport function rerankState(input: RerankInput): StateValue {\n const budget = input.excerptChars ?? DEFAULT_EXCERPT_CHARS\n return {\n query: input.query,\n candidates: input.candidates.map((c) => ({\n id: c.id,\n title: c.title,\n tags: c.tags?.length ? c.tags.join(\", \") : null,\n excerpt: clip(c.excerpt, budget),\n })),\n }\n}\n\n/** Built per call, because the option set IS the candidate set. */\nexport function rerankQuestions(candidates: RerankCandidate[]) {\n const criteria: Record<string, string> = {}\n for (const c of candidates) criteria[c.id] = c.title\n return {\n best: choice(criteria, \"Which candidate answers the query?\"),\n answerable: noul(\"Do any of the candidates answer the query?\"),\n }\n}\n\nexport type RerankAnswers = AnswersFor<ReturnType<typeof rerankQuestions>>\n\nexport interface RerankResult {\n /** Candidate ids, best first, by the Choice's per-option probability. */\n ranked: string[]\n scores: Record<string, number>\n /** P(the shortlist contains an answer at all). */\n answerable: number\n /** The Choice's own confidence — flat means it could not separate them. */\n confidence: number\n}\n\n/**\n * Turn one answer into a ranking.\n *\n * Ties keep the incoming order, so a Choice that genuinely cannot\n * separate the candidates degrades to BM25's ranking rather than to an\n * arbitrary one.\n */\nexport function toRanking(\n answers: RerankAnswers,\n candidates: RerankCandidate[],\n): RerankResult {\n const best = answers.best as ChoiceAnswer\n const scores: Record<string, number> = {}\n for (const c of candidates) scores[c.id] = best.probabilities[c.id] ?? 0\n\n const order = new Map(candidates.map((c, i) => [c.id, i]))\n const ranked = [...candidates.map((c) => c.id)].sort((a, b) => {\n const diff = scores[b] - scores[a]\n return diff !== 0 ? diff : (order.get(a) ?? 0) - (order.get(b) ?? 0)\n })\n\n return {\n ranked,\n scores,\n answerable: (answers.answerable as NoulAnswer).noul,\n confidence: best.confidence,\n }\n}\n\nfunction clip(text: string, max: number): string {\n const flat = String(text ?? \"\").replace(/\\s+/g, \" \").trim()\n return flat.length > max ? flat.slice(0, max) : flat\n}\n","import type { GraphSchema } from \"./types\"\n\n/**\n * Ships with the install. When .agentx/graph/schema.json is missing,\n * the store seeds this so a fresh daemon has something to classify\n * against.\n *\n * v2 — Phase 1 of the classifier-retire plan: verb-level intent\n * taxonomy. The classifier now answers ONLY \"what kind of work is\n * this\" — it does not embed client/project/agent in the leaf because\n * those already live on the event metadata (project, subject,\n * agentId). One copy of \"review.merge-request\" instead of one per\n * client.\n *\n * Two levels:\n * category — broad work area (code/ops/support/admin/knowledge/social/system)\n * verb — specific intent (review.merge-request, deploy.staging, etc.)\n *\n * The category is closed-set; the verb is open-set so the operator\n * can add new ones via `agentx graph review` over time. Most paths\n * will reuse the seeded verbs below.\n *\n * Why so few levels: every level is information the classifier\n * actually has to decide. The previous v1 schema (scope > location >\n * org > unit > activity) re-encoded data already on the event —\n * forcing a 5-LLM-question prompt to recover what we already knew.\n */\nexport const STARTER_SCHEMA: GraphSchema = {\n version: 2,\n levels: [\n {\n id: \"category\",\n description: \"Top-level kind of work. Closed set — pick the closest fit.\",\n axes: [\n {\n name: \"kind\",\n type: \"enum\",\n values: [\n \"code\", // anything code-related: review, fix, implement, refactor\n \"ops\", // infra: deploy, monitor, rollback, scale, incident\n \"support\", // human-facing: answer question, triage, route\n \"admin\", // governance: config change, scheduling, token, role\n \"knowledge\", // wiki, docs, research, summarize\n \"social\", // marketing, comms, brief, content\n \"system\", // internal infrastructure (rare; mostly classifier itself)\n ],\n description: \"Which category this work belongs in.\",\n },\n ],\n },\n {\n id: \"verb\",\n description: \"Specific intent — verb-level only, NOT client/project-bound.\",\n axes: [\n {\n name: \"name\",\n type: \"free\",\n description:\n \"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, \" +\n \"investigate.error, deploy.staging, deploy.production, rollback.release, \" +\n \"spec.feature, triage.issue, document.feature, chat.greeting, \" +\n \"chat.support-request, schedule.add, config.change, ingest.contact, \" +\n \"transcribe.audio, brief.daily, summarize.thread, plan.work.\",\n },\n ],\n },\n ],\n leafInput: {\n name: \"input\",\n type: \"enum\",\n values: [\n \"telegram\",\n \"whatsapp\",\n \"slack\",\n \"discord\",\n \"gitlab-mr\",\n \"gitlab-issue\",\n \"github-issue\",\n \"github-pr\",\n \"cron\",\n \"webhook\",\n \"mesh\",\n \"http\",\n ],\n description: \"Where the message entered the system.\",\n },\n leafOutput: {\n name: \"output\",\n type: \"free\",\n description:\n \"One short sentence describing what the agent is expected to produce. \" +\n \"Generic — refers to the verb's outcome, not the specific client/project \" +\n \"(those are on the event metadata already).\",\n },\n}\n\n/** What each category covers, in the words a reviewer would use to file a\n * message. Category nodes were seeded with only their `kind`, so a model\n * picking between them saw bare ids; the boundaries below are the ones a\n * labelled sample of seat answers got wrong most (support read as social\n * or admin, code read as system). */\nexport const CATEGORY_DESCRIPTIONS: Record<StarterCategory, string> = {\n code: \"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.\",\n ops: \"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.\",\n support: \"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.\",\n admin: \"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.\",\n knowledge: \"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.\",\n social: \"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.\",\n system: \"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this.\",\n}\n\n/** Pre-seeded verbs shipped with v2. The classifier picks from these\n * first; new verbs go through the review queue before they're\n * committed (so the taxonomy doesn't drift). Adding to this list is\n * cheap — the seed runs once when nodes.json is empty. */\nexport type StarterCategory = \"code\" | \"ops\" | \"support\" | \"admin\" | \"knowledge\" | \"social\" | \"system\"\n\nexport const STARTER_VERB_NODES: Array<{\n category: StarterCategory\n verb: string\n description?: string\n}> = [\n // code\n { category: \"code\", verb: \"review.merge-request\", description: \"Review a GitLab MR or GitHub PR\" },\n { category: \"code\", verb: \"review.code-change\", description: \"General code review (snippet, diff)\" },\n { category: \"code\", verb: \"fix.bug\", description: \"Fix a reported bug\" },\n { category: \"code\", verb: \"implement.feature\", description: \"Build a new feature\" },\n { category: \"code\", verb: \"investigate.error\", description: \"Investigate a failing test, exception, pipeline\" },\n { category: \"code\", verb: \"refactor.code\", description: \"Restructure existing code without behaviour change\" },\n { category: \"code\", verb: \"spec.feature\", description: \"Write or update a feature spec / RFC\" },\n { category: \"code\", verb: \"triage.issue\", description: \"Classify, label, or assign an issue\" },\n { category: \"code\", verb: \"answer.code-question\", description: \"Answer a code-related question\" },\n\n // ops\n { category: \"ops\", verb: \"deploy.staging\", description: \"Deploy to a staging/preview environment\" },\n { category: \"ops\", verb: \"deploy.production\", description: \"Deploy to production\" },\n { category: \"ops\", verb: \"rollback.release\", description: \"Roll back a release\" },\n { category: \"ops\", verb: \"investigate.incident\", description: \"Investigate a production incident\" },\n { category: \"ops\", verb: \"monitor.system\", description: \"Check system status / metrics\" },\n { category: \"ops\", verb: \"rotate.credential\", description: \"Rotate a token, key, certificate\" },\n { category: \"ops\", verb: \"audit.security\", description: \"Review for security issues\" },\n\n // support\n { category: \"support\", verb: \"chat.greeting\", description: \"A casual hello, no actionable request\" },\n { category: \"support\", verb: \"chat.support-request\", description: \"End-user / customer asking for help\" },\n { category: \"support\", verb: \"chat.casual\", description: \"Informal back-and-forth chat\" },\n { category: \"support\", verb: \"answer.question\", description: \"Answer an open-ended question\" },\n { category: \"support\", verb: \"route.request\", description: \"Forward a request to the right agent\" },\n\n // admin\n { category: \"admin\", verb: \"config.change\", description: \"Change agentx.json / environment / config\" },\n { category: \"admin\", verb: \"schedule.add\", description: \"Add a new cron / scheduled task\" },\n { category: \"admin\", verb: \"schedule.remove\", description: \"Remove or disable a schedule\" },\n { category: \"admin\", verb: \"token.create\", description: \"Mint a scoped API token\" },\n { category: \"admin\", verb: \"agent.add\", description: \"Configure a new agent\" },\n { category: \"admin\", verb: \"channel.add\", description: \"Wire up a new channel\" },\n\n // knowledge\n { category: \"knowledge\", verb: \"document.feature\", description: \"Write or update documentation\" },\n { category: \"knowledge\", verb: \"summarize.thread\", description: \"Summarize a long conversation/thread\" },\n { category: \"knowledge\", verb: \"research.topic\", description: \"Investigate / gather info on a topic\" },\n { category: \"knowledge\", verb: \"wiki.absorb\", description: \"Roll raw entries into typed wiki articles\" },\n\n // social\n { category: \"social\", verb: \"brief.daily\", description: \"Compose a daily brief / digest\" },\n { category: \"social\", verb: \"draft.post\", description: \"Draft a marketing post / announcement\" },\n { category: \"social\", verb: \"report.weekly\", description: \"Compose a weekly status report\" },\n\n // system (the classifier itself; rare to expose)\n { category: \"system\", verb: \"classify.intent\", description: \"Internal: graph-classifier sub-call\" },\n]\n\n","import {\n readFileSync,\n writeFileSync,\n appendFileSync,\n existsSync,\n mkdirSync,\n renameSync,\n statSync,\n} from \"fs\"\nimport { resolve, dirname } from \"path\"\nimport { createHash } from \"crypto\"\nimport {\n graphSchemaSchema,\n nodesFileSchema,\n indexFileSchema,\n fingerprintEntrySchema,\n classificationSchema,\n type GraphSchema,\n type GraphNode,\n type NodesFile,\n type IndexFile,\n type Classification,\n type FingerprintEntry,\n} from \"./types\"\nimport { CATEGORY_DESCRIPTIONS, STARTER_SCHEMA, STARTER_VERB_NODES } from \"./starter-schema\"\n\n// --- Intent Knowledge Graph filesystem store ---\n//\n// Mirrors the .agentx/wiki pattern: plain JSON on disk, one directory, no DB.\n// Not thread-safe across processes — writes go through safeWrite (tmp + rename).\n\nexport interface GraphStoreOptions {\n baseDir?: string\n log?: (...args: unknown[]) => void\n}\n\nexport class GraphStore {\n readonly baseDir: string\n private log: (...args: unknown[]) => void\n /** Parsed nodes/index files, keyed by path. The classifier reads both\n * several times per message and they grow without bound, so re-reading\n * and re-validating them each time blocked the daemon for seconds. */\n private parsed = new Map<string, { mtimeMs: number; size: number; data: unknown }>()\n\n constructor(opts: GraphStoreOptions = {}) {\n this.baseDir = opts.baseDir ?? resolve(process.cwd(), \".agentx/graph\")\n this.log = opts.log ?? console.error.bind(console, \"[graph]\")\n mkdirSync(this.baseDir, { recursive: true })\n }\n\n // --- Paths ---\n\n schemaPath(): string { return resolve(this.baseDir, \"schema.json\") }\n nodesPath(): string { return resolve(this.baseDir, \"nodes.json\") }\n indexPath(): string { return resolve(this.baseDir, \"index.json\") }\n classificationsPath(): string { return resolve(this.baseDir, \"classifications.jsonl\") }\n\n // --- Schema ---\n\n /** Load the graph schema, seeding STARTER_SCHEMA if the file is missing.\n * Phase 1 of the classifier-retire plan ships a v2 verb-level schema;\n * installs with the v1 hierarchical schema (scope > org > unit >\n * activity) get auto-migrated on next load: the v1 file is renamed\n * to schema.v1.bak.json, the v2 starter is written, and the\n * per-event nodes.json + classifications.jsonl are left alone for\n * historical reading. New events classify under v2 from then on. */\n loadSchema(): GraphSchema {\n const p = this.schemaPath()\n if (!existsSync(p)) {\n this.saveSchema(STARTER_SCHEMA)\n this.log(\"seeded starter schema at\", p)\n return STARTER_SCHEMA\n }\n const raw = readFileSync(p, \"utf-8\")\n const parsed = graphSchemaSchema.safeParse(JSON.parse(raw))\n if (!parsed.success) {\n throw new Error(`Invalid ${p}: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n if ((parsed.data.version ?? 1) < (STARTER_SCHEMA.version ?? 2)) {\n const backup = p.replace(/\\.json$/, `.v${parsed.data.version ?? 1}.bak.json`)\n try {\n writeFileSync(backup, raw)\n this.log(`migrated graph schema v${parsed.data.version ?? 1} -> v${STARTER_SCHEMA.version}; old saved at ${backup}`)\n } catch (e: any) {\n this.log(`could not back up old schema: ${e?.message ?? e}`)\n }\n this.saveSchema(STARTER_SCHEMA)\n // Same treatment for nodes.json — the v1 nodes were parented under\n // levels that don't exist in v2 and would fail validation. Archive\n // them and re-seed.\n const np = this.nodesPath()\n if (existsSync(np)) {\n const nbackup = np.replace(/\\.json$/, `.v1.bak.json`)\n try {\n writeFileSync(nbackup, readFileSync(np, \"utf-8\"))\n this.log(`archived v1 nodes.json -> ${nbackup}`)\n } catch (e: any) {\n this.log(`could not back up old nodes: ${e?.message ?? e}`)\n }\n try {\n const seeded = seedNodesFile()\n this.saveNodes(seeded)\n } catch (e: any) {\n this.log(`could not seed v2 nodes: ${e?.message ?? e}`)\n }\n }\n return STARTER_SCHEMA\n }\n return parsed.data\n }\n\n saveSchema(schema: GraphSchema): void {\n const parsed = graphSchemaSchema.safeParse(schema)\n if (!parsed.success) {\n throw new Error(`Refusing to save invalid schema: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n safeWriteJson(this.schemaPath(), parsed.data)\n }\n\n // --- Nodes ---\n\n loadNodes(): NodesFile {\n const p = this.nodesPath()\n if (!existsSync(p)) {\n // Seed the verb-level taxonomy on first load. Lets the classifier\n // pick from a stable set of common verbs out of the box, instead of\n // inventing slightly-different variants for every event.\n const seeded = seedNodesFile()\n this.saveNodes(seeded)\n return seeded\n }\n // A copy, so callers can edit it before saveNodes without touching the cache.\n return structuredClone(this.readParsed(p, (raw) => {\n const parsed = nodesFileSchema.safeParse(JSON.parse(raw))\n if (!parsed.success) {\n throw new Error(`Invalid ${p}: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n return parsed.data\n }))\n }\n\n saveNodes(file: NodesFile): void {\n const parsed = nodesFileSchema.safeParse(file)\n if (!parsed.success) {\n throw new Error(`Refusing to save invalid nodes file: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n this.writeParsed(this.nodesPath(), parsed.data)\n }\n\n /** The parsed file, re-read only when its mtime or size changes, so a\n * write from another process (CLI, dashboard) is still picked up. */\n private readParsed<T>(p: string, parse: (raw: string) => T): T {\n const { mtimeMs, size } = statSync(p)\n const hit = this.parsed.get(p)\n if (hit && hit.mtimeMs === mtimeMs && hit.size === size) return hit.data as T\n const data = parse(readFileSync(p, \"utf-8\"))\n this.parsed.set(p, { mtimeMs, size, data })\n return data\n }\n\n /** Write the file and keep the parsed copy, so the writer never re-reads\n * what it just wrote. `data` must not be mutated afterwards. */\n private writeParsed(p: string, data: unknown): void {\n this.parsed.delete(p)\n safeWriteJson(p, data)\n const { mtimeMs, size } = statSync(p)\n this.parsed.set(p, { mtimeMs, size, data })\n }\n\n /** Validate a node against the schema AND uniqueness within the nodes file. */\n validateNode(node: GraphNode, schema: GraphSchema, all: GraphNode[]): void {\n const level = schema.levels.find((l) => l.id === node.level)\n if (!level) throw new Error(`Unknown level: \"${node.level}\"`)\n\n const missing = level.axes\n .filter((a) => !a.optional)\n .filter((a) => !(a.name in node.axes))\n if (missing.length) {\n throw new Error(\n `Node ${node.id} (${node.level}) missing required axes: ${missing.map((a) => a.name).join(\", \")}`,\n )\n }\n\n for (const a of level.axes) {\n const v = node.axes[a.name]\n if (v == null) continue\n if (a.type === \"enum\" && a.values && !a.values.includes(v)) {\n throw new Error(`Node ${node.id}: axis ${a.name}=\"${v}\" not in enum ${JSON.stringify(a.values)}`)\n }\n if (a.type === \"ref\") {\n if (!all.some((n) => n.id === v)) {\n throw new Error(`Node ${node.id}: axis ${a.name}=\"${v}\" refers to unknown node`)\n }\n if (a.refLevel) {\n const target = all.find((n) => n.id === v)!\n if (target.level !== a.refLevel) {\n throw new Error(\n `Node ${node.id}: axis ${a.name} expected level \"${a.refLevel}\" but got \"${target.level}\"`,\n )\n }\n }\n }\n }\n\n const levelIdx = schema.levels.findIndex((l) => l.id === node.level)\n if (levelIdx === 0) {\n if (node.parentId !== null) {\n throw new Error(`Root-level node ${node.id} must have parentId: null`)\n }\n } else {\n if (!node.parentId) {\n throw new Error(`Non-root node ${node.id} must have a parentId`)\n }\n const parent = all.find((n) => n.id === node.parentId)\n if (!parent) throw new Error(`Node ${node.id}: parent \"${node.parentId}\" not found`)\n const parentLevelIdx = schema.levels.findIndex((l) => l.id === parent.level)\n // Parent may be at any higher level — intermediate levels can be skipped\n // for orgs that don't use them (e.g. remote-first: no location node).\n if (parentLevelIdx < 0 || parentLevelIdx >= levelIdx) {\n throw new Error(\n `Node ${node.id} at level \"${node.level}\" has parent at level \"${parent.level}\" — parent must be at a higher level`,\n )\n }\n }\n }\n\n /**\n * Commit a full classification path: for each path element that doesn't\n * yet exist, infer its schema level by matching the proposed axes against\n * the level's required axes (first match ≥ cursor wins — this handles\n * paths that skip levels, like business → acme where location is\n * absent). Refreshes the node list between adds so callers in a loop\n * don't hit \"Node id already exists\" on the second iteration.\n */\n commitNodesAlongPath(\n path: string[],\n proposedAxes: Record<string, Record<string, string>>,\n schema: GraphSchema,\n createdBy?: string,\n ): { added: GraphNode[]; skipped: string[] } {\n const added: GraphNode[] = []\n const skipped: string[] = []\n const now = new Date().toISOString()\n\n for (let i = 0; i < path.length; i++) {\n const id = path[i]\n // Load fresh each iteration — cheap O(N) file read, avoids stale snapshots.\n const current = this.loadNodes().nodes\n const existing = current.find((n) => n.id === id)\n if (existing) {\n skipped.push(id)\n continue\n }\n\n // Cursor: how deep the schema-levels we've already filled up to.\n let cursor = 0\n // Scan backwards through path[0..i-1] to find the deepest already-committed\n // or just-added node and resume after its level.\n for (let j = i - 1; j >= 0; j--) {\n const priorId = path[j]\n const priorNode = current.find((n) => n.id === priorId) || added.find((n) => n.id === priorId)\n if (priorNode) {\n cursor = schema.levels.findIndex((l) => l.id === priorNode.level) + 1\n break\n }\n }\n\n const axes = proposedAxes[id] ?? {}\n // Find the first level at or after the cursor whose required axes are\n // satisfied by proposedAxes[id]. \"Required\" here = listed in level.axes;\n // we accept a partial match (axes present in proposal, even if some\n // schema axes are missing — validateNode will catch truly broken ones).\n let chosenLevel: string | null = null\n for (let j = cursor; j < schema.levels.length; j++) {\n const level = schema.levels[j]\n const missing = level.axes\n .filter((a) => !a.optional)\n .filter((a) => !(a.name in axes))\n if (missing.length === 0) {\n chosenLevel = level.id\n cursor = j + 1\n break\n }\n }\n // Fallback: if no level's axes fully match, try the NEXT level after\n // the cursor anyway. Better to commit at the likely level and let\n // validateNode reject on write than to silently drop the whole path.\n if (!chosenLevel && cursor < schema.levels.length) {\n chosenLevel = schema.levels[cursor].id\n cursor++\n }\n if (!chosenLevel) {\n throw new Error(`Can't place node ${id} — no schema level left (cursor=${cursor}, levels=${schema.levels.length})`)\n }\n\n // Parent is the DEEPEST already-placed node at a level < chosenLevel.\n let parentId: string | null = null\n const chosenIdx = schema.levels.findIndex((l) => l.id === chosenLevel)\n for (let j = i - 1; j >= 0; j--) {\n const priorId = path[j]\n const prior = current.find((n) => n.id === priorId) || added.find((n) => n.id === priorId)\n if (!prior) continue\n const priorIdx = schema.levels.findIndex((l) => l.id === prior.level)\n if (priorIdx >= 0 && priorIdx < chosenIdx) { parentId = priorId; break }\n }\n\n const node: GraphNode = {\n id, level: chosenLevel, parentId, axes,\n createdAt: now,\n createdBy,\n }\n this.addNode(node) // throws if schema validation fails\n added.push(node)\n }\n\n return { added, skipped }\n }\n\n /** Append a node. Caller is responsible for id uniqueness; we check and throw. */\n addNode(node: GraphNode): GraphNode {\n const schema = this.loadSchema()\n const file = this.loadNodes()\n if (file.nodes.some((n) => n.id === node.id)) {\n throw new Error(`Node id already exists: ${node.id}`)\n }\n this.validateNode(node, schema, [...file.nodes, node])\n file.nodes.push(node)\n this.saveNodes(file)\n return node\n }\n\n // --- Classifications (append-only log) ---\n\n appendClassification(c: Classification): boolean {\n const parsed = classificationSchema.safeParse(c)\n if (!parsed.success) {\n // Before the fix this threw and took down the whole task. Now we drop\n // the bad classification and log enough detail (the offending path +\n // axes keys) for the operator to diagnose the prompt. Returning false\n // lets callers decide whether to retry with a cleaner proposal.\n const issues = parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\" · \")\n this.log(\n `skipped invalid classification — ${issues} ·`,\n `path=${JSON.stringify(c.path)}`,\n `axes-keys=${JSON.stringify(Object.keys(c.proposedAxes || {}))}`,\n )\n return false\n }\n const line = JSON.stringify(parsed.data) + \"\\n\"\n const p = this.classificationsPath()\n if (!existsSync(p)) {\n mkdirSync(dirname(p), { recursive: true })\n }\n appendFileSync(p, line)\n return true\n }\n\n /**\n * All pending classifications, newest first. Collapses the append-only\n * ledger by msgHash — the most recent entry per message wins (so if an\n * entry was updated via updateClassificationStatus, we see the current\n * state, not the original).\n */\n listPendingClassifications(limit = 200): Classification[] {\n return this.listByStatus(\"pending\", limit)\n }\n\n /** Every classification, newest-first, collapsed one row per message.\n * The human-label queue needs the whole population rather than one\n * status, because the rows worth checking are the auto-approved ones. */\n listAllClassifications(): Classification[] {\n return this.readAllCollapsed()\n }\n\n /** Same contract as listPendingClassifications but filtered to any status. */\n listByStatus(status: Classification[\"status\"], limit = 200): Classification[] {\n const all = this.readAllCollapsed()\n return all.filter((c) => c.status === status).slice(0, limit)\n }\n\n /**\n * Read every classification, collapse by msgHash keeping the newest entry\n * per message. Used by listByStatus + the review loop to see current state.\n * Returns newest-first order.\n */\n private readAllCollapsed(): Classification[] {\n const p = this.classificationsPath()\n if (!existsSync(p)) return []\n const raw = readFileSync(p, \"utf-8\")\n const lines = raw.split(\"\\n\").filter(Boolean)\n const byHash = new Map<string, Classification>()\n for (const line of lines) {\n try {\n const parsed = classificationSchema.safeParse(JSON.parse(line))\n if (!parsed.success) continue\n // Later entries overwrite earlier ones for the same msgHash.\n byHash.set(parsed.data.msgHash, parsed.data)\n } catch {\n // skip malformed\n }\n }\n // Newest-first — sort by ts desc.\n return Array.from(byHash.values()).sort((a, b) => (a.ts < b.ts ? 1 : -1))\n }\n\n /**\n * Append a status-update entry for an existing classification. The ledger\n * stays append-only; readers collapse by msgHash. Returns the updated\n * classification, or null if no prior entry for msgHash exists.\n */\n updateClassificationStatus(\n msgHash: string,\n update: {\n status: Classification[\"status\"]\n reviewer?: string\n reviewReason?: string\n },\n ): Classification | null {\n const all = this.readAllCollapsed()\n const prior = all.find((c) => c.msgHash === msgHash)\n if (!prior) return null\n const next: Classification = {\n ...prior,\n status: update.status,\n ts: new Date().toISOString(),\n }\n // Store reviewer + reason in the preview field so readers can see who\n // flipped what without needing a separate review-log file. Non-breaking:\n // preview is already optional text meant for UI display.\n if (update.reviewer || update.reviewReason) {\n const suffix = ` · ${update.reviewer ? `reviewer=${update.reviewer}` : \"\"}${update.reviewReason ? ` · ${update.reviewReason}` : \"\"}`\n next.preview = ((prior.preview || \"\") + suffix).slice(0, 500)\n }\n this.appendClassification(next)\n return next\n }\n\n /** Read the last N classifications, newest first. Cheap enough for the admin UI. */\n readRecentClassifications(limit = 50): Classification[] {\n const p = this.classificationsPath()\n if (!existsSync(p)) return []\n const raw = readFileSync(p, \"utf-8\")\n const lines = raw.split(\"\\n\").filter(Boolean)\n const out: Classification[] = []\n for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {\n try {\n const parsed = classificationSchema.safeParse(JSON.parse(lines[i]))\n if (parsed.success) out.push(parsed.data)\n } catch {\n // skip malformed line — append-only log; don't fail reads on one bad line\n }\n }\n return out\n }\n\n // --- Fingerprint index ---\n\n /**\n * Hash that represents \"this kind of message\" for snap-to-path caching.\n *\n * Keyed on the normalized wording plus the channel. The sender used to be\n * part of the key too, and the exact text was: measured over the last\n * 2,000 classifications, 89% missed, so nearly every task paid an LLM\n * call for a taxonomy label. Identifiers, numbers, links and mentions\n * are what differ between two messages that mean the same thing, so\n * they are folded away (see `normalizeForFingerprint`).\n */\n fingerprint(msg: {\n text: string\n channel?: string\n sender?: string\n }): string {\n const norm = normalizeForFingerprint(msg.text)\n const payload = [norm, msg.channel ?? \"\"].join(\"\\u0001\")\n return createHash(\"sha256\").update(payload).digest(\"hex\").slice(0, 32)\n }\n\n loadIndex(): IndexFile {\n return structuredClone(this.index())\n }\n\n saveIndex(file: IndexFile): void {\n const parsed = indexFileSchema.safeParse(file)\n if (!parsed.success) {\n throw new Error(`Refusing to save invalid index: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n this.writeParsed(this.indexPath(), parsed.data)\n }\n\n /** The cached index. Read-only: copy before handing it to a caller. */\n private index(): IndexFile {\n const p = this.indexPath()\n if (!existsSync(p)) return { version: 1, entries: {} }\n return this.readParsed(p, (raw) => {\n const parsed = indexFileSchema.safeParse(JSON.parse(raw))\n if (!parsed.success) {\n throw new Error(`Invalid ${p}: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n return parsed.data\n })\n }\n\n getFingerprint(fp: string): FingerprintEntry | undefined {\n const entry = this.index().entries[fp]\n return entry && structuredClone(entry)\n }\n\n setFingerprint(fp: string, entry: Omit<FingerprintEntry, \"fingerprint\" | \"updatedAt\">): void {\n // Validate only the new entry: the rest of the index was validated when\n // it was read, and re-checking thousands of entries per message is the\n // cost this cache exists to avoid.\n const parsed = fingerprintEntrySchema.safeParse({\n ...entry,\n fingerprint: fp,\n updatedAt: new Date().toISOString(),\n })\n if (!parsed.success) {\n throw new Error(`Refusing to save invalid index entry: ${parsed.error.issues.map((i) => i.message).join(\"; \")}`)\n }\n const current = this.index()\n this.writeParsed(this.indexPath(), { ...current, entries: { ...current.entries, [fp]: parsed.data } })\n }\n\n /** Update the axes on an existing node. Schema-validates the result. */\n updateNodeAxes(id: string, axes: Record<string, string>): GraphNode {\n const schema = this.loadSchema()\n const file = this.loadNodes()\n const node = file.nodes.find((n) => n.id === id)\n if (!node) throw new Error(`Node not found: ${id}`)\n const updated: GraphNode = { ...node, axes }\n this.validateNode(updated, schema, file.nodes.map((n) => (n.id === id ? updated : n)))\n file.nodes = file.nodes.map((n) => (n.id === id ? updated : n))\n this.saveNodes(file)\n return updated\n }\n\n /** Remove a node. Refuses to delete if any other node still references it\n * (child via parentId, or axis ref). */\n deleteNode(id: string): void {\n const file = this.loadNodes()\n const child = file.nodes.find((n) => n.parentId === id)\n if (child) {\n throw new Error(`Cannot delete \"${id}\" — child node \"${child.id}\" still points to it`)\n }\n const refHolder = file.nodes.find((n) =>\n Object.values(n.axes).some((v) => v === id),\n )\n if (refHolder) {\n throw new Error(`Cannot delete \"${id}\" — node \"${refHolder.id}\" references it via an axis`)\n }\n file.nodes = file.nodes.filter((n) => n.id !== id)\n this.saveNodes(file)\n }\n\n /** Approve a pending classification. Commits any new nodes along its path,\n * stamps the fingerprint index so future similar messages hit the cache,\n * and appends an audit entry. Idempotent — no-op if already cached. */\n approveClassification(c: Classification): void {\n if (this.getFingerprint(c.msgHash)) return // already approved\n // Commit any path nodes the LLM proposed but hadn't been confirmed yet.\n const schema = this.loadSchema()\n const known = new Set(this.loadNodes().nodes.map((n) => n.id))\n for (let i = 0; i < c.path.length; i++) {\n const id = c.path[i]\n if (known.has(id)) continue\n const level = schema.levels[i]?.id\n if (!level) break\n const axes = c.proposedAxes?.[id] ?? {}\n const parentId = i === 0 ? null : c.path[i - 1]\n this.addNode({\n id,\n level,\n parentId,\n axes,\n createdAt: new Date().toISOString(),\n createdBy: c.agentId,\n })\n known.add(id)\n }\n this.setFingerprint(c.msgHash, { path: c.path, leaf: c.leaf })\n this.appendClassification({ ...c, status: \"approved\", ts: new Date().toISOString() })\n }\n\n /** Record rejection — no nodes committed, no fingerprint set. */\n rejectClassification(c: Classification): void {\n this.appendClassification({ ...c, status: \"rejected\", ts: new Date().toISOString() })\n }\n}\n\n/** Atomic write: tmp file + rename. Avoids half-written JSON on crashes. */\nfunction safeWriteJson(path: string, data: unknown): void {\n mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.tmp-${process.pid}`\n writeFileSync(tmp, JSON.stringify(data, null, 2))\n renameSync(tmp, path)\n}\n\n/** Build the seed nodes.json — one category node per enum value, plus\n * one verb node per STARTER_VERB_NODES entry parented under its\n * category. Idempotent shape: same input always produces the same\n * file, so re-seeding is safe. */\nfunction seedNodesFile(): NodesFile {\n const now = new Date().toISOString()\n const nodes: NodesFile[\"nodes\"] = []\n const seenCats = new Set<string>()\n for (const v of STARTER_VERB_NODES) {\n if (!seenCats.has(v.category)) {\n nodes.push({\n id: v.category,\n level: \"category\",\n parentId: null,\n axes: { kind: v.category, description: CATEGORY_DESCRIPTIONS[v.category] },\n createdAt: now,\n createdBy: \"starter\",\n })\n seenCats.add(v.category)\n }\n }\n for (const v of STARTER_VERB_NODES) {\n nodes.push({\n id: v.verb,\n level: \"verb\",\n parentId: v.category,\n axes: { name: v.verb, ...(v.description ? { description: v.description } : {}) },\n createdAt: now,\n createdBy: \"starter\",\n })\n }\n return { version: 1, nodes }\n}\n\n/**\n * Fold a message down to the words that carry its intent. Links, mentions,\n * issue or MR references, hashes and numbers vary between two requests of\n * the same kind, so they collapse to placeholders; punctuation and case go.\n * Long webhook bodies are cut so a note on the same thread hashes alike.\n */\nexport function normalizeForFingerprint(text: string): string {\n return text\n .toLowerCase()\n .replace(/https?:\\/\\/\\S+/g, \" url \")\n .replace(/[@#][\\w.\\/-]+/g, \" ref \")\n .replace(/\\b[0-9a-f]{7,}\\b/g, \" id \")\n .replace(/\\d+/g, \" num \")\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 400)\n}\n","import { createHash } from \"crypto\"\nimport { extractJson } from \"@/utils/extract-json\"\nimport { GraphStore } from \"./store\"\nimport {\n type GraphSchema,\n type GraphNode,\n type Classification,\n} from \"./types\"\nimport { createProvider, type ProviderName, type AgentProvider } from \"@/agent/providers\"\nimport { getSeatMode } from \"@/decisions/seat\"\nimport { INTENT_PATH_SEAT, proposePathViaSeat } from \"@/decisions/seats/intent-path\"\n\n/** A path for a cache miss, with where it came from. */\ninterface Proposal {\n path: string[]\n proposedAxes: Record<string, Record<string, string>>\n confidence?: number\n leaf: { input?: string; output?: string }\n source: \"llm\" | \"seat\"\n}\n\n// --- Intent Knowledge Graph classifier ---\n//\n// For every incoming message, returns a path through the taxonomy:\n// 1. fingerprint → cache hit → reuse path (0 LLM calls, source=cache)\n// 2. miss → LLM draftAgent proposes { path, axes } → validated → pending\n// 3. autoApproveConfidence met → committed + cached\n//\n// Pending paths are still usable immediately (caller tags artifacts with\n// them); approval flips the flag and populates the fingerprint index so\n// the next similar message hits the cache.\n\nexport interface ClassifyInput {\n text: string\n channel?: string\n sender?: string\n /** Conversation id; stored on the classification so `agentx_wiki_query`\n * can look up the path of the request it is serving. */\n chatId?: string\n /** Agent that will RECEIVE the message after classification. When this\n * equals `draftAgent`, classification is skipped to prevent a deadlock —\n * the classifier's sub-task would otherwise queue behind the in-progress\n * main task on the same agent. */\n agentId?: string\n}\n\nexport interface ClassifyResult {\n /** Node ids from root to leaf. Shorter-than-full paths are allowed. */\n path: string[]\n /** Stable hash of the path — used as the `graph:<pathId>` wiki tag. */\n pathId: string\n /** Human-readable \"A › B › C\" path for logs + UI. */\n pathLabel: string\n /** Axis values asserted by the classifier. Keyed by node id. */\n axes: Record<string, Record<string, string>>\n leaf: { input?: string; output?: string }\n source: \"cache\" | \"llm\" | \"seat\"\n status: \"pending\" | \"approved\"\n confidence?: number\n}\n\nexport type ApprovalStructurePolicy = \"strict\" | \"extend-leaves\" | \"any\"\n\nexport interface ClassifierOptions {\n store: GraphStore\n /** Base URL of the daemon — used to POST /task for LLM proposals. */\n daemonUrl: string\n /** Optional bearer token for the daemon. */\n token?: string\n /** Which agent makes the proposal. Required if caller ever expects a\n * non-cached classification (cache hits work without an agent). */\n draftAgent?: string\n /** Structural approval policy — see config.ts for semantics. Default\n * \"extend-leaves\" (auto-approve pure reuse + single-leaf additions). */\n autoApproveStructure?: ApprovalStructurePolicy\n /** Minimum confidence (0..1) to commit without human approval. 1.0 = never.\n * OR'd with the structural policy. */\n autoApproveConfidence?: number\n /** Provider used for the in-process classifier call. Defaults to\n * \"claude-code\", which auto-detects auth via `loadAuthConfig()` —\n * Claude Max OAuth (CLI subprocess), API key, etc. NEVER opens a\n * paid path beyond what the operator has already configured. */\n classifierProvider?: ProviderName\n /** Model id passed to the provider. For claude-code OAuth this is\n * mapped through `CLI_MODEL_ALIASES` (sonnet/opus/haiku). Cheap\n * default — classification is metadata, not work. */\n classifierModel?: string\n log?: (...args: unknown[]) => void\n}\n\nexport class Classifier {\n private store: GraphStore\n private daemonUrl: string\n private token?: string\n private draftAgent?: string\n private autoApprove: number\n private autoApproveStructure: ApprovalStructurePolicy\n private classifierModel: string\n private classifierProviderName: ProviderName\n private providerInstance?: AgentProvider\n private log: (...args: unknown[]) => void\n\n constructor(opts: ClassifierOptions) {\n this.store = opts.store\n this.daemonUrl = opts.daemonUrl.replace(/\\/+$/, \"\")\n this.token = opts.token\n this.draftAgent = opts.draftAgent\n this.autoApprove = opts.autoApproveConfidence ?? 1.0\n this.autoApproveStructure = opts.autoApproveStructure ?? \"extend-leaves\"\n this.classifierModel = opts.classifierModel ?? \"claude-haiku-4-5-20251001\"\n this.classifierProviderName = opts.classifierProvider ?? \"claude-code\"\n this.log = opts.log ?? console.error.bind(console, \"[classifier]\")\n }\n\n /** Lazily build the provider instance. Lazy because constructing\n * ClaudeCodeProvider hits auth-store; deferring it keeps the\n * classifier importable in tests / dry-run paths that never call\n * classify(). */\n private getProvider(): AgentProvider {\n if (!this.providerInstance) {\n this.providerInstance = createProvider(this.classifierProviderName)\n }\n return this.providerInstance\n }\n\n async classify(input: ClassifyInput): Promise<ClassifyResult | null> {\n const fp = this.store.fingerprint({\n text: input.text,\n channel: input.channel,\n sender: input.sender,\n })\n\n // 1. Cache hit — instant return, zero LLM. Logged to classifications.jsonl\n // so the cache-hit rate is measurable from the persisted record alone\n // (otherwise hits leave no trace and ROI of the classifier is invisible).\n const cached = this.store.getFingerprint(fp)\n if (cached) {\n this.store.appendClassification({\n ts: new Date().toISOString(),\n msgHash: fp,\n agentId: input.agentId,\n channel: input.channel,\n sender: input.sender,\n chatId: input.chatId,\n path: cached.path,\n proposedAxes: {},\n leaf: cached.leaf,\n source: \"cache\",\n status: \"approved\",\n preview: input.text.slice(0, 200),\n })\n return {\n path: cached.path,\n pathId: hashPath(cached.path),\n pathLabel: pathLabel(cached.path, this.store.loadNodes().nodes),\n axes: {},\n leaf: cached.leaf,\n source: \"cache\",\n status: \"approved\",\n }\n }\n\n // 2. Cache miss — need an LLM proposal. Phase 2 of classifier-retire\n // replaced the /task → graph-agent dispatch with a direct Anthropic\n // Messages call, so we no longer need a draftAgent and the\n // self-dispatch deadlock guard (`agentId === draftAgent`) is moot.\n // `graph.enabled` is the only gate now.\n const schema = this.store.loadSchema()\n const nodes = this.store.loadNodes().nodes\n const proposal = await this.propose(input, schema, nodes)\n if (!proposal) return null\n\n // 3. Validate + persist as pending. Any NEW node the LLM proposed is\n // only committed if the whole classification auto-approves below.\n const { path, proposedAxes, confidence, leaf } = proposal\n if (path.length === 0) return null\n\n const classification: Classification = {\n ts: new Date().toISOString(),\n msgHash: fp,\n agentId: input.agentId,\n channel: input.channel,\n sender: input.sender,\n chatId: input.chatId,\n path,\n proposedAxes,\n leaf,\n source: proposal.source,\n status: \"pending\",\n confidence,\n preview: input.text.slice(0, 200),\n }\n\n // --- Auto-approval policy (see config.ts for full semantics) ---\n //\n // Two conditions, OR'd. Either approves the classification:\n // 1. Structure policy — what KIND of change the proposed path makes:\n // strict: nothing auto — always pending\n // extend-leaves: auto if the path either (a) reuses only existing\n // nodes, or (b) adds exactly one new node at the\n // DEEPEST level (a new leaf). Structural changes\n // (new mid-path or root node) still queue.\n // any: auto regardless of structure.\n // 2. Confidence — LLM-self-reported confidence >= autoApproveConfidence.\n //\n // Pending classifications still persist to the log, but don't commit nodes\n // and don't populate the fingerprint cache (so similar messages re-query).\n const existingIds = new Set(nodes.map((n) => n.id))\n const newNodeIndices = path\n .map((id, idx) => (existingIds.has(id) ? -1 : idx))\n .filter((idx) => idx >= 0)\n\n let structureOk = false\n if (this.autoApproveStructure === \"any\") {\n structureOk = true\n } else if (this.autoApproveStructure === \"extend-leaves\") {\n const isReuseOnly = newNodeIndices.length === 0\n const isSingleLeafAddition =\n newNodeIndices.length === 1 && newNodeIndices[0] === path.length - 1\n structureOk = isReuseOnly || isSingleLeafAddition\n }\n const confidenceOk = confidence !== undefined && confidence >= this.autoApprove\n\n let status: \"pending\" | \"approved\" = \"pending\"\n if (structureOk || confidenceOk) {\n // Commit any new nodes; if ANY fail schema validation (missing axes,\n // bad ref, etc.) fall back to pending for the whole classification\n // rather than half-committing the graph and bubbling the error up to\n // the task handler.\n try {\n this.commitNewNodes(path, proposedAxes, schema, nodes, input.sender)\n this.store.setFingerprint(fp, { path, leaf })\n status = \"approved\"\n } catch (e: any) {\n this.log(\n `auto-approve failed — staying pending ·`,\n `path=${JSON.stringify(path)}`,\n `reason=${(e?.message || e).toString().slice(0, 200)}`,\n )\n }\n }\n classification.status = status\n this.store.appendClassification(classification)\n\n return {\n path,\n pathId: hashPath(path),\n pathLabel: pathLabel(path, this.store.loadNodes().nodes),\n axes: proposedAxes,\n leaf,\n source: proposal.source,\n status,\n confidence,\n }\n }\n\n /**\n * Where a cache miss gets its path from, by the intent-path seat's mode:\n *\n * off the LLM, as before\n * shadow the LLM decides; the seat runs afterwards with the LLM's path\n * as incumbent, so agreement is measured before it can act\n * active the seat decides when both stages clear their thresholds;\n * the LLM only answers what the seat could not\n *\n * The seat reuses existing nodes only, so a seat proposal never adds to\n * the taxonomy; the LLM keeps that role in every mode.\n */\n private async propose(\n input: ClassifyInput,\n schema: GraphSchema,\n nodes: GraphNode[],\n ): Promise<Proposal | null> {\n const mode = getSeatMode(INTENT_PATH_SEAT)\n const seatInput = { message: input.text, channel: input.channel, sender: input.sender, agent: input.agentId }\n\n if (mode === \"active\") {\n const viaSeat = await proposePathViaSeat(seatInput, nodes).catch((e) => {\n this.log(\"intent-path seat failed:\", e?.message || e)\n return null\n })\n if (viaSeat?.confident) {\n return { path: viaSeat.path, proposedAxes: {}, leaf: {}, confidence: viaSeat.confidence, source: \"seat\" }\n }\n }\n\n const viaLlm = await this.proposePath(input, schema, nodes).catch((e) => {\n this.log(\"LLM proposal failed:\", e?.message || e)\n return null\n })\n if (mode === \"shadow\" && viaLlm) {\n void proposePathViaSeat(seatInput, nodes, { incumbent: viaLlm.path }).catch(() => {})\n }\n return viaLlm ? { ...viaLlm, source: \"llm\" } : null\n }\n\n /** Direct call to Anthropic to propose a path. Pure I/O; no side effects.\n * Bypasses the mesh / dispatch / ledger pipeline so a classification\n * doesn't surface as a sibling task in the activity graph. */\n private async proposePath(\n input: ClassifyInput,\n schema: GraphSchema,\n nodes: GraphNode[],\n ): Promise<{\n path: string[]\n proposedAxes: Record<string, Record<string, string>>\n confidence?: number\n leaf: { input?: string; output?: string }\n } | null> {\n const nodesForPrompt = nodes.map((n) => ({\n id: n.id,\n level: n.level,\n parentId: n.parentId,\n axes: n.axes,\n }))\n const userPrompt = [\n `You are the intent classifier for AgentX. You answer ONE question:`,\n `\"what kind of work does this message describe?\" — verb-level only.`,\n ``,\n `IMPORTANT — what NOT to encode in the path:`,\n `- Client / company / project / team names. Those are already on the event`,\n ` metadata (project, channel, agentId). Embedding them in the path causes`,\n ` duplicate nodes (one per client) for the same verb.`,\n `- The specific subject (issue number, file name, person name). Same reason.`,\n `- The agent's name or role. Pick the verb the *requester* intended.`,\n ``,\n `SCHEMA (fixed levels — pick one node per level):`,\n \"```json\",\n JSON.stringify(schema, null, 2),\n \"```\",\n ``,\n `EXISTING NODES (prefer reusing these; only invent a new node when no`,\n `existing one fits):`,\n \"```json\",\n JSON.stringify(nodesForPrompt, null, 2),\n \"```\",\n ``,\n `MESSAGE:`,\n \"```\",\n input.text.slice(0, 2000),\n \"```\",\n `channel: ${input.channel ?? \"?\"}`,\n `sender: ${input.sender ?? \"?\"}`,\n ``,\n `TASK:`,\n `1. Classify into 'category' (closed enum): code, ops, support, admin,`,\n ` knowledge, social, system. Pick the closest fit.`,\n `2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,`,\n ` e.g. \"review.merge-request\", \"deploy.staging\", \"investigate.error\",`,\n ` \"chat.greeting\", \"fix.bug\". Reuse an existing verb when the message is`,\n ` the same kind of work as something already classified, even when the`,\n ` client / project / subject differs.`,\n ``,\n `Examples (right vs wrong):`,\n `- \"Please review MR #957 on globex/system\" → [\"code\", \"review.merge-request\"]`,\n ` NOT [\"business\", \"acme\", \"globex-v2\", \"review-mr-957-system\"]`,\n `- \"Deploy initech-v2 to staging please\" → [\"ops\", \"deploy.staging\"]`,\n ` NOT [\"business\", \"acme\", \"initech-v2\", \"deploy-initech-v2-to-staging\"]`,\n `- \"Hello Atlas\" → [\"support\", \"chat.greeting\"]`,\n ``,\n `NODE ID RULES (strict — invalid ids get dropped):`,\n `- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*`,\n `- no spaces, no uppercase, no Arabic/other non-Latin`,\n `- verb ids should use a \"category.specific\" or \"verb.modifier\" shape`,\n ``,\n `Return ONE JSON object on one line, no prose, no fences:`,\n ` { \"path\": string[], \"proposedAxes\": { [nodeId]: { [axisName]: string } }, \"leaf\": { \"input\"?: string, \"output\"?: string }, \"confidence\": number }`,\n `confidence in [0,1]. Prefer low confidence over guessing.`,\n ].join(\"\\n\")\n\n // Phase 2 of classifier-retire: in-process provider call.\n // Replaces the `/task → graph-agent → mesh` dispatch path that\n // generated a sibling ledger event per classification (60–70% of\n // dispatches in the activity graph). Reuses whatever auth the\n // operator already configured (Claude Max OAuth via CLI subprocess,\n // Anthropic API key, etc.) — never opens a paid path the operator\n // didn't already opt into. The provider returns a plain JSON-text\n // GenerationResult, so we parse the same way as before.\n const text = await this.callProvider(userPrompt)\n const parsed = extractJson(text)\n if (!parsed || !Array.isArray(parsed.path)) return null\n\n // LLM often returns human-readable labels (\"Business\", \"Sales Manager\").\n // The node-id schema requires a lowercase slug, so normalize here and\n // remember the original → slug mapping so proposedAxes stays attached.\n // We also drop any element that can't be slugified into a valid id (e.g.\n // a path entry of pure Arabic script) — better to classify with a shorter\n // path than to have the store reject the whole classification.\n const NODE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/\n const slugMap = new Map<string, string>()\n const path: string[] = parsed.path\n .filter((s: unknown): s is string => typeof s === \"string\" && s.length > 0)\n .map((s: string) => {\n const trimmed = s.trim()\n const slugged = slugifyNodeId(trimmed)\n if (trimmed !== slugged) slugMap.set(trimmed, slugged)\n return slugged\n })\n .filter((s: string) => NODE_ID_RE.test(s))\n if (path.length === 0) return null\n\n const proposedAxes: Record<string, Record<string, string>> = {}\n if (parsed.proposedAxes && typeof parsed.proposedAxes === \"object\") {\n for (const [rawNodeId, axes] of Object.entries(parsed.proposedAxes as Record<string, any>)) {\n if (!axes || typeof axes !== \"object\") continue\n const nodeId = slugMap.get(rawNodeId) ?? slugifyNodeId(rawNodeId)\n if (!nodeId) continue\n const clean: Record<string, string> = {}\n for (const [k, v] of Object.entries(axes)) {\n if (typeof v === \"string\") clean[k] = v\n }\n // If the LLM didn't volunteer a human-readable name but we slugified\n // one away, preserve the original as a `name` axis so the UI can\n // render \"Sales Manager\" not \"sales-manager\".\n if (!clean.name && rawNodeId !== nodeId) clean.name = rawNodeId.trim()\n proposedAxes[nodeId] = clean\n }\n }\n\n const leaf: { input?: string; output?: string } = {}\n if (parsed.leaf && typeof parsed.leaf === \"object\") {\n if (typeof parsed.leaf.input === \"string\") leaf.input = parsed.leaf.input\n if (typeof parsed.leaf.output === \"string\") leaf.output = parsed.leaf.output\n }\n\n const confidence = typeof parsed.confidence === \"number\"\n ? Math.max(0, Math.min(1, parsed.confidence))\n : undefined\n\n return { path, proposedAxes, confidence, leaf }\n }\n\n /** Create any nodes along `path` that don't exist yet. Delegates to the\n * store so level inference (for paths that skip levels) + fresh reloads\n * between adds are shared with the review path. */\n private commitNewNodes(\n path: string[],\n proposedAxes: Record<string, Record<string, string>>,\n schema: GraphSchema,\n _existing: GraphNode[],\n createdBy?: string,\n ): void {\n this.store.commitNodesAlongPath(path, proposedAxes, schema, createdBy)\n }\n\n /** Run the prompt through whichever AgentProvider the operator already\n * configured (Claude Max subscription via CLI, Anthropic API key, …).\n * Hard rule: NEVER open a paid path the operator didn't opt into —\n * this is just a thin wrapper that reuses existing auth. 30s timeout\n * is enough for Haiku/CLI cold-start; any longer and the classifier\n * is stalling the caller. */\n private async callProvider(userPrompt: string): Promise<string> {\n const provider = this.getProvider()\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 30_000)\n try {\n const res = await provider.generate(\n [\n {\n role: \"system\",\n content:\n \"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences.\",\n },\n { role: \"user\", content: userPrompt },\n ],\n { model: this.classifierModel, maxTokens: 800, abortSignal: ac.signal, bare: true },\n )\n return res.content || \"\"\n } finally {\n clearTimeout(timer)\n }\n }\n}\n\n/** Normalize an LLM-proposed node label to a valid node id. Matches the\n * schema's `^[a-z0-9][a-z0-9._-]*$` — lowercase, alnum/./-/_, leading alnum.\n * Dots are preserved for verb ids like \"review.merge-request\". */\nfunction slugifyNodeId(raw: string): string {\n const s = raw\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^[-_]+|[-_]+$/g, \"\")\n .replace(/-{2,}/g, \"-\")\n if (!s) return \"\"\n // Ensure leading char is alnum (schema rejects leading _ or -).\n return /^[a-z0-9]/.test(s) ? s : `n-${s}`.replace(/[-_]+$/, \"\")\n}\n\n// --- path helpers used by both classifier + wiki retrieval ---\n\n/** Deterministic hash of a path, used as the `graph:<pathId>` wiki tag. */\nexport function hashPath(path: string[]): string {\n return createHash(\"sha1\")\n .update(path.join(\"\\u0001\"))\n .digest(\"hex\")\n .slice(0, 16)\n}\n\n/** \"Business › Acme › DevOps › Review MR\" — for the UI + context render. */\nexport function pathLabel(path: string[], nodes: GraphNode[]): string {\n return path\n .map((id) => {\n const n = nodes.find((x) => x.id === id)\n if (!n) return id\n // Prefer a `name` axis when the schema has one; fall back to id.\n const name = n.axes?.name || n.axes?.what || id\n return name\n })\n .join(\" › \")\n}\n\n/**\n * Depth of the deepest common ancestor between two paths, normalized to [0,1].\n * Used to score wiki articles: exact match = 1, shared grandparent = 0.5, none = 0.\n */\nexport function ancestryScore(a: string[], b: string[]): number {\n if (a.length === 0 || b.length === 0) return 0\n let shared = 0\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n if (a[i] === b[i]) shared++\n else break\n }\n if (shared === 0) return 0\n const depth = Math.max(a.length, b.length)\n return shared / depth\n}\n\n","import { choice } from \"../questions\"\nimport { askSeat, getSeatMode } from \"../seat\"\nimport type { SeatMode } from \"../store\"\nimport type { ChoiceAnswer, StateValue } from \"../types\"\nimport type { GraphNode } from \"@/graph/types\"\nimport { CATEGORY_DESCRIPTIONS } from \"@/graph/starter-schema\"\n\n// Which intent-graph path a message belongs to.\n//\n// The intent graph is a closed set: seven categories, a few hundred verbs,\n// and in the last few thousand classifications the LLM classifier never\n// proposed a node that did not already exist. Picking one label out of a\n// known list is what a decision seat does in under a second for a fraction\n// of a cent; asking a chat model to write the label out cost a fresh CLI\n// process per task, twenty seconds of wall time on average.\n//\n// Two stages because Jev caps a Choice at 255 options and the largest\n// category holds about a hundred verbs: first the category, then the verb\n// within it. Each stage carries the LLM's answer as the incumbent while the\n// seat runs in shadow, so `agentx decisions stats` reports agreement before\n// the seat is allowed to decide.\n//\n// Fail-open, as every seat: a missing or unconfident answer means \"no\n// proposal\", and the classifier falls back to the LLM it uses today. The\n// seat can only ever reuse existing nodes; growing the taxonomy stays the\n// LLM's job.\n\nexport const INTENT_PATH_SEAT = \"intent-path\"\n\n/** Below these the seat's answer is not acted on. A Choice always returns\n * an argmax, so the probability mass behind it is the only signal that\n * the pick is a match rather than the least bad option. */\nexport const INTENT_PATH_MIN_CATEGORY_P = 0.5\nexport const INTENT_PATH_MIN_VERB_P = 0.3\n/** A verb between the floor above and this keeps only its category. In the\n * first days active, 30% of seat labels sat at 0.30-0.50 and most of the\n * nonsensical verbs in a spot check were under 0.45, while the category\n * stayed right. Dropping the verb keeps the sub-second answer instead of\n * handing the message to an LLM fallback that failed about half the time. */\nexport const INTENT_PATH_FULL_VERB_P = 0.45\n\nexport interface IntentPathInput {\n message: string\n channel?: string\n sender?: string\n agent?: string\n}\n\nexport interface IntentPathProposal {\n /** `[category]` or `[category, verb]`, existing node ids only. A verb\n * under `INTENT_PATH_FULL_VERB_P` is dropped from `path`. */\n path: string[]\n /** min over the stages' argmax probability, over the stages kept in\n * `path`. */\n confidence: number\n /** Both stages cleared their thresholds; the caller may act on `path`. */\n confident: boolean\n mode: SeatMode\n}\n\nexport function intentPathState(input: IntentPathInput): StateValue {\n return {\n message: clip(input.message, 2000),\n channel: input.channel ?? null,\n sender: input.sender ?? null,\n agent: input.agent ?? null,\n }\n}\n\n/** One Choice over the given nodes. The option text is the node's own\n * description when it has one, so the seat reads what a reviewer reads. */\nexport function nodeChoice(nodes: GraphNode[], instructions: string) {\n const criteria: Record<string, string | null> = {}\n for (const n of nodes) criteria[n.id] = describe(n)\n return choice(criteria, instructions)\n}\n\nexport function categoryQuestions(categories: GraphNode[]) {\n // Stores seeded before categories carried a description still hold bare\n // `{ kind }` nodes; the shipped text fills in so the options are not ids.\n const described = categories.map((n) => {\n const fallback = (CATEGORY_DESCRIPTIONS as Record<string, string | undefined>)[n.id]\n return n.axes?.description?.trim() || !fallback ? n : { ...n, axes: { ...n.axes, description: fallback } }\n })\n return {\n category: nodeChoice(\n described,\n \"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.\",\n ),\n }\n}\n\nexport function verbQuestions(verbs: GraphNode[]) {\n return {\n verb: nodeChoice(\n verbs,\n \"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.\",\n ),\n }\n}\n\nexport interface ProposeViaSeatOptions {\n /** The LLM's path for the same message, recorded as the incumbent so the\n * shadow report can measure agreement. */\n incumbent?: string[]\n}\n\n/**\n * Two-stage classification through the seat. Returns null when the seat is\n * off, unreachable or the taxonomy is too small to ask; otherwise a proposal\n * whose `confident` flag says whether the thresholds were met.\n */\nexport async function proposePathViaSeat(\n input: IntentPathInput,\n nodes: GraphNode[],\n opts: ProposeViaSeatOptions = {},\n): Promise<IntentPathProposal | null> {\n if (getSeatMode(INTENT_PATH_SEAT) === \"off\") return null\n const categories = nodes.filter((n) => n.parentId === null)\n if (categories.length < 2) return null\n\n const state = intentPathState(input)\n const features = { agent: input.agent ?? \"unknown\", channel: input.channel ?? \"unknown\" }\n const links = input.agent ? [{ kind: \"agent\", id: input.agent }] : undefined\n\n const stage1 = await askSeat(INTENT_PATH_SEAT, state, categoryQuestions(categories), {\n incumbent: opts.incumbent?.[0] ? { category: opts.incumbent[0] } : undefined,\n features: { ...features, stage: \"category\" },\n links,\n })\n if (!stage1) return null\n const cat = stage1.answers.category as ChoiceAnswer\n let confidence = cat.pMax\n let confident = cat.pMax >= INTENT_PATH_MIN_CATEGORY_P\n const path = [cat.choice]\n\n const verbs = nodes.filter((n) => n.parentId === cat.choice)\n if (verbs.length >= 2) {\n const sameCategory = opts.incumbent?.[0] === cat.choice\n const stage2 = await askSeat(INTENT_PATH_SEAT, { ...(state as Record<string, StateValue>), category: cat.choice }, verbQuestions(verbs), {\n // The LLM's verb is only a fair incumbent when it lives in the same\n // category; otherwise it is not among the options at all.\n incumbent: sameCategory && opts.incumbent?.[1] ? { verb: opts.incumbent[1] } : undefined,\n features: { ...features, stage: \"verb\", category: cat.choice },\n links,\n })\n if (!stage2) return null\n const verb = stage2.answers.verb as ChoiceAnswer\n confident = confident && verb.pMax >= INTENT_PATH_MIN_VERB_P\n if (verb.pMax >= INTENT_PATH_FULL_VERB_P || !confident) {\n confidence = Math.min(confidence, verb.pMax)\n path.push(verb.choice)\n }\n } else if (verbs.length === 1) {\n path.push(verbs[0].id)\n }\n\n return { path, confidence, confident, mode: stage1.mode }\n}\n\nfunction describe(n: GraphNode): string | null {\n const d = n.axes?.description?.trim() || undefined\n const rawName = n.axes?.name?.trim()\n // A name that merely repeats the id adds nothing the label does not say.\n const name = rawName && rawName !== n.id ? rawName : undefined\n if (d && name) return `${name}: ${d}`\n return d ?? name ?? null\n}\n\nfunction clip(s: string, max: number): string {\n return s.length > max ? `${s.slice(0, max)}…` : s\n}\n"],"mappings":"gRAAAA,IAwBO,IAAMC,GAAmB,cAiBnBC,GAAoB,GACpBC,GAAwB,IAiB9B,SAASC,GAAYC,EAAgC,CAC1D,IAAMC,EAASD,EAAM,cAAgBF,GACrC,MAAO,CACL,MAAOE,EA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AAW,GAAKA,EAAE,SAAW,EAAG,MAAO,GAC7C,IAAIC,EAAS,EACb,QAASC,EAAI,EAAGA,EAAI,KAAK,IAAI,EAAE,OAAQF,EAAE,MAAM,GACzC,EAAEE,CAAC,IAAMF,EAAEE,CAAC,EADgCA,IAC7BD,IAGrB,GAAIA,IAAW,EAAG,MAAO,GACzB,IAAME,EAAQ,KAAK,IAAI,EAAE,OAAQH,EAAE,MAAM,EACzC,OAAOC,EAASE,CAClB","names":["init_questions","WIKI_RERANK_SEAT","DEFAULT_SHORTLIST","DEFAULT_EXCERPT_CHARS","rerankState","input","budget","c","clip","rerankQuestions","candidates","criteria","choice","noul","toRanking","answers","best","scores","order","i","a","b","diff","text","max","flat","STARTER_SCHEMA","CATEGORY_DESCRIPTIONS","STARTER_VERB_NODES","readFileSync","writeFileSync","appendFileSync","existsSync","mkdirSync","renameSync","statSync","resolve","dirname","createHash","GraphStore","opts","resolve","mkdirSync","p","existsSync","STARTER_SCHEMA","raw","readFileSync","parsed","graphSchemaSchema","i","backup","writeFileSync","e","np","nbackup","seeded","seedNodesFile","schema","safeWriteJson","nodesFileSchema","file","parse","mtimeMs","size","statSync","hit","data","node","all","level","l","missing","a","v","n","target","levelIdx","parent","parentLevelIdx","path","proposedAxes","createdBy","added","skipped","now","id","current","cursor","j","priorId","priorNode","axes","chosenLevel","parentId","chosenIdx","prior","priorIdx","c","classificationSchema","issues","line","dirname","appendFileSync","limit","status","lines","byHash","b","msgHash","update","next","suffix","out","msg","payload","normalizeForFingerprint","createHash","indexFileSchema","fp","entry","fingerprintEntrySchema","updated","child","refHolder","known","tmp","renameSync","nodes","seenCats","STARTER_VERB_NODES","CATEGORY_DESCRIPTIONS","text","init_extract_json","init_providers","init_seat","createHash","init_questions","init_seat","INTENT_PATH_SEAT","INTENT_PATH_MIN_CATEGORY_P","INTENT_PATH_MIN_VERB_P","INTENT_PATH_FULL_VERB_P","intentPathState","input","clip","nodeChoice","nodes","instructions","criteria","n","describe","choice","categoryQuestions","categories","described","fallback","CATEGORY_DESCRIPTIONS","verbQuestions","verbs","proposePathViaSeat","opts","getSeatMode","state","features","links","stage1","askSeat","cat","confidence","confident","path","sameCategory","stage2","verb","d","rawName","name","s","max","Classifier","opts","createProvider","input","fp","cached","hashPath","pathLabel","schema","nodes","proposal","path","proposedAxes","confidence","leaf","classification","existingIds","n","newNodeIndices","id","idx","structureOk","isReuseOnly","isSingleLeafAddition","confidenceOk","status","e","mode","getSeatMode","INTENT_PATH_SEAT","seatInput","viaSeat","proposePathViaSeat","viaLlm","nodesForPrompt","userPrompt","text","parsed","extractJson","NODE_ID_RE","slugMap","s","trimmed","slugged","slugifyNodeId","rawNodeId","axes","nodeId","clean","k","v","_existing","createdBy","provider","ac","timer","raw","createHash","x","ancestryScore","b","shared","i","depth"]}
@@ -1,4 +1,4 @@
1
- import{b as S,c as O}from"./chunk-CYKPDILL.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Le}from"child_process";import{writeFileSync as ee,mkdirSync as w,existsSync as b,readFileSync as $e}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Pe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
1
+ import{b as S,c as O}from"./chunk-PX2AOZ5G.js";import{a as I,b as X}from"./chunk-FCPTN6NF.js";import{a as F,b as oe}from"./chunk-7I7IEX4S.js";import{d as M}from"./chunk-QIJLFPWE.js";import{execFile as Le}from"child_process";import{writeFileSync as ee,mkdirSync as w,existsSync as b,readFileSync as $e}from"fs";import{resolve as _}from"path";var ce=["off","shadow","authoritative"],ae={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},de="INTENT_LEDGER_MODE";function B(n,e=process.env){let t=P(e[ae[n]]);if(t)return t;let i=P(e[de]);return i||"off"}function P(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return ce.includes(e)?e:null}X();import ue from"better-sqlite3";import{existsSync as Pe,mkdirSync as le}from"fs";import{dirname as ge,resolve as me}from"path";var T=class{db;path;constructor(e={}){this.path=me(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),le(ge(this.path),{recursive:!0}),this.db=new ue(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),fe(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let i=this.findEventBySourceId(e.source,e.sourceEventId);if(i)return i}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
2
2
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let i=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
3
3
  FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return i?U(i):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
4
4
  FROM intent_events WHERE id = ?`).get(e);return t?U(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
@@ -123,4 +123,4 @@ ${r.prompt}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,timeoutMinut
123
123
  `);return t.length<=e?t.join(`
124
124
  `):t.slice(-e).join(`
125
125
  `)}function Ce(n,e,t){return new Promise((i,r)=>{Le("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,c,o)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}i({stdout:String(c??""),stderr:String(o??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,G as b,it as c,De as d,rt as e,st as f,$ as g,Q as h,B as i,je as j,V as k,K as l,at as m,Ae as n,ne as o,ie as p,re as q,we as r,C as s};
126
- //# sourceMappingURL=chunk-VGI4EZTP.js.map
126
+ //# sourceMappingURL=chunk-BXYKFWAI.js.map
@@ -1,4 +1,4 @@
1
- import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-SCJ5ZXEN.js";import{C as se}from"./chunk-6WNQY6K2.js";import{a as de,b as le}from"./chunk-BGG3ZSMW.js";import{c as ae,e as oe}from"./chunk-LQE73AZR.js";import{e as F,g as ie}from"./chunk-JIT5GPTX.js";import{a as ne,b as re}from"./chunk-CYKPDILL.js";import{a as te}from"./chunk-VQM77L54.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as U,ma as j,w as L,x as Q}from"./chunk-Y5HBYSJW.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function W(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
1
+ import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-SCJ5ZXEN.js";import{C as se}from"./chunk-2QSG53RN.js";import{a as de,b as le}from"./chunk-BGG3ZSMW.js";import{c as ae,e as oe}from"./chunk-LQE73AZR.js";import{e as F,g as ie}from"./chunk-JIT5GPTX.js";import{a as ne,b as re}from"./chunk-PX2AOZ5G.js";import{a as te}from"./chunk-K3BG77KK.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as U,ma as j,w as L,x as Q}from"./chunk-IGORU3XR.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function W(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
2
2
  `,l=n+".tmp";Y(l,s,"utf-8");try{JSON.parse(pe(l,"utf-8"))}catch(c){throw new Error(`config did not round-trip cleanly: ${c.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,Me(n,i)),Y(n,s,"utf-8"),t.skipReload||Ne().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function ue(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(ge(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return Y(n,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:n}}async function Ne(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function fe(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
@@ -742,4 +742,4 @@ tr:hover td { background: var(--bg-hover); }
742
742
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
743
  ${r}`).all(t,...n,...a).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function pn(e,t){return Ae(e,t,L,"ORDER BY created_at")}function gn(e,t,n=50){return Ae(e,t,[...L,...Q],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ze();var V="member:",gt=90,mt="members",ut="tailscale-user-login",ft=400,ht=60*60*1e3;function vt(e){let t=e.scopes.find(n=>n.startsWith(V));return t?t.slice(V.length):null}function Ie(e,t){if(!e)return null;let n=t.verify(e),r=n?vt(n):null;return n&&r?{rec:n,personId:r}:null}function xn(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${V}${n.id}`],expiresInDays:gt}),{code:o,expiresAt:s}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:a.id,person:n}}var bt=Math.round(ae/6e4);function xt(e){return e==="client"?"Your project":"My work"}function yn(e){let t=xt(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${oe(e.code)}`,` The code works once, for ${bt} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
744
744
  `)}var yt="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",kt="Too many machines are waiting for the owner's answer. Try again later.",Se="That code didn't work. Check it, or ask the person who invited you for a new one.",Ee=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Te(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function wt(e){if(!Te(e))return null;let t=Ee(e,ut).toLowerCase();return t?t.slice(0,80):null}function $t(e){let t=e.socket?.remoteAddress||"unknown";if(!Te(e))return t;let n=Ee(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function At(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function St(e){return e.identities.map(Z).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function kn(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(m=>console.log(m)),o=$t(e),s=t.limiter.retryAfter(o);if(s>0)return a(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await se(e,2048);l=m.code,i=At(m.machine)}catch{}let c=t.codes.redeem(l),g=c?Ie(c.token,t.tokens):null;if(await Et(n,t.minMs??ft),!c||!g)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Se}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:Se}};let u=wt(e),A=St(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),a(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:yt}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=ie(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:mt},{now:r()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),a(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:c.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),a(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:kt}})}var H="this machine is not paired",It="waiting for the owner to approve this machine";function Ce(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function wn(e,t){return t.state==="pending"&&t.cardId?Ce(F(e,t.cardId)):null}function $n(e,t,n){let r=t.now??Date.now,a=t.log??(g=>console.log(g)),o=Ie(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Re(t,s.id,"person no longer listed"),a(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?F(t.root,i.cardId):null,f=Ce(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(r()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),a(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),a(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:It,waiting:!0}}let c=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(r()-c>=ht||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Re(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function An(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Re(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Et(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pe=["gitlab","github"];function Tt(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pe.includes(r))throw new Error(`Request status works on ${Pe.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function En(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Tn(e){let{summary:t}=W(n=>Tt(n,e?.channel,!!e?.enabled));return{summary:t}}var Ct="https://ntfy.sh";function Rn(e){return{enabled:!!e?.enabled,server:e?.server||Ct,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,xe as b,jt as c,Ft as d,Jt as e,Vt as f,Qt as g,Zt as h,cn as i,pn as j,gn as k,gt as l,xn as m,bt as n,xt as o,yn as p,$t as q,kn as r,wn as s,$n as t,Re as u,An as v,Pe as w,Tt as x,En as y,Tn as z,Rn as A,Pn as B,lt as C,sn as D};
745
- //# sourceMappingURL=chunk-HPY54DU6.js.map
745
+ //# sourceMappingURL=chunk-CJJULHPJ.js.map