agentix-cli 0.125.1 → 0.126.2
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.
- package/dist/absorb-eval-5Y5IZWW2.js +2 -0
- package/dist/{agent-YJFWFQ6A.js → agent-WJTYM5HR.js} +2 -2
- package/dist/{board-dashboard-SPYYHH54.js → board-dashboard-DQR2OSV7.js} +2 -2
- package/dist/{board-dashboard-SPYYHH54.js.map → board-dashboard-DQR2OSV7.js.map} +1 -1
- package/dist/{chunk-NW7RVE57.js → chunk-2C3X6DVD.js} +2 -2
- package/dist/chunk-2W3X6H7Z.js +51 -0
- package/dist/chunk-2W3X6H7Z.js.map +1 -0
- package/dist/chunk-3PGPN323.js +2 -0
- package/dist/chunk-3PGPN323.js.map +1 -0
- package/dist/{chunk-CECHWYJ2.js → chunk-4VVHGR7H.js} +1 -1
- package/dist/chunk-4VVHGR7H.js.map +1 -0
- package/dist/{chunk-UOAJWNRF.js → chunk-D6SWAB5J.js} +6 -6
- package/dist/chunk-EO4DEEXL.js +2 -0
- package/dist/chunk-EO4DEEXL.js.map +1 -0
- package/dist/{chunk-INLKJEEN.js → chunk-FVG2BADS.js} +2 -2
- package/dist/{chunk-YKYMGIQ5.js → chunk-GUQDPA6R.js} +2 -2
- package/dist/{chunk-5RE2B5YQ.js → chunk-JIXNSA67.js} +2 -2
- package/dist/{chunk-BN5QMNON.js → chunk-JUIL2EW3.js} +2 -2
- package/dist/{chunk-ITATBKUL.js → chunk-LVV7JBHM.js} +2 -2
- package/dist/{chunk-FX3D7YON.js → chunk-MCI3DIWW.js} +2 -2
- package/dist/{chunk-4WKBK7EQ.js → chunk-O4XEQTEN.js} +2 -2
- package/dist/chunk-QX2B4TJU.js +3 -0
- package/dist/chunk-QX2B4TJU.js.map +1 -0
- package/dist/{chunk-IS4DA5CR.js → chunk-UUVFH7BO.js} +4 -4
- package/dist/chunk-UUVFH7BO.js.map +1 -0
- package/dist/{chunk-VHT7HESZ.js → chunk-VXKNB4AW.js} +2 -2
- package/dist/{chunk-5VWOK3GQ.js → chunk-WUDVBPQV.js} +2 -2
- package/dist/{chunk-WX47PYHL.js → chunk-YNA5T43U.js} +2 -2
- package/dist/chunk-Z7XXUYBB.js +894 -0
- package/dist/chunk-Z7XXUYBB.js.map +1 -0
- package/dist/chunk-ZQWWMAMJ.js +105 -0
- package/dist/chunk-ZQWWMAMJ.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{context-planner-BKHPKDX5.js → context-planner-3JDA7FNR.js} +2 -2
- package/dist/extract-json-7775Q7KO.js +2 -0
- package/dist/graph-5ZJ7YACP.js +2 -0
- package/dist/hub-53YQQCVA.js +2 -0
- package/dist/index.d.ts +45 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/load-NK3MIYXP.js +2 -0
- package/dist/{program-JNRKGK3U.js → program-LGCT7FFJ.js} +260 -271
- package/dist/program-LGCT7FFJ.js.map +1 -0
- package/dist/promote-MQYJMGGZ.js +2 -0
- package/dist/push-bridge-325SXDGN.js +1 -1
- package/dist/{query-RV6SHTRN.js → query-DNJONEKC.js} +2 -2
- package/dist/registry-5A3SLBVJ.js +2 -0
- package/dist/registry-5A3SLBVJ.js.map +1 -0
- package/dist/{request-planner-2G73AJ4S.js → request-planner-XYHM26CO.js} +2 -2
- package/dist/{review-candidates-S34UICQD.js → review-candidates-XRBAMRBH.js} +2 -2
- package/dist/{routing-K2LAUFRL.js → routing-OMIWZKNC.js} +2 -2
- package/dist/routing-OMIWZKNC.js.map +1 -0
- package/dist/{seat-ZJT5T2NO.js → seat-LKBZ6SDS.js} +2 -2
- package/dist/seat-LKBZ6SDS.js.map +1 -0
- package/dist/{select-Y23SKHCJ.js → select-BSC3TFMZ.js} +2 -2
- package/dist/types-ROL44T62.js +2 -0
- package/dist/types-ROL44T62.js.map +1 -0
- package/dist/wiki-BT3H2WCD.js +2 -0
- package/dist/wiki-BT3H2WCD.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-BFCNSZHN.js +0 -745
- package/dist/chunk-BFCNSZHN.js.map +0 -1
- package/dist/chunk-CECHWYJ2.js.map +0 -1
- package/dist/chunk-IS4DA5CR.js.map +0 -1
- package/dist/chunk-XSDUORMZ.js +0 -105
- package/dist/chunk-XSDUORMZ.js.map +0 -1
- package/dist/program-JNRKGK3U.js.map +0 -1
- package/dist/promote-GXZ7BLVG.js +0 -2
- package/dist/registry-PPJO5I6J.js +0 -2
- package/dist/types-NZOBHQGS.js +0 -2
- package/dist/wiki-WJM5XNFS.js +0 -2
- /package/dist/{agent-YJFWFQ6A.js.map → absorb-eval-5Y5IZWW2.js.map} +0 -0
- /package/dist/{promote-GXZ7BLVG.js.map → agent-WJTYM5HR.js.map} +0 -0
- /package/dist/{chunk-NW7RVE57.js.map → chunk-2C3X6DVD.js.map} +0 -0
- /package/dist/{chunk-UOAJWNRF.js.map → chunk-D6SWAB5J.js.map} +0 -0
- /package/dist/{chunk-INLKJEEN.js.map → chunk-FVG2BADS.js.map} +0 -0
- /package/dist/{chunk-YKYMGIQ5.js.map → chunk-GUQDPA6R.js.map} +0 -0
- /package/dist/{chunk-5RE2B5YQ.js.map → chunk-JIXNSA67.js.map} +0 -0
- /package/dist/{chunk-BN5QMNON.js.map → chunk-JUIL2EW3.js.map} +0 -0
- /package/dist/{chunk-ITATBKUL.js.map → chunk-LVV7JBHM.js.map} +0 -0
- /package/dist/{chunk-FX3D7YON.js.map → chunk-MCI3DIWW.js.map} +0 -0
- /package/dist/{chunk-4WKBK7EQ.js.map → chunk-O4XEQTEN.js.map} +0 -0
- /package/dist/{chunk-VHT7HESZ.js.map → chunk-VXKNB4AW.js.map} +0 -0
- /package/dist/{chunk-5VWOK3GQ.js.map → chunk-WUDVBPQV.js.map} +0 -0
- /package/dist/{chunk-WX47PYHL.js.map → chunk-YNA5T43U.js.map} +0 -0
- /package/dist/{context-planner-BKHPKDX5.js.map → context-planner-3JDA7FNR.js.map} +0 -0
- /package/dist/{query-RV6SHTRN.js.map → extract-json-7775Q7KO.js.map} +0 -0
- /package/dist/{registry-PPJO5I6J.js.map → graph-5ZJ7YACP.js.map} +0 -0
- /package/dist/{routing-K2LAUFRL.js.map → hub-53YQQCVA.js.map} +0 -0
- /package/dist/{seat-ZJT5T2NO.js.map → load-NK3MIYXP.js.map} +0 -0
- /package/dist/{types-NZOBHQGS.js.map → promote-MQYJMGGZ.js.map} +0 -0
- /package/dist/{wiki-WJM5XNFS.js.map → query-DNJONEKC.js.map} +0 -0
- /package/dist/{request-planner-2G73AJ4S.js.map → request-planner-XYHM26CO.js.map} +0 -0
- /package/dist/{review-candidates-S34UICQD.js.map → review-candidates-XRBAMRBH.js.map} +0 -0
- /package/dist/{select-Y23SKHCJ.js.map → select-BSC3TFMZ.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-BN5QMNON.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-FX3D7YON.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
1
|
+
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-JUIL2EW3.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
5
|
`),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-VXKNB4AW.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-5A3SLBVJ.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-WUDVBPQV.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as c}from"./chunk-
|
|
1
|
+
import{a as c}from"./chunk-ZQWWMAMJ.js";import{resolve as a}from"path";import{existsSync as h,readdirSync as y,mkdirSync as l,readFileSync as u,writeFileSync as p,renameSync as f}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=a(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=a(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new c(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=a(this.agentsDir,e,this.mode),i=new c(t,this.log);return this.agentStores.set(r,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(h(this.agentsDir))for(let t of y(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let i=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let s of r)g.entries[s]={at:d,cited:i.has(s)};let n=this.ledgerPath(e);l(a(n,".."),{recursive:!0});let o=`${n}.tmp`;p(o,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),f(o,n)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let i=r.get(t.agentId);i?i.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:i,cited:g,read:d,pending:n,articles:o}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:i.length,totalArticles:o.length,cited:g.length,readNotCited:d.length,unabsorbed:n.length,articles:o}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,i=new Set;for(let s of t)if(s.sources)for(let S of s.sources)i.add(S);let g=this.readLedger(e).entries,d=[],n=[],o=[];for(let s of r)i.has(s.id)?d.push(s):g[s.id]?n.push(s):o.push(s);return{all:r,cited:d,read:n,pending:o,articles:t}}syncedFrom(e){let r=a(this.agentsDir,e,"_synced.json");if(!h(r))return null;try{return JSON.parse(u(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=a(this.agentsDir,e,"_synced.json");l(a(t,".."),{recursive:!0});let i=`${t}.tmp`;p(i,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),f(i,t)}ledgerPath(e){return a(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!h(r))return{entries:{}};try{return{entries:JSON.parse(u(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-YNA5T43U.js.map
|