agentix-cli 0.72.0 → 0.74.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 (112) hide show
  1. package/dist/{App-244WEQJR.js → App-U2MOUDOM.js} +2 -2
  2. package/dist/{ChatApp-SFP6SHUU.js → ChatApp-YY4RGZSI.js} +2 -2
  3. package/dist/{agent-PMNBXRFW.js → agent-HEL3Y4NA.js} +2 -2
  4. package/dist/{board-dashboard-J34PSEJS.js → board-dashboard-GNMELVCM.js} +262 -179
  5. package/dist/board-dashboard-GNMELVCM.js.map +1 -0
  6. package/dist/{chunk-335JCO5R.js → chunk-22TKLH6A.js} +170 -170
  7. package/dist/chunk-22TKLH6A.js.map +1 -0
  8. package/dist/{chunk-OSHG52OO.js → chunk-2RGXCUE3.js} +26 -26
  9. package/dist/{chunk-OSHG52OO.js.map → chunk-2RGXCUE3.js.map} +1 -1
  10. package/dist/{chunk-PY54XYAG.js → chunk-3TQ2WONT.js} +2 -2
  11. package/dist/{chunk-OWRPCMGW.js → chunk-6PUNM3Y7.js} +233 -214
  12. package/dist/chunk-6PUNM3Y7.js.map +1 -0
  13. package/dist/chunk-7XB2CVC3.js +2 -0
  14. package/dist/chunk-7XB2CVC3.js.map +1 -0
  15. package/dist/{chunk-DMWFRKWR.js → chunk-BOY572B3.js} +2 -2
  16. package/dist/{chunk-QKV7FN67.js → chunk-CVEL3UBP.js} +2 -2
  17. package/dist/{chunk-YVLFX35J.js → chunk-DEYXG7OA.js} +2 -2
  18. package/dist/{chunk-55N4VTWX.js → chunk-E343ELHB.js} +2 -2
  19. package/dist/{chunk-576L7ZFD.js → chunk-HAUOH34T.js} +2 -2
  20. package/dist/{chunk-7XR5LGLD.js → chunk-HGEZBEBI.js} +2 -2
  21. package/dist/{chunk-PC5LKW3L.js → chunk-HX4AF2N4.js} +2 -2
  22. package/dist/{chunk-FMUOVVXX.js → chunk-IEEKRDVW.js} +2 -2
  23. package/dist/{chunk-VWMO4C72.js → chunk-JXBXIH23.js} +2 -2
  24. package/dist/{chunk-MESWF2ZM.js → chunk-MMTP7WWU.js} +2 -2
  25. package/dist/{chunk-UFPWMNUW.js → chunk-RDEDIOAH.js} +2 -2
  26. package/dist/{chunk-PHSYP22H.js → chunk-ROKRMNVL.js} +2 -2
  27. package/dist/{chunk-J6RZOP7Z.js → chunk-S4NYBA3M.js} +2 -2
  28. package/dist/{chunk-PBRI3MTE.js → chunk-TUPHLC77.js} +2 -2
  29. package/dist/chunk-U7LOXDIP.js +15 -0
  30. package/dist/chunk-U7LOXDIP.js.map +1 -0
  31. package/dist/{chunk-Z5TXWHDN.js → chunk-W7XQCUDK.js} +2 -2
  32. package/dist/{chunk-FWQVXZ5T.js → chunk-WIBDEAAB.js} +32 -30
  33. package/dist/chunk-WIBDEAAB.js.map +1 -0
  34. package/dist/{chunk-TT4T6CB3.js → chunk-X6MK5VK3.js} +2 -2
  35. package/dist/cli.js +1 -1
  36. package/dist/client-7SK3SEQV.js +2 -0
  37. package/dist/{config-X7BHZ75G.js → config-6UXC7MPC.js} +2 -2
  38. package/dist/config-mutator-QNTAKNI7.js +2 -0
  39. package/dist/doctor-FNM7ZKP3.js +2 -0
  40. package/dist/{facts-X44PF73W.js → facts-2K6UX5GD.js} +6 -6
  41. package/dist/facts-2K6UX5GD.js.map +1 -0
  42. package/dist/index.d.ts +251 -6
  43. package/dist/index.js +1 -1
  44. package/dist/program-3DYKSCIY.js +2 -0
  45. package/dist/{promote-36XF4LH7.js → promote-I5QCWYXG.js} +2 -2
  46. package/dist/{query-YFZ6GWHU.js → query-WNOCMO46.js} +2 -2
  47. package/dist/{registry-WJSGG62F.js → registry-KXNT3HID.js} +2 -2
  48. package/dist/{request-planner-OXRWVBXI.js → request-planner-VAHGNG7U.js} +2 -2
  49. package/dist/{review-candidates-5XZWP2BN.js → review-candidates-UQJ3IA2Z.js} +2 -2
  50. package/dist/{routing-XEPCPLVM.js → routing-AVMCSZXP.js} +2 -2
  51. package/dist/schedule-tool-O47FNQ3A.js +2 -0
  52. package/dist/scheduler-DBAQHLHQ.js +2 -0
  53. package/dist/{seat-FGFHW363.js → seat-2GOJBTII.js} +2 -2
  54. package/dist/{select-N6CIZF2S.js → select-GIDPNJAA.js} +2 -2
  55. package/dist/{set-enabled-L7Z6H7EG.js → set-enabled-QW33PWJV.js} +2 -2
  56. package/dist/{tool-OSH6GHIF.js → tool-RXQ4F6HI.js} +2 -2
  57. package/dist/wiki-T22CW4EY.js +2 -0
  58. package/package.json +1 -1
  59. package/dist/board-dashboard-J34PSEJS.js.map +0 -1
  60. package/dist/chunk-335JCO5R.js.map +0 -1
  61. package/dist/chunk-FWQVXZ5T.js.map +0 -1
  62. package/dist/chunk-NMFXY3QU.js +0 -2
  63. package/dist/chunk-NMFXY3QU.js.map +0 -1
  64. package/dist/chunk-OWRPCMGW.js.map +0 -1
  65. package/dist/chunk-RAYOK4GI.js +0 -15
  66. package/dist/chunk-RAYOK4GI.js.map +0 -1
  67. package/dist/client-L4JAPXTE.js +0 -2
  68. package/dist/config-mutator-R2KBGTZJ.js +0 -2
  69. package/dist/doctor-5VFQVAVC.js +0 -2
  70. package/dist/facts-X44PF73W.js.map +0 -1
  71. package/dist/program-6C3G65YA.js +0 -2
  72. package/dist/schedule-tool-WQCO2YUG.js +0 -2
  73. package/dist/scheduler-4NQ62XDK.js +0 -2
  74. package/dist/wiki-E46QDRS7.js +0 -2
  75. /package/dist/{App-244WEQJR.js.map → App-U2MOUDOM.js.map} +0 -0
  76. /package/dist/{ChatApp-SFP6SHUU.js.map → ChatApp-YY4RGZSI.js.map} +0 -0
  77. /package/dist/{agent-PMNBXRFW.js.map → agent-HEL3Y4NA.js.map} +0 -0
  78. /package/dist/{chunk-PY54XYAG.js.map → chunk-3TQ2WONT.js.map} +0 -0
  79. /package/dist/{chunk-DMWFRKWR.js.map → chunk-BOY572B3.js.map} +0 -0
  80. /package/dist/{chunk-QKV7FN67.js.map → chunk-CVEL3UBP.js.map} +0 -0
  81. /package/dist/{chunk-YVLFX35J.js.map → chunk-DEYXG7OA.js.map} +0 -0
  82. /package/dist/{chunk-55N4VTWX.js.map → chunk-E343ELHB.js.map} +0 -0
  83. /package/dist/{chunk-576L7ZFD.js.map → chunk-HAUOH34T.js.map} +0 -0
  84. /package/dist/{chunk-7XR5LGLD.js.map → chunk-HGEZBEBI.js.map} +0 -0
  85. /package/dist/{chunk-PC5LKW3L.js.map → chunk-HX4AF2N4.js.map} +0 -0
  86. /package/dist/{chunk-FMUOVVXX.js.map → chunk-IEEKRDVW.js.map} +0 -0
  87. /package/dist/{chunk-VWMO4C72.js.map → chunk-JXBXIH23.js.map} +0 -0
  88. /package/dist/{chunk-MESWF2ZM.js.map → chunk-MMTP7WWU.js.map} +0 -0
  89. /package/dist/{chunk-UFPWMNUW.js.map → chunk-RDEDIOAH.js.map} +0 -0
  90. /package/dist/{chunk-PHSYP22H.js.map → chunk-ROKRMNVL.js.map} +0 -0
  91. /package/dist/{chunk-J6RZOP7Z.js.map → chunk-S4NYBA3M.js.map} +0 -0
  92. /package/dist/{chunk-PBRI3MTE.js.map → chunk-TUPHLC77.js.map} +0 -0
  93. /package/dist/{chunk-Z5TXWHDN.js.map → chunk-W7XQCUDK.js.map} +0 -0
  94. /package/dist/{chunk-TT4T6CB3.js.map → chunk-X6MK5VK3.js.map} +0 -0
  95. /package/dist/{client-L4JAPXTE.js.map → client-7SK3SEQV.js.map} +0 -0
  96. /package/dist/{config-X7BHZ75G.js.map → config-6UXC7MPC.js.map} +0 -0
  97. /package/dist/{config-mutator-R2KBGTZJ.js.map → config-mutator-QNTAKNI7.js.map} +0 -0
  98. /package/dist/{doctor-5VFQVAVC.js.map → doctor-FNM7ZKP3.js.map} +0 -0
  99. /package/dist/{program-6C3G65YA.js.map → program-3DYKSCIY.js.map} +0 -0
  100. /package/dist/{promote-36XF4LH7.js.map → promote-I5QCWYXG.js.map} +0 -0
  101. /package/dist/{query-YFZ6GWHU.js.map → query-WNOCMO46.js.map} +0 -0
  102. /package/dist/{registry-WJSGG62F.js.map → registry-KXNT3HID.js.map} +0 -0
  103. /package/dist/{request-planner-OXRWVBXI.js.map → request-planner-VAHGNG7U.js.map} +0 -0
  104. /package/dist/{review-candidates-5XZWP2BN.js.map → review-candidates-UQJ3IA2Z.js.map} +0 -0
  105. /package/dist/{routing-XEPCPLVM.js.map → routing-AVMCSZXP.js.map} +0 -0
  106. /package/dist/{schedule-tool-WQCO2YUG.js.map → schedule-tool-O47FNQ3A.js.map} +0 -0
  107. /package/dist/{scheduler-4NQ62XDK.js.map → scheduler-DBAQHLHQ.js.map} +0 -0
  108. /package/dist/{seat-FGFHW363.js.map → seat-2GOJBTII.js.map} +0 -0
  109. /package/dist/{select-N6CIZF2S.js.map → select-GIDPNJAA.js.map} +0 -0
  110. /package/dist/{set-enabled-L7Z6H7EG.js.map → set-enabled-QW33PWJV.js.map} +0 -0
  111. /package/dist/{tool-OSH6GHIF.js.map → tool-RXQ4F6HI.js.map} +0 -0
  112. /package/dist/{wiki-E46QDRS7.js.map → wiki-T22CW4EY.js.map} +0 -0
@@ -1,6 +1,6 @@
1
- import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-YVLFX35J.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(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 ne(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)."}},G=[{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 M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=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]"),F(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=O.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{M(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{M(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=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(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=T.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=T.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),Y(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 g=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){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;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,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, 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 u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}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=$.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)+`
1
+ import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-DEYXG7OA.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(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 ne(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)."}},G=[{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 M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=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]"),F(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=O.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{M(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{M(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=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(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=T.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=T.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),Y(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 g=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){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;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,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, 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 u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}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=$.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
2
  `,n=this.classificationsPath();return S(n)||F(X(n),{recursive:!0}),ie(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
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=$.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
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=$.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[ce(e.text),e.channel??""].join("");return ae("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=j.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=j.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=U.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 Y(a,e){F(X(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;M(t,JSON.stringify(e,null,2)),oe(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of G)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of G)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 ce(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)}re();te();W();import{createHash as me}from"crypto";V();W();var P="intent-path",de=.5,le=.3;function pe(a){return{message:fe(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function Z(a,e){let t={};for(let r of a)t[r.id]=he(r);return C(t,e)}function ge(a){return{category:Z(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function ue(a){return{verb:Z(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 D(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=pe(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await E(P,n,ge(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>=de,b=[c.choice],g=e.filter(m=>m.parentId===c.choice);if(g.length>=2){let m=t.incumbent?.[0]===c.choice,d=await E(P,{...n,category:c.choice},ue(g),{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;l=Math.min(l,f.pMax),h=h&&f.pMax>=le,b.push(f.choice)}else g.length===1&&b.push(g[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function he(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 fe(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=J(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:q(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)},g=new Set(o.map(u=>u.id)),m=s.map((u,p)=>g.has(u)?-1:p).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=m.length===0,p=m.length===1&&m[0]===s.length-1;d=u||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(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:q(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 D(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&&D(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
5
  `),i=await this.callProvider(o),s=B(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=ee(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)??ee(d);if(!v)continue;let u={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(u[p]=y);!u.name&&d!==v&&(u.name=d.trim()),b[v]=u}let g={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(g.input=s.leaf.input),typeof s.leaf.output=="string"&&(g.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:g}}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 ee(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 me("sha1").update(a.join("")).digest("hex").slice(0,16)}function q(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 ve(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{we as a,be as b,xe as c,Se as d,Ne as e,x as f,_ as g,L as h,q as i,ve as j};
6
- //# sourceMappingURL=chunk-TT4T6CB3.js.map
6
+ //# sourceMappingURL=chunk-X6MK5VK3.js.map
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as n}from"./chunk-335JCO5R.js";import"./chunk-7XR5LGLD.js";import"./chunk-PC5LKW3L.js";import"./chunk-J6RZOP7Z.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-SZDACK6O.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-OWRPCMGW.js";import"./chunk-FWQVXZ5T.js";import"./chunk-PY54XYAG.js";import"./chunk-BYJ3A55Y.js";import"./chunk-NMFXY3QU.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-VWMO4C72.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-OSHG52OO.js";import"./chunk-PBRI3MTE.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-Z5TXWHDN.js";import"./chunk-SFQUP3BP.js";import"./chunk-576L7ZFD.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-DMWFRKWR.js";import"./chunk-55N4VTWX.js";import"./chunk-VWTBHLMX.js";import"./chunk-QKV7FN67.js";import"./chunk-PHSYP22H.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-UFPWMNUW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-MESWF2ZM.js";import"./chunk-TT4T6CB3.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-YVLFX35J.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-RAYOK4GI.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
2
+ import{a as n}from"./chunk-22TKLH6A.js";import"./chunk-HGEZBEBI.js";import"./chunk-HX4AF2N4.js";import"./chunk-S4NYBA3M.js";import"./chunk-Z3IP66SL.js";import"./chunk-C4CDVE2E.js";import"./chunk-RKPAVWXF.js";import"./chunk-SZDACK6O.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-6PUNM3Y7.js";import"./chunk-WIBDEAAB.js";import"./chunk-3TQ2WONT.js";import"./chunk-BYJ3A55Y.js";import"./chunk-7XB2CVC3.js";import"./chunk-LQRBGQIR.js";import"./chunk-ZVP6GB4G.js";import"./chunk-JXBXIH23.js";import"./chunk-AQASR6KR.js";import"./chunk-2D3RYIDU.js";import"./chunk-EKJG63EJ.js";import"./chunk-2RGXCUE3.js";import"./chunk-TUPHLC77.js";import"./chunk-WP6KLXTP.js";import"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-W7XQCUDK.js";import"./chunk-SFQUP3BP.js";import"./chunk-HAUOH34T.js";import"./chunk-2AXFYDWF.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-BOY572B3.js";import"./chunk-E343ELHB.js";import"./chunk-VWTBHLMX.js";import"./chunk-CVEL3UBP.js";import"./chunk-ROKRMNVL.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-RDEDIOAH.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-MMTP7WWU.js";import"./chunk-X6MK5VK3.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-DEYXG7OA.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-U7LOXDIP.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";var r=["SIGINT","SIGTERM"];function o(t=process){for(let i of r)t.on(i,()=>{t.listenerCount(i)<=1&&t.exit(0)})}o();async function s(){let t=await n();if(process.argv.slice(2).length===0){t.outputHelp();return}t.parse()}s();
3
3
  //# sourceMappingURL=cli.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e,f,g}from"./chunk-HGEZBEBI.js";import"./chunk-U7LOXDIP.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
2
+ //# sourceMappingURL=client-7SK3SEQV.js.map
@@ -1,2 +1,2 @@
1
- import{A as i,r as a,s as b,t as c,u as d,v as e,w as f,x as g,y as h}from"./chunk-RAYOK4GI.js";import"./chunk-QIJLFPWE.js";i();export{a as INTEGRATION_KINDS,d as approvalsConfigSchema,c as callsSchema,e as daemonConfigSchema,b as eventSubscriptionSchema,f as expandEnvVars,g as loadDaemonConfig,h as validateWorkspaces};
2
- //# sourceMappingURL=config-X7BHZ75G.js.map
1
+ import{A as h,C as i,t as a,u as b,v as c,w as d,x as e,y as f,z as g}from"./chunk-U7LOXDIP.js";import"./chunk-QIJLFPWE.js";i();export{a as INTEGRATION_KINDS,d as approvalsConfigSchema,c as callsSchema,e as daemonConfigSchema,b as eventSubscriptionSchema,f as expandEnvVars,g as loadDaemonConfig,h as validateWorkspaces};
2
+ //# sourceMappingURL=config-6UXC7MPC.js.map
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d,e}from"./chunk-E343ELHB.js";import"./chunk-U7LOXDIP.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
2
+ //# sourceMappingURL=config-mutator-QNTAKNI7.js.map
@@ -0,0 +1,2 @@
1
+ import{b as a,c as b,d as c,e as d,f as e}from"./chunk-HX4AF2N4.js";import"./chunk-BYJ3A55Y.js";import"./chunk-U7LOXDIP.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
2
+ //# sourceMappingURL=doctor-FNM7ZKP3.js.map
@@ -1,7 +1,7 @@
1
- import{b as A}from"./chunk-NMFXY3QU.js";import"./chunk-QIJLFPWE.js";import{existsSync as C,readFileSync as j}from"fs";import{resolve as M}from"path";import{execFile as G}from"child_process";function p(n,t,o={}){return new Promise(e=>{G(n,t,{timeout:o.timeoutMs??15e3,signal:o.signal,maxBuffer:4*1024*1024,env:{...process.env,PATH:[process.env.PATH??"","/opt/homebrew/bin","/usr/local/bin",`${process.env.HOME??""}/.local/bin`].filter(Boolean).join(":")}},(r,a,i)=>{let s=r&&typeof r.code=="number"?r.code:r?1:0;e({stdout:String(a??""),stderr:String(i??""),code:s})})})}async function y(n){let{code:t}=await p("command",["-v",n],{timeoutMs:3e3}).catch(()=>({code:1}));if(t===0)return!0;let{code:o}=await p("/usr/bin/which",[n],{timeoutMs:3e3});return o===0}var I=[["216","Tunisia"],["966","Saudi Arabia"],["971","UAE"],["974","Qatar"],["965","Kuwait"],["973","Bahrain"],["968","Oman"],["962","Jordan"],["961","Lebanon"],["212","Morocco"],["213","Algeria"],["218","Libya"],["249","Sudan"],["20","Egypt"],["90","Turkey"],["33","France"],["49","Germany"],["39","Italy"],["34","Spain"],["44","United Kingdom"],["31","Netherlands"],["32","Belgium"],["41","Switzerland"],["1","US/Canada"]];function m(n){let t=n.replace(/\D/g,""),o,e=0;for(let[r,a]of I)t.startsWith(r)&&r.length>e&&(o=a,e=r.length);return o}function F(n){let t=[];for(let o of n.split(`
2
- `)){let e=o.trim();if(!e||e.startsWith("ALIAS"))continue;let r=e.split(/\s{2,}/).filter(Boolean);if(r.length<2)continue;let a=r[r.length-1];if(!a.includes("@"))continue;let i=r[r.length-2],s=r.length>=3?r[r.length-3]:"";if(!s||!/\d/.test(i))continue;let l=m(i);t.push({name:s,source:"wacli",fields:{phone:`+${i.replace(/\D/g,"")}`,whatsapp:a,...l?{country:l}:{}}})}return t}function w(){return{name:"wacli",provides:["contact value","country"],async available(){if(!await y("wacli"))return{kind:"not-installed",hint:"brew install wacli \u2014 see https://wacli.sh"};let{stdout:n,stderr:t,code:o}=await p("wacli",["contacts","search","__agentx_probe__"],{timeoutMs:1e4});return o!==0&&/auth|not logged in|no session|login/i.test(n+t)?{kind:"not-configured",hint:"wacli auth \u2014 scan the QR to link the account"}:null},async lookup(n,t){let o=[],e=new Set;for(let r of n)for(let a of T(r.name)){let{stdout:i,code:s}=await p("wacli",["contacts","search",a],{signal:t,timeoutMs:15e3});if(s!==0)continue;let l=F(i).filter(u=>E(u.name,r.name));if(l.length!==0){for(let u of l){let c=u.fields.whatsapp;e.has(c)||(e.add(c),o.push({...u,fuzzy:!P(u.name,r.name)}))}break}}return o}}}var h=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim(),P=(n,t)=>h(n)===h(t);function T(n){let t=h(n).split(/\s+/).filter(o=>o.length>2);return t.length>1?[n,t[t.length-1]]:[n]}function E(n,t){let o=h(n).split(/\s+/).filter(Boolean),e=h(t).split(/\s+/).filter(Boolean);if(o.length===0||e.length===0)return!1;let[r,a]=o.length<=e.length?[o,e]:[e,o];return r.every(i=>a.includes(i))}var D={whatsapp:"whatsapp",telegram:"telegram",gitlab:"gitlab",github:"github",email:"email",phone:"phone",slack:"slack",discord:"discord"};function z(n=".agentx"){return M(process.cwd(),n,"contacts.json")}function S(n){if(!C(n))return[];try{let t=JSON.parse(j(n,"utf-8"));return Array.isArray(t?.contacts)?t.contacts:[]}catch{return[]}}var b=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim();function _(n){return[n.name,n.id,...n.aliases??[]].filter(t=>!!(t&&t.trim())).map(b)}function L(n){let t={};for(let[o,e]of Object.entries(n.channels??{})){let r=String(e??"").trim();if(!r)continue;let a=D[o.toLowerCase()]??o.toLowerCase();if(a==="whatsapp"){let i=r.split("@")[0].replace(/\D/g,"");if(t.whatsapp=r.includes("@")?r:`${i}@s.whatsapp.net`,i){t.phone??=`+${i}`;let s=m(i);s&&(t.country??=s)}continue}if(a==="phone"){let i=r.replace(/\D/g,"");t.phone=r.startsWith("+")?r:`+${i}`;let s=m(i);s&&(t.country??=s);continue}if(a==="telegram"&&/^\d+$/.test(r)){t.telegramId=r;continue}t[a]=a==="gitlab"||a==="github"?r.startsWith("@")?r:`@${r}`:r}return t}function k(n={}){let t=n.path??z();return{name:"contacts",provides:["contact value","handles","country"],async available(){return C(t)?S(t).length>0?null:{kind:"not-configured",hint:`${t} has no contacts`}:{kind:"not-configured",hint:`no ${t} \u2014 add {"contacts":[{"name":"\u2026","aliases":[],"channels":{"whatsapp":"\u2026"}}]}`}},async lookup(o){let e=S(t);if(e.length===0)return[];let r=new Map;for(let s of e)for(let l of _(s))l&&r.set(l,s);let a=[],i=new Set;for(let s of o){let l=r.get(b(s.name));if(!l||i.has(l))continue;i.add(l);let u=L(l);Object.keys(u).length!==0&&a.push({name:l.name??s.name,source:"contacts",fields:u,fuzzy:b(l.name??"")!==b(s.name)})}return a}}}function v(n={}){let t=(n.baseUrl??process.env.GITLAB_URL??"").replace(/\/+$/,""),o=n.token??process.env.GITLAB_ADMIN_TOKEN??process.env.GITLAB_TOKEN;return{name:"gitlab",provides:["email","handle","profile URL"],async available(){if(!t)return{kind:"not-configured",hint:"export GITLAB_URL=https://<your-gitlab-host>"};if(!o)return{kind:"not-configured",hint:"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)"};try{let e=await fetch(`${t}/api/v4/user`,{headers:{"PRIVATE-TOKEN":o}});if(e.status===401||e.status===403)return{kind:"not-configured",hint:`GitLab rejected the token (${e.status}) \u2014 set a valid GITLAB_ADMIN_TOKEN`};if(!e.ok)return{kind:"failed",hint:`GitLab returned ${e.status} for the auth probe`}}catch(e){return{kind:"failed",hint:`cannot reach ${t}: ${String(e?.message??e)}`}}return null},async lookup(e,r){if(!o||!t)return[];let a=[],i=new Set;for(let s of e){let l=`${t}/api/v4/users?search=${encodeURIComponent(s.name)}&per_page=5`,u;try{let c=await fetch(l,{headers:{"PRIVATE-TOKEN":o},signal:r});if(!c.ok)continue;u=await c.json()}catch{continue}if(Array.isArray(u))for(let c of u){let d=c.username??c.web_url??"";if(!d||i.has(d))continue;i.add(d);let f={},g=c.email||c.public_email;g&&(f.email=g),c.username&&(f.gitlab=`@${c.username}`),c.web_url&&(f.profile=c.web_url),c.organization&&(f.organisation=c.organization),c.job_title&&(f.role=c.job_title),c.state&&c.state!=="active"&&(f.accountState=c.state),Object.keys(f).length!==0&&a.push({name:c.name??s.name,source:"gitlab",fields:f,fuzzy:(c.name??"").toLowerCase()!==s.name.toLowerCase()})}}return a}}}function x(){return{name:"gog",provides:["contact value","email","organisation","role","country"],async available(){if(!await y("gog"))return{kind:"not-installed",hint:"brew install gog \u2014 Google CLI"};let{stdout:n,stderr:t}=await p("gog",["contacts","list","-j"],{timeoutMs:2e4}),o=n+t;return/unknown flag|Run with --help/i.test(o)?{kind:"failed",hint:`gog rejected the probe: ${o.split(`
3
- `)[0]}`}:/accessNotConfigured|has not been used in project/i.test(o)?{kind:"not-configured",hint:"enable the People API on the gog OAuth project, then retry (console.developers.google.com \u2192 APIs \u2192 People API)"}:/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(o)?{kind:"not-configured",hint:"gog auth login \u2014 the stored token is expired or lacks contacts scope"}:null},async lookup(n,t){let o=[];for(let e of n){let{stdout:r,code:a}=await p("gog",["contacts","search",e.name,"-j","--results-only"],{signal:t,timeoutMs:2e4});if(a!==0)continue;let i;try{i=JSON.parse(r)}catch{continue}let s=Array.isArray(i)?i:i?.results??i?.people??[];for(let l of s){let u={},c=l.phoneNumbers?.[0]?.value,d=l.emailAddresses?.[0]?.value,f=l.organizations?.[0];c&&(u.phone=c),d&&(u.email=d),f?.name&&(u.organisation=f.name),f?.title&&(u.role=f.title);let g=l.addresses?.[0]?.country;g&&(u.country=g),Object.keys(u).length!==0&&o.push({name:l.names?.[0]?.displayName??e.name,source:"gog",fields:u})}}return o}}}var R=n=>typeof n=="string"&&n.trim()?n.trim():void 0;function $(n){return String(n??"").split("@")[0].split(":")[0].toLowerCase()}function H(n){let t=new Map;for(let o of n){let e=R(o.meta?.sender);if(!e||A(e))continue;let r=R(o.meta?.senderId),a=R(o.meta?.senderUsername),i=$(o.source),s={};if(r&&/@s\.whatsapp\.net$/.test(r)){let c=r.split("@")[0].replace(/\D/g,"");if(c){s.phone=`+${c}`,s.whatsapp=r;let d=m(c);d&&(s.country=d)}}else if(i==="whatsapp"&&r&&/^\d{6,}$/.test(r)){s.phone=`+${r}`,s.whatsapp=`${r}@s.whatsapp.net`;let c=m(r);c&&(s.country=c)}if(a){let c=a.startsWith("@")?a:`@${a}`;i==="gitlab"?s.gitlab=c:i==="github"?s.github=c:i==="telegram"?s.telegram=c:s.handle=c}if(r&&!s.phone&&!a&&(s[`${i||"platform"}Id`]=r),Object.keys(s).length===0)continue;let l=e.toLowerCase(),u=t.get(l);if(!u){t.set(l,{name:e,source:"entries",fields:s});continue}for(let[c,d]of Object.entries(s))u.fields[c]??=d}return Array.from(t.values())}function U(n){let t;return{...n,available:()=>t??=n.available(),lookup:(o,e)=>n.lookup(o,e)}}function N(){return[k(),w(),v(),x()].map(U)}function ut(n,t={}){let o=t.max??25,e=new Map;for(let a of n){let i=(a.sender??"").trim();i&&O(i)&&e.set(i.toLowerCase(),{name:i,origin:"sender",type:"person"})}for(let a of n){let i=(a.context??"").trim();if(!O(i))continue;let s=i.toLowerCase();e.has(s)||e.set(s,{name:i,origin:"context"})}let r=(t.known??[]).filter(a=>a.trim().length>2);if(r.length>0){let a=n.map(i=>i.content??"").join(`
4
- `).toLowerCase();for(let i of r){let s=i.toLowerCase().trim();e.has(s)||a.includes(s)&&e.set(s,{name:i,origin:"body",type:"person"})}}return Array.from(e.values()).slice(0,o)}var B=new Set(["me","user","system","cron","unknown","anonymous","bot","agent","self","test","admin","none","null","n/a"]),W=new Set(["group","team","chat","channel","squad","crew","room","family","project","board","committee","club","staff","office","dept","department","support","sales","ops","admins","everyone","all"]);function O(n){let t=n.trim();if(!t||t.length>48||B.has(t.toLowerCase())||/[\d@/\\#:|_]/.test(t))return!1;let o=t.split(/\s+/);return o.length<2||o.length>4||o.some(e=>W.has(e.toLowerCase()))?!1:o.every(e=>/^[\p{Lu}][\p{L}'’.-]*$/u.test(e))}async function ft(n,t={}){let o=t.sources??N(),e=n.slice(0,t.maxEntities??25);if(e.length===0)return{records:[],results:[]};let r=new AbortController,a=setTimeout(()=>r.abort(),t.timeoutMs??12e4);try{let i=await Promise.all(o.map(async s=>{let l=Date.now();try{let u=await s.available();if(u)return{source:s.name,records:[],unavailable:u,ms:Date.now()-l};let c=await s.lookup(e,r.signal);return{source:s.name,records:c,ms:Date.now()-l}}catch(u){return{source:s.name,records:[],unavailable:{kind:"failed",hint:String(u?.message??u)},ms:Date.now()-l}}}));for(let s of i)t.onResult?.(s);return{records:i.flatMap(s=>s.records),results:i}}finally{clearTimeout(a)}}function dt(n,t=N()){let o=new Map(t.map(e=>[e.name,e.provides]));return n.filter(e=>e.unavailable&&e.unavailable.kind!=="failed").map(e=>({source:e.source,kind:e.unavailable.kind,hint:e.unavailable.hint,provides:o.get(e.source)??[]}))}function pt(n){let t=new Map;for(let o of n){let e=o.name.toLowerCase().trim(),r=t.get(e);r||(r={name:o.name,fields:{}},t.set(e,r));for(let[a,i]of Object.entries(o.fields)){if(!i?.trim())continue;let s=r.fields[a];if(!s){r.fields[a]={value:i,source:o.source};continue}s.value!==i&&(r.fields[`${a} (${o.source})`]??={value:i,source:o.source})}}return Array.from(t.values())}function mt(n){if(n.length===0)return"";let t=n.filter(o=>Object.keys(o.fields).length>0).map(o=>{let e=Object.entries(o.fields).map(([r,a])=>` - ${r}: \`${a.value}\` _(${a.source})_`).join(`
1
+ import{a as g,b as y,d as F}from"./chunk-7XB2CVC3.js";import"./chunk-QIJLFPWE.js";import{existsSync as E,readFileSync as T}from"fs";import{resolve as P}from"path";var G=[["216","Tunisia"],["966","Saudi Arabia"],["971","UAE"],["974","Qatar"],["965","Kuwait"],["973","Bahrain"],["968","Oman"],["962","Jordan"],["961","Lebanon"],["212","Morocco"],["213","Algeria"],["218","Libya"],["249","Sudan"],["20","Egypt"],["90","Turkey"],["33","France"],["49","Germany"],["39","Italy"],["34","Spain"],["44","United Kingdom"],["31","Netherlands"],["32","Belgium"],["41","Switzerland"],["1","US/Canada"]];function p(n){let t=n.replace(/\D/g,""),o,e=0;for(let[r,a]of G)t.startsWith(r)&&r.length>e&&(o=a,e=r.length);return o}function A(n){let t=[];for(let o of n.split(`
2
+ `)){let e=o.trim();if(!e||e.startsWith("ALIAS"))continue;let r=e.split(/\s{2,}/).filter(Boolean);if(r.length<2)continue;let a=r[r.length-1];if(!a.includes("@"))continue;let i=r[r.length-2],s=r.length>=3?r[r.length-3]:"";if(!s||!/\d/.test(i))continue;let l=p(i);t.push({name:s,source:"wacli",fields:{phone:`+${i.replace(/\D/g,"")}`,whatsapp:a,...l?{country:l}:{}}})}return t}function w(){return{name:"wacli",provides:["contact value","country"],async available(){if(!await y("wacli"))return{kind:"not-installed",hint:"brew install wacli \u2014 see https://wacli.sh"};let{stdout:n,stderr:t,code:o}=await g("wacli",["contacts","search","__agentx_probe__"],{timeoutMs:1e4});return o!==0&&/auth|not logged in|no session|login/i.test(n+t)?{kind:"not-configured",hint:"wacli auth \u2014 scan the QR to link the account"}:null},async lookup(n,t){let o=[],e=new Set;for(let r of n)for(let a of j(r.name)){let{stdout:i,code:s}=await g("wacli",["contacts","search",a],{signal:t,timeoutMs:15e3});if(s!==0)continue;let l=A(i).filter(u=>C(u.name,r.name));if(l.length!==0){for(let u of l){let c=u.fields.whatsapp;e.has(c)||(e.add(c),o.push({...u,fuzzy:!I(u.name,r.name)}))}break}}return o}}}var h=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim(),I=(n,t)=>h(n)===h(t);function j(n){let t=h(n).split(/\s+/).filter(o=>o.length>2);return t.length>1?[n,t[t.length-1]]:[n]}function C(n,t){let o=h(n).split(/\s+/).filter(Boolean),e=h(t).split(/\s+/).filter(Boolean);if(o.length===0||e.length===0)return!1;let[r,a]=o.length<=e.length?[o,e]:[e,o];return r.every(i=>a.includes(i))}var M={whatsapp:"whatsapp",telegram:"telegram",gitlab:"gitlab",github:"github",email:"email",phone:"phone",slack:"slack",discord:"discord"};function D(n=".agentx"){return P(process.cwd(),n,"contacts.json")}function S(n){if(!E(n))return[];try{let t=JSON.parse(T(n,"utf-8"));return Array.isArray(t?.contacts)?t.contacts:[]}catch{return[]}}var b=n=>n.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9 ]/g,"").trim();function _(n){return[n.name,n.id,...n.aliases??[]].filter(t=>!!(t&&t.trim())).map(b)}function L(n){let t={};for(let[o,e]of Object.entries(n.channels??{})){let r=String(e??"").trim();if(!r)continue;let a=M[o.toLowerCase()]??o.toLowerCase();if(a==="whatsapp"){let i=r.split("@")[0].replace(/\D/g,"");if(t.whatsapp=r.includes("@")?r:`${i}@s.whatsapp.net`,i){t.phone??=`+${i}`;let s=p(i);s&&(t.country??=s)}continue}if(a==="phone"){let i=r.replace(/\D/g,"");t.phone=r.startsWith("+")?r:`+${i}`;let s=p(i);s&&(t.country??=s);continue}if(a==="telegram"&&/^\d+$/.test(r)){t.telegramId=r;continue}t[a]=a==="gitlab"||a==="github"?r.startsWith("@")?r:`@${r}`:r}return t}function k(n={}){let t=n.path??D();return{name:"contacts",provides:["contact value","handles","country"],async available(){return E(t)?S(t).length>0?null:{kind:"not-configured",hint:`${t} has no contacts`}:{kind:"not-configured",hint:`no ${t} \u2014 add {"contacts":[{"name":"\u2026","aliases":[],"channels":{"whatsapp":"\u2026"}}]}`}},async lookup(o){let e=S(t);if(e.length===0)return[];let r=new Map;for(let s of e)for(let l of _(s))l&&r.set(l,s);let a=[],i=new Set;for(let s of o){let l=r.get(b(s.name));if(!l||i.has(l))continue;i.add(l);let u=L(l);Object.keys(u).length!==0&&a.push({name:l.name??s.name,source:"contacts",fields:u,fuzzy:b(l.name??"")!==b(s.name)})}return a}}}function v(n={}){let t=(n.baseUrl??process.env.GITLAB_URL??"").replace(/\/+$/,""),o=n.token??process.env.GITLAB_ADMIN_TOKEN??process.env.GITLAB_TOKEN;return{name:"gitlab",provides:["email","handle","profile URL"],async available(){if(!t)return{kind:"not-configured",hint:"export GITLAB_URL=https://<your-gitlab-host>"};if(!o)return{kind:"not-configured",hint:"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)"};try{let e=await fetch(`${t}/api/v4/user`,{headers:{"PRIVATE-TOKEN":o}});if(e.status===401||e.status===403)return{kind:"not-configured",hint:`GitLab rejected the token (${e.status}) \u2014 set a valid GITLAB_ADMIN_TOKEN`};if(!e.ok)return{kind:"failed",hint:`GitLab returned ${e.status} for the auth probe`}}catch(e){return{kind:"failed",hint:`cannot reach ${t}: ${String(e?.message??e)}`}}return null},async lookup(e,r){if(!o||!t)return[];let a=[],i=new Set;for(let s of e){let l=`${t}/api/v4/users?search=${encodeURIComponent(s.name)}&per_page=5`,u;try{let c=await fetch(l,{headers:{"PRIVATE-TOKEN":o},signal:r});if(!c.ok)continue;u=await c.json()}catch{continue}if(Array.isArray(u))for(let c of u){let d=c.username??c.web_url??"";if(!d||i.has(d))continue;i.add(d);let f={},m=c.email||c.public_email;m&&(f.email=m),c.username&&(f.gitlab=`@${c.username}`),c.web_url&&(f.profile=c.web_url),c.organization&&(f.organisation=c.organization),c.job_title&&(f.role=c.job_title),c.state&&c.state!=="active"&&(f.accountState=c.state),Object.keys(f).length!==0&&a.push({name:c.name??s.name,source:"gitlab",fields:f,fuzzy:(c.name??"").toLowerCase()!==s.name.toLowerCase()})}}return a}}}function x(){return{name:"gog",provides:["contact value","email","organisation","role","country"],async available(){if(!await y("gog"))return{kind:"not-installed",hint:"brew install gog \u2014 Google CLI"};let{stdout:n,stderr:t}=await g("gog",["contacts","list","-j"],{timeoutMs:2e4}),o=n+t;return/unknown flag|Run with --help/i.test(o)?{kind:"failed",hint:`gog rejected the probe: ${o.split(`
3
+ `)[0]}`}:/accessNotConfigured|has not been used in project/i.test(o)?{kind:"not-configured",hint:"enable the People API on the gog OAuth project, then retry (console.developers.google.com \u2192 APIs \u2192 People API)"}:/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(o)?{kind:"not-configured",hint:"gog auth login \u2014 the stored token is expired or lacks contacts scope"}:null},async lookup(n,t){let o=[];for(let e of n){let{stdout:r,code:a}=await g("gog",["contacts","search",e.name,"-j","--results-only"],{signal:t,timeoutMs:2e4});if(a!==0)continue;let i;try{i=JSON.parse(r)}catch{continue}let s=Array.isArray(i)?i:i?.results??i?.people??[];for(let l of s){let u={},c=l.phoneNumbers?.[0]?.value,d=l.emailAddresses?.[0]?.value,f=l.organizations?.[0];c&&(u.phone=c),d&&(u.email=d),f?.name&&(u.organisation=f.name),f?.title&&(u.role=f.title);let m=l.addresses?.[0]?.country;m&&(u.country=m),Object.keys(u).length!==0&&o.push({name:l.names?.[0]?.displayName??e.name,source:"gog",fields:u})}}return o}}}var R=n=>typeof n=="string"&&n.trim()?n.trim():void 0;function $(n){return String(n??"").split("@")[0].split(":")[0].toLowerCase()}function z(n){let t=new Map;for(let o of n){let e=R(o.meta?.sender);if(!e||F(e))continue;let r=R(o.meta?.senderId),a=R(o.meta?.senderUsername),i=$(o.source),s={};if(r&&/@s\.whatsapp\.net$/.test(r)){let c=r.split("@")[0].replace(/\D/g,"");if(c){s.phone=`+${c}`,s.whatsapp=r;let d=p(c);d&&(s.country=d)}}else if(i==="whatsapp"&&r&&/^\d{6,}$/.test(r)){s.phone=`+${r}`,s.whatsapp=`${r}@s.whatsapp.net`;let c=p(r);c&&(s.country=c)}if(a){let c=a.startsWith("@")?a:`@${a}`;i==="gitlab"?s.gitlab=c:i==="github"?s.github=c:i==="telegram"?s.telegram=c:s.handle=c}if(r&&!s.phone&&!a&&(s[`${i||"platform"}Id`]=r),Object.keys(s).length===0)continue;let l=e.toLowerCase(),u=t.get(l);if(!u){t.set(l,{name:e,source:"entries",fields:s});continue}for(let[c,d]of Object.entries(s))u.fields[c]??=d}return Array.from(t.values())}function U(n){let t;return{...n,available:()=>t??=n.available(),lookup:(o,e)=>n.lookup(o,e)}}function N(){return[k(),w(),v(),x()].map(U)}function at(n,t={}){let o=t.max??25,e=new Map;for(let a of n){let i=(a.sender??"").trim();i&&O(i)&&e.set(i.toLowerCase(),{name:i,origin:"sender",type:"person"})}for(let a of n){let i=(a.context??"").trim();if(!O(i))continue;let s=i.toLowerCase();e.has(s)||e.set(s,{name:i,origin:"context"})}let r=(t.known??[]).filter(a=>a.trim().length>2);if(r.length>0){let a=n.map(i=>i.content??"").join(`
4
+ `).toLowerCase();for(let i of r){let s=i.toLowerCase().trim();e.has(s)||a.includes(s)&&e.set(s,{name:i,origin:"body",type:"person"})}}return Array.from(e.values()).slice(0,o)}var H=new Set(["me","user","system","cron","unknown","anonymous","bot","agent","self","test","admin","none","null","n/a"]),B=new Set(["group","team","chat","channel","squad","crew","room","family","project","board","committee","club","staff","office","dept","department","support","sales","ops","admins","everyone","all"]);function O(n){let t=n.trim();if(!t||t.length>48||H.has(t.toLowerCase())||/[\d@/\\#:|_]/.test(t))return!1;let o=t.split(/\s+/);return o.length<2||o.length>4||o.some(e=>B.has(e.toLowerCase()))?!1:o.every(e=>/^[\p{Lu}][\p{L}'’.-]*$/u.test(e))}async function ct(n,t={}){let o=t.sources??N(),e=n.slice(0,t.maxEntities??25);if(e.length===0)return{records:[],results:[]};let r=new AbortController,a=setTimeout(()=>r.abort(),t.timeoutMs??12e4);try{let i=await Promise.all(o.map(async s=>{let l=Date.now();try{let u=await s.available();if(u)return{source:s.name,records:[],unavailable:u,ms:Date.now()-l};let c=await s.lookup(e,r.signal);return{source:s.name,records:c,ms:Date.now()-l}}catch(u){return{source:s.name,records:[],unavailable:{kind:"failed",hint:String(u?.message??u)},ms:Date.now()-l}}}));for(let s of i)t.onResult?.(s);return{records:i.flatMap(s=>s.records),results:i}}finally{clearTimeout(a)}}function lt(n,t=N()){let o=new Map(t.map(e=>[e.name,e.provides]));return n.filter(e=>e.unavailable&&e.unavailable.kind!=="failed").map(e=>({source:e.source,kind:e.unavailable.kind,hint:e.unavailable.hint,provides:o.get(e.source)??[]}))}function ut(n){let t=new Map;for(let o of n){let e=o.name.toLowerCase().trim(),r=t.get(e);r||(r={name:o.name,fields:{}},t.set(e,r));for(let[a,i]of Object.entries(o.fields)){if(!i?.trim())continue;let s=r.fields[a];if(!s){r.fields[a]={value:i,source:o.source};continue}s.value!==i&&(r.fields[`${a} (${o.source})`]??={value:i,source:o.source})}}return Array.from(t.values())}function ft(n){if(n.length===0)return"";let t=n.filter(o=>Object.keys(o.fields).length>0).map(o=>{let e=Object.entries(o.fields).map(([r,a])=>` - ${r}: \`${a.value}\` _(${a.source})_`).join(`
5
5
  `);return`- **${o.name}**
6
6
  ${e}`});return t.length===0?"":`
7
7
  ## Verified facts
@@ -18,5 +18,5 @@ contradicts the entries, this wins and the entry is stale.
18
18
 
19
19
  ${t.join(`
20
20
  `)}
21
- `}export{m as countryFromPhone,k as createContactsSource,v as createGitlabSource,x as createGogSource,w as createWacliSource,N as defaultSources,ut as extractHints,L as factsFrom,dt as installPrompts,O as isPersonName,S as loadContacts,U as memoizeAvailability,pt as mergeRecords,_ as namesOf,F as parseContactsTable,$ as platformOf,E as plausible,H as recordsFromEntries,mt as renderFactsBlock,ft as resolveFacts};
22
- //# sourceMappingURL=facts-X44PF73W.js.map
21
+ `}export{p as countryFromPhone,k as createContactsSource,v as createGitlabSource,x as createGogSource,w as createWacliSource,N as defaultSources,at as extractHints,L as factsFrom,lt as installPrompts,O as isPersonName,S as loadContacts,U as memoizeAvailability,ut as mergeRecords,_ as namesOf,A as parseContactsTable,$ as platformOf,C as plausible,z as recordsFromEntries,ft as renderFactsBlock,ct as resolveFacts};
22
+ //# sourceMappingURL=facts-2K6UX5GD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/wiki/facts/sources/contacts.ts","../src/wiki/facts/sources/wacli.ts","../src/wiki/facts/sources/gitlab.ts","../src/wiki/facts/sources/gog.ts","../src/wiki/facts/sources/entries.ts","../src/wiki/facts/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\n\n// The contact registry an operator maintains by hand.\n//\n// `.agentx/contacts.json` already existed and nothing in the wiki layer\n// read it, which meant the one place a person had deliberately written\n// down \"this human is these accounts\" was invisible to the pipeline\n// asking that exact question.\n//\n// It ranks above every other source. wacli knows what WhatsApp knows,\n// GitLab knows what GitLab knows, and the entries know who sent a\n// message; this is the only source where someone decided that a name,\n// an alias and a set of handles all refer to one person. Where it\n// disagrees with a directory, the deliberate answer wins — and the\n// disagreement is kept and rendered rather than resolved silently.\n//\n// It is also the only source that resolves aliases, which is what makes\n// a single registry entry cover a given name, a \"first.last\" handle and\n// the display name a phone happens to be saved under.\n\nexport interface ContactRecord {\n id?: string\n name?: string\n aliases?: string[]\n channels?: Record<string, string>\n}\n\n/** Channel key → the fact field it supplies. */\nconst CHANNEL_FIELDS: Record<string, string> = {\n whatsapp: \"whatsapp\",\n telegram: \"telegram\",\n gitlab: \"gitlab\",\n github: \"github\",\n email: \"email\",\n phone: \"phone\",\n slack: \"slack\",\n discord: \"discord\",\n}\n\nexport function contactsPath(agentxDir = \".agentx\"): string {\n return resolve(process.cwd(), agentxDir, \"contacts.json\")\n}\n\nexport function loadContacts(path: string): ContactRecord[] {\n if (!existsSync(path)) return []\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { contacts?: unknown }\n return Array.isArray(parsed?.contacts) ? (parsed.contacts as ContactRecord[]) : []\n } catch {\n return []\n }\n}\n\nconst norm = (s: string) =>\n s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\n\n/** Every spelling this registry entry answers to. */\nexport function namesOf(c: ContactRecord): string[] {\n return [c.name, c.id, ...(c.aliases ?? [])]\n .filter((x): x is string => Boolean(x && x.trim()))\n .map(norm)\n}\n\n/**\n * Turn one registry entry's channels into fact fields.\n *\n * A WhatsApp JID is also a number and a country, so it expands rather\n * than being copied across verbatim — the same unpacking the entries\n * source does, because a reader wants the number, not the routing\n * address it happens to be embedded in.\n */\nexport function factsFrom(c: ContactRecord): Record<string, string> {\n const fields: Record<string, string> = {}\n for (const [key, raw] of Object.entries(c.channels ?? {})) {\n const value = String(raw ?? \"\").trim()\n if (!value) continue\n const field = CHANNEL_FIELDS[key.toLowerCase()] ?? key.toLowerCase()\n\n if (field === \"whatsapp\") {\n const digits = value.split(\"@\")[0].replace(/\\D/g, \"\")\n fields.whatsapp = value.includes(\"@\") ? value : `${digits}@s.whatsapp.net`\n if (digits) {\n fields.phone ??= `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n }\n continue\n }\n if (field === \"phone\") {\n const digits = value.replace(/\\D/g, \"\")\n fields.phone = value.startsWith(\"+\") ? value : `+${digits}`\n const country = countryFromPhone(digits)\n if (country) fields.country ??= country\n continue\n }\n // A bare numeric Telegram id is an account, not a way to reach\n // someone — same rule the entries source applies.\n if (field === \"telegram\" && /^\\d+$/.test(value)) {\n fields.telegramId = value\n continue\n }\n fields[field] = field === \"gitlab\" || field === \"github\"\n ? (value.startsWith(\"@\") ? value : `@${value}`)\n : value\n }\n return fields\n}\n\nexport function createContactsSource(opts: { path?: string } = {}): FactSource {\n const path = opts.path ?? contactsPath()\n\n return {\n name: \"contacts\",\n provides: [\"contact value\", \"handles\", \"country\"],\n async available() {\n if (!existsSync(path)) {\n return {\n kind: \"not-configured\",\n hint: `no ${path} — add {\"contacts\":[{\"name\":\"…\",\"aliases\":[],\"channels\":{\"whatsapp\":\"…\"}}]}`,\n }\n }\n return loadContacts(path).length > 0\n ? null\n : { kind: \"not-configured\", hint: `${path} has no contacts` }\n },\n async lookup(hints: EntityHint[]) {\n const contacts = loadContacts(path)\n if (contacts.length === 0) return []\n\n const index = new Map<string, ContactRecord>()\n for (const c of contacts) for (const n of namesOf(c)) if (n) index.set(n, c)\n\n const out: FactRecord[] = []\n const seen = new Set<ContactRecord>()\n for (const h of hints) {\n const c = index.get(norm(h.name))\n if (!c || seen.has(c)) continue\n seen.add(c)\n const fields = factsFrom(c)\n if (Object.keys(fields).length === 0) continue\n out.push({\n name: c.name ?? h.name,\n source: \"contacts\",\n fields,\n // Matched on an alias rather than the registry's own name.\n fuzzy: norm(c.name ?? \"\") !== norm(h.name),\n })\n }\n return out\n },\n }\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Phone numbers, from the WhatsApp contact store.\n//\n// This is the source that closes the gap the grader found. It also\n// answers country for free: a JID is an E.164 number, so the dialling\n// prefix identifies the country without a second lookup.\n\nconst CC: Array<[string, string]> = [\n [\"216\", \"Tunisia\"], [\"966\", \"Saudi Arabia\"], [\"971\", \"UAE\"], [\"974\", \"Qatar\"],\n [\"965\", \"Kuwait\"], [\"973\", \"Bahrain\"], [\"968\", \"Oman\"], [\"962\", \"Jordan\"],\n [\"961\", \"Lebanon\"], [\"212\", \"Morocco\"], [\"213\", \"Algeria\"], [\"218\", \"Libya\"],\n [\"249\", \"Sudan\"], [\"20\", \"Egypt\"], [\"90\", \"Turkey\"], [\"33\", \"France\"],\n [\"49\", \"Germany\"], [\"39\", \"Italy\"], [\"34\", \"Spain\"], [\"44\", \"United Kingdom\"],\n [\"31\", \"Netherlands\"], [\"32\", \"Belgium\"], [\"41\", \"Switzerland\"], [\"1\", \"US/Canada\"],\n]\n\n/** Longest prefix wins, or \"1\" would claim every +1xx number. */\nexport function countryFromPhone(phone: string): string | undefined {\n const d = phone.replace(/\\D/g, \"\")\n let best: string | undefined\n let bestLen = 0\n for (const [code, name] of CC) {\n if (d.startsWith(code) && code.length > bestLen) { best = name; bestLen = code.length }\n }\n return best\n}\n\n/**\n * `wacli contacts search` prints a fixed-width table, not JSON:\n *\n * ALIAS NAME PHONE JID\n * Sample Person <e164> <e164>@s.whatsapp.net\n *\n * Parsed from the right, because ALIAS is frequently empty and NAME\n * contains spaces — splitting from the left mis-assigns both.\n */\nexport function parseContactsTable(stdout: string): FactRecord[] {\n const out: FactRecord[] = []\n for (const line of stdout.split(\"\\n\")) {\n const t = line.trim()\n if (!t || t.startsWith(\"ALIAS\")) continue\n const cols = t.split(/\\s{2,}/).filter(Boolean)\n if (cols.length < 2) continue\n const jid = cols[cols.length - 1]\n if (!jid.includes(\"@\")) continue\n const phone = cols[cols.length - 2]\n const name = cols.length >= 3 ? cols[cols.length - 3] : \"\"\n if (!name || !/\\d/.test(phone)) continue\n const country = countryFromPhone(phone)\n out.push({\n name,\n source: \"wacli\",\n fields: {\n phone: `+${phone.replace(/\\D/g, \"\")}`,\n whatsapp: jid,\n ...(country ? { country } : {}),\n },\n })\n }\n return out\n}\n\nexport function createWacliSource(): FactSource {\n return {\n name: \"wacli\",\n provides: [\"contact value\", \"country\"],\n async available() {\n if (!(await binaryExists(\"wacli\"))) {\n return { kind: \"not-installed\", hint: \"brew install wacli — see https://wacli.sh\" }\n }\n // Installed but never authenticated returns an empty store for\n // every query, which looks identical to \"this person is not a\n // contact\" and would quietly teach us the corpus has no numbers.\n const { stdout, stderr, code } = await run(\"wacli\", [\"contacts\", \"search\", \"__agentx_probe__\"], { timeoutMs: 10_000 })\n if (code !== 0 && /auth|not logged in|no session|login/i.test(stdout + stderr)) {\n return { kind: \"not-configured\", hint: \"wacli auth — scan the QR to link the account\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n // Search the surname alone when the full name misses; the\n // contact store often holds a shorter form than the wiki does.\n for (const q of queriesFor(h.name)) {\n const { stdout, code } = await run(\"wacli\", [\"contacts\", \"search\", q], { signal, timeoutMs: 15_000 })\n if (code !== 0) continue\n const hit = parseContactsTable(stdout).filter((r) => plausible(r.name, h.name))\n if (hit.length === 0) continue\n for (const r of hit) {\n const key = r.fields.whatsapp\n if (seen.has(key)) continue\n seen.add(key)\n records.push({ ...r, fuzzy: !sameName(r.name, h.name) })\n }\n break\n }\n }\n return records\n },\n }\n}\n\nconst norm = (s: string) => s.toLowerCase().normalize(\"NFD\").replace(/[̀-ͯ]/g, \"\").replace(/[^a-z0-9 ]/g, \"\").trim()\nconst sameName = (a: string, b: string) => norm(a) === norm(b)\n\nfunction queriesFor(name: string): string[] {\n const parts = norm(name).split(/\\s+/).filter((p) => p.length > 2)\n return parts.length > 1 ? [name, parts[parts.length - 1]] : [name]\n}\n\n/**\n * A surname search returns everyone who shares it. Requiring every token\n * of the shorter name to appear in the longer one keeps a two-word wiki\n * name matching a contact stored under just the first name, while\n * rejecting an unrelated person who shares the surname.\n */\nexport function plausible(candidate: string, wanted: string): boolean {\n const a = norm(candidate).split(/\\s+/).filter(Boolean)\n const b = norm(wanted).split(/\\s+/).filter(Boolean)\n if (a.length === 0 || b.length === 0) return false\n const [short, long] = a.length <= b.length ? [a, b] : [b, a]\n return short.every((t) => long.includes(t))\n}\n","import type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Emails, handles and profile URLs, from the GitLab instance.\n//\n// Where most of a fleet's entries arrive through GitLab, this is the\n// system that knows who the people in them are. The user search returns\n// `organization` and `job_title` too, but both are optional and often\n// blank — the source reports what it has and stays quiet about the\n// rest, so a blank job title never reaches the prompt as a fact.\n//\n// Host and token come from the environment. There is no default host:\n// guessing one would send entity names from a private corpus to\n// whatever answers at that address.\n\nexport interface GitlabSourceOptions {\n baseUrl?: string\n token?: string\n}\n\ninterface GitlabUser {\n username?: string\n name?: string\n email?: string\n public_email?: string\n organization?: string\n job_title?: string\n web_url?: string\n state?: string\n}\n\nexport function createGitlabSource(opts: GitlabSourceOptions = {}): FactSource {\n const baseUrl = (opts.baseUrl ?? process.env.GITLAB_URL ?? \"\").replace(/\\/+$/, \"\")\n const token = opts.token ?? process.env.GITLAB_ADMIN_TOKEN ?? process.env.GITLAB_TOKEN\n\n return {\n name: \"gitlab\",\n provides: [\"email\", \"handle\", \"profile URL\"],\n async available() {\n if (!baseUrl) {\n return { kind: \"not-configured\", hint: \"export GITLAB_URL=https://<your-gitlab-host>\" }\n }\n if (!token) {\n return { kind: \"not-configured\", hint: \"export GITLAB_ADMIN_TOKEN=<PAT> (read_api scope is enough)\" }\n }\n // A present-but-rejected token is the dangerous case: every lookup\n // returns nothing, which is indistinguishable from \"this person is\n // not in GitLab\", and the corpus quietly grows a hole while the\n // source reports itself healthy. One authenticated call turns that\n // into a prompt.\n try {\n const res = await fetch(`${baseUrl}/api/v4/user`, { headers: { \"PRIVATE-TOKEN\": token } })\n if (res.status === 401 || res.status === 403) {\n return { kind: \"not-configured\", hint: `GitLab rejected the token (${res.status}) — set a valid GITLAB_ADMIN_TOKEN` }\n }\n if (!res.ok) {\n return { kind: \"failed\", hint: `GitLab returned ${res.status} for the auth probe` }\n }\n } catch (err) {\n return { kind: \"failed\", hint: `cannot reach ${baseUrl}: ${String((err as Error)?.message ?? err)}` }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n if (!token || !baseUrl) return []\n const records: FactRecord[] = []\n const seen = new Set<string>()\n for (const h of hints) {\n const url = `${baseUrl}/api/v4/users?search=${encodeURIComponent(h.name)}&per_page=5`\n let users: GitlabUser[]\n try {\n const res = await fetch(url, { headers: { \"PRIVATE-TOKEN\": token }, signal })\n if (!res.ok) continue\n users = (await res.json()) as GitlabUser[]\n } catch {\n continue\n }\n if (!Array.isArray(users)) continue\n for (const u of users) {\n const key = u.username ?? u.web_url ?? \"\"\n if (!key || seen.has(key)) continue\n seen.add(key)\n const fields: Record<string, string> = {}\n const email = u.email || u.public_email\n if (email) fields.email = email\n if (u.username) fields.gitlab = `@${u.username}`\n if (u.web_url) fields.profile = u.web_url\n // Blank strings are the instance's default, not a stated fact.\n if (u.organization) fields.organisation = u.organization\n if (u.job_title) fields.role = u.job_title\n if (u.state && u.state !== \"active\") fields.accountState = u.state\n if (Object.keys(fields).length === 0) continue\n records.push({\n name: u.name ?? h.name,\n source: \"gitlab\",\n fields,\n fuzzy: (u.name ?? \"\").toLowerCase() !== h.name.toLowerCase(),\n })\n }\n }\n return records\n },\n }\n}\n","import { binaryExists, run } from \"../exec\"\nimport type { EntityHint, FactRecord, FactSource } from \"../types\"\n\n// Contact cards, from Google Contacts via `gog`.\n//\n// On this install the People API is not enabled on the OAuth project and\n// every call returns 403 accessNotConfigured. That is the normal case\n// for a source, not an exception: `available()` reports false, the\n// resolver drops it, and the absorb runs with one fewer input. Enabling\n// the API turns it on with no code change.\n\ninterface GogContact {\n names?: Array<{ displayName?: string }>\n emailAddresses?: Array<{ value?: string }>\n phoneNumbers?: Array<{ value?: string }>\n organizations?: Array<{ name?: string; title?: string }>\n addresses?: Array<{ formattedValue?: string; country?: string }>\n}\n\nexport function createGogSource(): FactSource {\n return {\n name: \"gog\",\n provides: [\"contact value\", \"email\", \"organisation\", \"role\", \"country\"],\n async available() {\n if (!(await binaryExists(\"gog\"))) {\n return { kind: \"not-installed\", hint: \"brew install gog — Google CLI\" }\n }\n // A 403 for a disabled API is reported on stdout with exit 0, so\n // the exit code alone would call this source healthy. The probe\n // takes no flags beyond -j: an unknown flag makes gog print a\n // usage error instead of calling the API, and the probe then\n // passes while every real lookup fails.\n const { stdout, stderr } = await run(\"gog\", [\"contacts\", \"list\", \"-j\"], { timeoutMs: 20_000 })\n const out = stdout + stderr\n if (/unknown flag|Run with --help/i.test(out)) {\n return { kind: \"failed\", hint: `gog rejected the probe: ${out.split(\"\\n\")[0]}` }\n }\n if (/accessNotConfigured|has not been used in project/i.test(out)) {\n return {\n kind: \"not-configured\",\n hint: \"enable the People API on the gog OAuth project, then retry (console.developers.google.com → APIs → People API)\",\n }\n }\n if (/invalid_grant|PERMISSION_DENIED|unauthenticated/i.test(out)) {\n return { kind: \"not-configured\", hint: \"gog auth login — the stored token is expired or lacks contacts scope\" }\n }\n return null\n },\n async lookup(hints: EntityHint[], signal?: AbortSignal) {\n const records: FactRecord[] = []\n for (const h of hints) {\n const { stdout, code } = await run(\"gog\", [\"contacts\", \"search\", h.name, \"-j\", \"--results-only\"], { signal, timeoutMs: 20_000 })\n if (code !== 0) continue\n let parsed: unknown\n try { parsed = JSON.parse(stdout) } catch { continue }\n const list: GogContact[] = Array.isArray(parsed)\n ? (parsed as GogContact[])\n : ((parsed as { results?: unknown[]; people?: unknown[] })?.results as GogContact[])\n ?? ((parsed as { people?: unknown[] })?.people as GogContact[])\n ?? []\n for (const c of list) {\n const fields: Record<string, string> = {}\n const phone = c.phoneNumbers?.[0]?.value\n const email = c.emailAddresses?.[0]?.value\n const org = c.organizations?.[0]\n if (phone) fields.phone = phone\n if (email) fields.email = email\n if (org?.name) fields.organisation = org.name\n if (org?.title) fields.role = org.title\n const country = c.addresses?.[0]?.country\n if (country) fields.country = country\n if (Object.keys(fields).length === 0) continue\n records.push({ name: c.names?.[0]?.displayName ?? h.name, source: \"gog\", fields })\n }\n }\n return records\n },\n }\n}\n","import type { FactRecord } from \"../types\"\nimport { countryFromPhone } from \"./wacli\"\nimport { isAgentSender } from \"@/a2a/initiator\"\n\n// Identifiers the entries already carry.\n//\n// Every other source in this directory asks an outside system who\n// someone is. This one asks the batch, because since senders are\n// stamped at capture the platform's own identifier travels with the\n// message: a WhatsApp JID is the number, a GitLab sender is the handle.\n//\n// That makes it the best source available, not a fallback. It needs no\n// tool installed, no token, and no network — it works on a server with\n// none of the CLIs — and it cannot mismatch, because there is no name\n// resolution step to get wrong. `wacli` answers \"who is called Alex\n// Rivera\"; this answers \"who sent this message\", and only the second\n// question has one right answer.\n\nexport interface SenderStampedEntry {\n source?: string\n meta?: Record<string, unknown> | undefined\n}\n\nconst str = (v: unknown): string | undefined =>\n typeof v === \"string\" && v.trim() ? v.trim() : undefined\n\n/** \"whatsapp@peer-server\" and \"gitlab\" both normalise to their platform. */\nexport function platformOf(source?: string): string {\n return String(source ?? \"\").split(\"@\")[0].split(\":\")[0].toLowerCase()\n}\n\n/**\n * Turn stamped sender metadata into fact records.\n *\n * Deliberately conservative about what counts as a contact value. A\n * Telegram numeric user id identifies an account but cannot be dialled,\n * messaged by a human, or pasted anywhere useful, so it is recorded as\n * an account id and never as a way to reach someone — writing it into\n * an article's contact line would satisfy the grader while helping\n * nobody, which is the exact failure this whole layer exists to undo.\n */\nexport function recordsFromEntries(entries: SenderStampedEntry[]): FactRecord[] {\n const byName = new Map<string, FactRecord>()\n\n for (const e of entries) {\n const name = str(e.meta?.sender)\n if (!name) continue\n // An agent's post (\"agent:<id>\", even one made with a person's forge\n // account) says nothing about how to reach a person.\n if (isAgentSender(name)) continue\n const id = str(e.meta?.senderId)\n const username = str(e.meta?.senderUsername)\n const platform = platformOf(e.source)\n\n const fields: Record<string, string> = {}\n\n if (id && /@s\\.whatsapp\\.net$/.test(id)) {\n const digits = id.split(\"@\")[0].replace(/\\D/g, \"\")\n if (digits) {\n fields.phone = `+${digits}`\n fields.whatsapp = id\n const country = countryFromPhone(digits)\n if (country) fields.country = country\n }\n } else if (platform === \"whatsapp\" && id && /^\\d{6,}$/.test(id)) {\n fields.phone = `+${id}`\n fields.whatsapp = `${id}@s.whatsapp.net`\n const country = countryFromPhone(id)\n if (country) fields.country = country\n }\n\n if (username) {\n const handle = username.startsWith(\"@\") ? username : `@${username}`\n if (platform === \"gitlab\") fields.gitlab = handle\n else if (platform === \"github\") fields.github = handle\n else if (platform === \"telegram\") fields.telegram = handle\n else fields.handle = handle\n }\n\n // An account id is provenance, not a contact value.\n if (id && !fields.phone && !username) fields[`${platform || \"platform\"}Id`] = id\n\n if (Object.keys(fields).length === 0) continue\n\n const key = name.toLowerCase()\n const existing = byName.get(key)\n if (!existing) {\n byName.set(key, { name, source: \"entries\", fields })\n continue\n }\n // Same person across several entries — union the identifiers rather\n // than letting the last message win.\n for (const [k, v] of Object.entries(fields)) existing.fields[k] ??= v\n }\n\n return Array.from(byName.values())\n}\n","import { createContactsSource } from \"./sources/contacts\"\nimport { createGitlabSource } from \"./sources/gitlab\"\nimport { createGogSource } from \"./sources/gog\"\nimport { createWacliSource } from \"./sources/wacli\"\nimport type { EntityHint, FactRecord, FactSource, FactSourceResult, Unavailable } from \"./types\"\n\nexport * from \"./types\"\nexport { countryFromPhone, parseContactsTable, plausible } from \"./sources/wacli\"\nexport { createGitlabSource } from \"./sources/gitlab\"\nexport { createGogSource } from \"./sources/gog\"\nexport { createWacliSource } from \"./sources/wacli\"\nexport { platformOf, recordsFromEntries } from \"./sources/entries\"\nexport { createContactsSource, factsFrom, loadContacts, namesOf } from \"./sources/contacts\"\nexport type { ContactRecord } from \"./sources/contacts\"\nexport type { SenderStampedEntry } from \"./sources/entries\"\n\nexport interface ResolveOptions {\n sources?: FactSource[]\n /** Whole-resolve budget. A slow address book must not stall an absorb. */\n timeoutMs?: number\n /** Cap on entities looked up per batch — each one is N network calls. */\n maxEntities?: number\n onResult?: (r: FactSourceResult) => void\n}\n\n/**\n * Probe each source once per process, not once per lookup.\n *\n * Availability does not change mid-run, but the probes are real work —\n * gog's costs about 1.4s because it has to make an API call to\n * distinguish \"installed\" from \"installed but the API is disabled\".\n * Backfilling 50 articles re-ran every probe 50 times and spent longer\n * asking whether the sources worked than using them.\n *\n * The promise is cached, not the result, so concurrent callers share one\n * probe rather than racing.\n */\nexport function memoizeAvailability(source: FactSource): FactSource {\n let probe: Promise<Unavailable | null> | undefined\n return {\n ...source,\n available: () => (probe ??= source.available()),\n lookup: (hints, signal) => source.lookup(hints, signal),\n }\n}\n\n/**\n * Ordered by authority, because mergeRecords lets the first source to\n * state a field win.\n *\n * The hand-maintained registry comes first: it is the only source where\n * a person decided that a name, its aliases and a set of handles all\n * refer to one human. Directories only know their own corner, and they\n * cannot resolve an alias at all.\n */\nexport function defaultSources(): FactSource[] {\n return [\n createContactsSource(),\n createWacliSource(),\n createGitlabSource(),\n createGogSource(),\n ].map(memoizeAvailability)\n}\n\n/**\n * Names worth a lookup, taken from the batch.\n *\n * Only entities the batch already mentions are ever queried. That is a\n * deliberate limit and not just an efficiency one: exporting the address\n * book into a prompt would put identifiers for people who have nothing\n * to do with the work into a model's context. A lookup is justified by\n * the entry that names the person.\n */\nexport function extractHints(\n entries: Array<{ context?: string; content?: string; sender?: string }>,\n opts: { max?: number; known?: string[] } = {},\n): EntityHint[] {\n const max = opts.max ?? 25\n const byName = new Map<string, EntityHint>()\n\n // The stamped sender first: it is the platform's own record of who\n // spoke, so it beats both a heuristic over `context` and a substring\n // scan of the body. Entries captured before senders were recorded\n // simply have none, and fall through to the other two.\n for (const e of entries) {\n const s = (e.sender ?? \"\").trim()\n if (s && isPersonName(s)) byName.set(s.toLowerCase(), { name: s, origin: \"sender\", type: \"person\" })\n }\n\n for (const e of entries) {\n const ctx = (e.context ?? \"\").trim()\n if (!isPersonName(ctx)) continue\n const key = ctx.toLowerCase()\n if (byName.has(key)) continue\n byName.set(key, { name: ctx, origin: \"context\" })\n }\n\n // `context` only names a person for one-to-one channels. On a GitLab\n // entry it is the issue title, and in a group chat it is the group —\n // so the people who talk in groups, which is most of them, were never\n // looked up at all. The first article written with this layer live\n // said \"Contact identifiers: unknown … no number is recorded\" about\n // someone the contact store knew perfectly well.\n //\n // The bodies do name them, but harvesting capitalised word pairs out\n // of free text would spend lookups on noise and, worse, resolve\n // strangers. So the corpus is its own dictionary: a name is a hint\n // only if the wiki already has a person article for it. That is\n // precise by construction, and it targets exactly the articles a\n // second pass is going to rewrite.\n const known = (opts.known ?? []).filter((n) => n.trim().length > 2)\n if (known.length > 0) {\n const haystack = entries.map((e) => e.content ?? \"\").join(\"\\n\").toLowerCase()\n for (const name of known) {\n const key = name.toLowerCase().trim()\n if (byName.has(key)) continue\n if (haystack.includes(key)) byName.set(key, { name, origin: \"body\", type: \"person\" })\n }\n }\n\n return Array.from(byName.values()).slice(0, max)\n}\n\nconst NOT_A_PERSON = new Set([\n \"me\", \"user\", \"system\", \"cron\", \"unknown\", \"anonymous\", \"bot\", \"agent\",\n \"self\", \"test\", \"admin\", \"none\", \"null\", \"n/a\",\n])\n\n/**\n * Words that make a capitalised phrase a collection rather than a person.\n *\n * A group chat's `context` is its name, and plenty of group names are\n * shaped exactly like a person's — \"Team Group\", \"Acme Family\". Shape\n * alone cannot separate them, and treating one as a person spends a\n * lookup and risks matching a real contact with a similar name.\n */\nconst COLLECTION_NOUNS = new Set([\n \"group\", \"team\", \"chat\", \"channel\", \"squad\", \"crew\", \"room\", \"family\",\n \"project\", \"board\", \"committee\", \"club\", \"staff\", \"office\", \"dept\",\n \"department\", \"support\", \"sales\", \"ops\", \"admins\", \"everyone\", \"all\",\n])\n\n/**\n * Two to four capitalised words, no digits, not a known placeholder.\n *\n * `context` holds a person's name for chat sources and an issue title\n * for GitLab ones, and issue titles are long and full of punctuation.\n * The bar is deliberately high: a false positive costs a wasted lookup\n * and, worse, risks putting an unrelated person's identifiers into the\n * prompt, so a missed name is the cheaper error.\n */\nexport function isPersonName(s: string): boolean {\n const t = s.trim()\n if (!t || t.length > 48) return false\n if (NOT_A_PERSON.has(t.toLowerCase())) return false\n if (/[\\d@/\\\\#:|_]/.test(t)) return false\n const words = t.split(/\\s+/)\n if (words.length < 2 || words.length > 4) return false\n if (words.some((w) => COLLECTION_NOUNS.has(w.toLowerCase()))) return false\n return words.every((w) => /^[\\p{Lu}][\\p{L}'’.-]*$/u.test(w))\n}\n\nexport async function resolveFacts(\n hints: EntityHint[],\n opts: ResolveOptions = {},\n): Promise<{ records: FactRecord[]; results: FactSourceResult[] }> {\n const sources = opts.sources ?? defaultSources()\n const picked = hints.slice(0, opts.maxEntities ?? 25)\n if (picked.length === 0) return { records: [], results: [] }\n\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? 120_000)\n try {\n const results = await Promise.all(sources.map(async (s): Promise<FactSourceResult> => {\n const t0 = Date.now()\n try {\n const why = await s.available()\n if (why) return { source: s.name, records: [], unavailable: why, ms: Date.now() - t0 }\n const records = await s.lookup(picked, ac.signal)\n return { source: s.name, records, ms: Date.now() - t0 }\n } catch (err) {\n // A source that throws contributes nothing and blocks nothing.\n return {\n source: s.name,\n records: [],\n unavailable: { kind: \"failed\", hint: String((err as Error)?.message ?? err) },\n ms: Date.now() - t0,\n }\n }\n }))\n for (const r of results) opts.onResult?.(r)\n return { records: results.flatMap((r) => r.records), results }\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * What to tell the operator about the sources that did not answer.\n *\n * A source silently contributing nothing is the worst outcome: the\n * corpus quietly develops a hole shaped like the missing tool, and the\n * grader reports the resulting gaps as though the fact did not exist\n * anywhere. Installing `wacli` is a one-line fix that nobody makes if\n * nobody is told. `failed` is left out — a transient error is noise, not\n * a task.\n */\nexport function installPrompts(\n results: FactSourceResult[],\n sources: FactSource[] = defaultSources(),\n): Array<{ source: string; kind: string; hint: string; provides: string[] }> {\n const provides = new Map(sources.map((s) => [s.name, s.provides]))\n return results\n .filter((r) => r.unavailable && r.unavailable.kind !== \"failed\")\n .map((r) => ({\n source: r.source,\n kind: r.unavailable!.kind,\n hint: r.unavailable!.hint,\n provides: provides.get(r.source) ?? [],\n }))\n}\n\nexport interface MergedEntity {\n name: string\n /** field → value, with the source that supplied it. */\n fields: Record<string, { value: string; source: string }>\n}\n\n/**\n * Merge per entity, first source to state a field wins.\n *\n * Order is the source order, which puts WhatsApp's number ahead of\n * Google's. That is intentional rather than arbitrary: the WhatsApp\n * number is the one the agent will actually message on, so where the two\n * disagree the messaging channel's own record is the operative fact.\n * Conflicts are kept and rendered, never silently resolved.\n */\nexport function mergeRecords(records: FactRecord[]): MergedEntity[] {\n const out = new Map<string, MergedEntity>()\n for (const r of records) {\n const key = r.name.toLowerCase().trim()\n let e = out.get(key)\n if (!e) { e = { name: r.name, fields: {} }; out.set(key, e) }\n for (const [k, v] of Object.entries(r.fields)) {\n if (!v?.trim()) continue\n const existing = e.fields[k]\n if (!existing) { e.fields[k] = { value: v, source: r.source }; continue }\n if (existing.value !== v) {\n // Two systems of record disagree. The writer should see both.\n e.fields[`${k} (${r.source})`] ??= { value: v, source: r.source }\n }\n }\n }\n return Array.from(out.values())\n}\n\n/**\n * The prompt block.\n *\n * Phrased as an instruction to copy rather than as context to consider.\n * Absorb's whole disposition is to summarise, and an identifier\n * summarised is an identifier lost — which is the failure this exists\n * to fix.\n */\nexport function renderFactsBlock(entities: MergedEntity[]): string {\n if (entities.length === 0) return \"\"\n const lines = entities\n .filter((e) => Object.keys(e.fields).length > 0)\n .map((e) => {\n const fields = Object.entries(e.fields)\n .map(([k, v]) => ` - ${k}: \\`${v.value}\\` _(${v.source})_`)\n .join(\"\\n\")\n return `- **${e.name}**\\n${fields}`\n })\n if (lines.length === 0) return \"\"\n return `\n## Verified facts\n\nThese were read from systems of record — WhatsApp, GitLab, Google, the\nERP — not from the entries. They are more reliable than anything the\nconversation implies, and they are the identity fields articles are\ngraded on.\n\nCopy every value that belongs to an article you write, **verbatim**, into\nits Identity section. Do not paraphrase an identifier, reformat it, or\nreplace it with the name of the channel it belongs to. Where a fact here\ncontradicts the entries, this wins and the entry is stale.\n\n${lines.join(\"\\n\")}\n`\n}\n"],"mappings":"kFAAA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,KACzC,OAAS,WAAAC,MAAe,OCQxB,IAAMC,EAA8B,CAClC,CAAC,MAAO,SAAS,EAAG,CAAC,MAAO,cAAc,EAAG,CAAC,MAAO,KAAK,EAAG,CAAC,MAAO,OAAO,EAC5E,CAAC,MAAO,QAAQ,E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["existsSync","readFileSync","resolve","CC","countryFromPhone","phone","d","best","bestLen","code","name","parseContactsTable","stdout","out","line","t","cols","jid","country","createWacliSource","binaryExists","stderr","run","hints","signal","records","seen","h","q","queriesFor","hit","r","plausible","key","sameName","norm","s","a","b","parts","p","candidate","wanted","short","long","CHANNEL_FIELDS","contactsPath","agentxDir","resolve","loadContacts","path","existsSync","parsed","readFileSync","norm","s","namesOf","c","x","factsFrom","fields","key","raw","value","field","digits","country","countryFromPhone","createContactsSource","opts","hints","contacts","index","n","out","seen","h","createGitlabSource","opts","baseUrl","token","res","err","hints","signal","records","seen","h","url","users","u","key","fields","email","createGogSource","binaryExists","stdout","stderr","run","out","hints","signal","records","h","code","parsed","list","c","fields","phone","email","org","country","str","v","platformOf","source","recordsFromEntries","entries","byName","e","name","isAgentSender","id","username","platform","fields","digits","country","countryFromPhone","handle","key","existing","k","memoizeAvailability","source","probe","hints","signal","defaultSources","createContactsSource","createWacliSource","createGitlabSource","createGogSource","extractHints","entries","opts","max","byName","e","s","isPersonName","ctx","key","known","n","haystack","name","NOT_A_PERSON","COLLECTION_NOUNS","words","w","resolveFacts","sources","picked","ac","timer","results","t0","why","records","err","r","installPrompts","provides","mergeRecords","out","k","v","existing","renderFactsBlock","entities","lines","fields"]}