agentix-cli 0.152.0 → 0.153.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.
- package/dist/{App-NCB3Y5DS.js → App-2SWSYFED.js} +2 -2
- package/dist/{ChatApp-HOWN5H7Y.js → ChatApp-NYTNFLIB.js} +2 -2
- package/dist/{absorb-eval-JXRNSZII.js → absorb-eval-SYX5QN4H.js} +2 -2
- package/dist/{agent-DMXUUMEU.js → agent-UCYQELAQ.js} +2 -2
- package/dist/{board-dashboard-POWARL34.js → board-dashboard-OZJSS6EM.js} +8 -5
- package/dist/{board-dashboard-POWARL34.js.map → board-dashboard-OZJSS6EM.js.map} +1 -1
- package/dist/{chunk-QSNKF5VD.js → chunk-2J2OES2S.js} +2 -2
- package/dist/{chunk-HS7ATV4Z.js → chunk-3LU2ZQZJ.js} +2 -2
- package/dist/{chunk-CZEBLLZQ.js → chunk-3OPW64OM.js} +2 -2
- package/dist/{chunk-MTBY46CL.js → chunk-5DPN2HIR.js} +5 -5
- package/dist/{chunk-SQUTRMKH.js → chunk-5VPU5FHB.js} +7 -7
- package/dist/{chunk-SQUTRMKH.js.map → chunk-5VPU5FHB.js.map} +1 -1
- package/dist/{chunk-XE3CGJV4.js → chunk-BFONYVOM.js} +2 -2
- package/dist/{chunk-PC24JMEH.js → chunk-CFPRIE6F.js} +2 -2
- package/dist/{chunk-JHAQE46R.js → chunk-D6U37WO3.js} +18 -18
- package/dist/chunk-D6U37WO3.js.map +1 -0
- package/dist/{chunk-P25TJ4XN.js → chunk-DPSHY7GN.js} +3 -3
- package/dist/{chunk-PGLTBNGZ.js → chunk-FVRREIVV.js} +2 -2
- package/dist/{chunk-7UH3DXAG.js → chunk-GDLO7FC7.js} +2 -2
- package/dist/{chunk-RNAKP7WY.js → chunk-HVNWI63Z.js} +2 -2
- package/dist/{chunk-TNZBQAUR.js → chunk-I45WFYGM.js} +2 -2
- package/dist/{chunk-P4EZJIQ4.js → chunk-IJQ2UUMZ.js} +282 -266
- package/dist/chunk-IJQ2UUMZ.js.map +1 -0
- package/dist/{chunk-YJZQRFET.js → chunk-JPZBWHNZ.js} +2 -2
- package/dist/{chunk-GI5CY27P.js → chunk-LH3GOBZP.js} +2 -2
- package/dist/{chunk-YBUCVI45.js → chunk-MM3ABEOW.js} +2 -2
- package/dist/chunk-MOCDP7Q3.js +36 -0
- package/dist/chunk-MOCDP7Q3.js.map +1 -0
- package/dist/{chunk-E4V5EADX.js → chunk-MWYPW5XP.js} +2 -2
- package/dist/{chunk-JDX7AYIB.js → chunk-P24P43ZB.js} +2 -2
- package/dist/{chunk-LOTCKF22.js → chunk-RJCHFDF3.js} +2 -2
- package/dist/{chunk-DZUJP6L7.js → chunk-RUQMUDSX.js} +2 -2
- package/dist/{chunk-UFYKUC4E.js → chunk-S5FRIHWM.js} +2 -2
- package/dist/{chunk-ADG6NBZY.js → chunk-SW6HCRLU.js} +4 -4
- package/dist/chunk-SW6HCRLU.js.map +1 -0
- package/dist/{chunk-ILZRO6SN.js → chunk-UUVJX6WD.js} +2 -2
- package/dist/{chunk-LDLRDBAD.js → chunk-Z2KGUEB6.js} +2 -2
- package/dist/{chunk-VIZVF6KH.js → chunk-ZQONMM3B.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-6IOWB5AT.js → client-PBIUMGDL.js} +2 -2
- package/dist/{config-SHIT5WJE.js → config-VLH5DJTH.js} +2 -2
- package/dist/{config-mutate-6ACI5COM.js → config-mutate-G7HW2R6H.js} +2 -2
- package/dist/config-mutator-XWWW3PSV.js +2 -0
- package/dist/{contributions-N7K6LNL7.js → contributions-GZVKJXSJ.js} +2 -2
- package/dist/{doctor-T7QAQRCJ.js → doctor-UT32WKCP.js} +2 -2
- package/dist/{follow-up-tool-HQ2GWF4K.js → follow-up-tool-PTKDMFA7.js} +2 -2
- package/dist/{hub-53IMEYGX.js → hub-BHCBRQZP.js} +2 -2
- package/dist/index.d.ts +217 -2
- package/dist/index.js +1 -1
- package/dist/{program-LSXONKPW.js → program-NU6QIXJJ.js} +192 -192
- package/dist/program-NU6QIXJJ.js.map +1 -0
- package/dist/{promote-626PE5VM.js → promote-73ZGTRDV.js} +2 -2
- package/dist/{query-GR3SOD6A.js → query-KHW4AERR.js} +2 -2
- package/dist/{query-settings-6XZHNFXE.js → query-settings-P6RUUEFO.js} +2 -2
- package/dist/{registry-SAY7ROZV.js → registry-RQBXAPUZ.js} +2 -2
- package/dist/{request-planner-DWYXUVF4.js → request-planner-EUIMJ7R3.js} +2 -2
- package/dist/{review-candidates-GXWMKZKA.js → review-candidates-KKGDAZIB.js} +2 -2
- package/dist/{routing-TB6BBRH4.js → routing-FQNGOTMV.js} +2 -2
- package/dist/schedule-tool-2OWGAK4H.js +2 -0
- package/dist/{scheduler-VOZIMG5F.js → scheduler-JXZBVPOS.js} +2 -2
- package/dist/{seat-H6F6H55Y.js → seat-DZB3NSZ7.js} +2 -2
- package/dist/{select-OUBL6EMZ.js → select-YD4CA7FP.js} +2 -2
- package/dist/{set-enabled-NYJHFXHY.js → set-enabled-UK4SE5MZ.js} +2 -2
- package/dist/{tool-FWATXW5Q.js → tool-2PA2USUG.js} +2 -2
- package/dist/{tool-HXFGNBLS.js → tool-DIJN4XBY.js} +2 -2
- package/dist/{wiki-PG5ZBOMH.js → wiki-CQBXLZ2Y.js} +2 -2
- package/dist/wiki-enrich-PA6JS2YN.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-ADG6NBZY.js.map +0 -1
- package/dist/chunk-JHAQE46R.js.map +0 -1
- package/dist/chunk-JJOLZPUY.js +0 -35
- package/dist/chunk-JJOLZPUY.js.map +0 -1
- package/dist/chunk-P4EZJIQ4.js.map +0 -1
- package/dist/config-mutator-LAEX6HOH.js +0 -2
- package/dist/program-LSXONKPW.js.map +0 -1
- package/dist/schedule-tool-EI2SRMZM.js +0 -2
- package/dist/wiki-enrich-BIQZWJRB.js +0 -2
- /package/dist/{App-NCB3Y5DS.js.map → App-2SWSYFED.js.map} +0 -0
- /package/dist/{ChatApp-HOWN5H7Y.js.map → ChatApp-NYTNFLIB.js.map} +0 -0
- /package/dist/{absorb-eval-JXRNSZII.js.map → absorb-eval-SYX5QN4H.js.map} +0 -0
- /package/dist/{agent-DMXUUMEU.js.map → agent-UCYQELAQ.js.map} +0 -0
- /package/dist/{chunk-QSNKF5VD.js.map → chunk-2J2OES2S.js.map} +0 -0
- /package/dist/{chunk-HS7ATV4Z.js.map → chunk-3LU2ZQZJ.js.map} +0 -0
- /package/dist/{chunk-CZEBLLZQ.js.map → chunk-3OPW64OM.js.map} +0 -0
- /package/dist/{chunk-MTBY46CL.js.map → chunk-5DPN2HIR.js.map} +0 -0
- /package/dist/{chunk-XE3CGJV4.js.map → chunk-BFONYVOM.js.map} +0 -0
- /package/dist/{chunk-PC24JMEH.js.map → chunk-CFPRIE6F.js.map} +0 -0
- /package/dist/{chunk-P25TJ4XN.js.map → chunk-DPSHY7GN.js.map} +0 -0
- /package/dist/{chunk-PGLTBNGZ.js.map → chunk-FVRREIVV.js.map} +0 -0
- /package/dist/{chunk-7UH3DXAG.js.map → chunk-GDLO7FC7.js.map} +0 -0
- /package/dist/{chunk-RNAKP7WY.js.map → chunk-HVNWI63Z.js.map} +0 -0
- /package/dist/{chunk-TNZBQAUR.js.map → chunk-I45WFYGM.js.map} +0 -0
- /package/dist/{chunk-YJZQRFET.js.map → chunk-JPZBWHNZ.js.map} +0 -0
- /package/dist/{chunk-GI5CY27P.js.map → chunk-LH3GOBZP.js.map} +0 -0
- /package/dist/{chunk-YBUCVI45.js.map → chunk-MM3ABEOW.js.map} +0 -0
- /package/dist/{chunk-E4V5EADX.js.map → chunk-MWYPW5XP.js.map} +0 -0
- /package/dist/{chunk-JDX7AYIB.js.map → chunk-P24P43ZB.js.map} +0 -0
- /package/dist/{chunk-LOTCKF22.js.map → chunk-RJCHFDF3.js.map} +0 -0
- /package/dist/{chunk-DZUJP6L7.js.map → chunk-RUQMUDSX.js.map} +0 -0
- /package/dist/{chunk-UFYKUC4E.js.map → chunk-S5FRIHWM.js.map} +0 -0
- /package/dist/{chunk-ILZRO6SN.js.map → chunk-UUVJX6WD.js.map} +0 -0
- /package/dist/{chunk-LDLRDBAD.js.map → chunk-Z2KGUEB6.js.map} +0 -0
- /package/dist/{chunk-VIZVF6KH.js.map → chunk-ZQONMM3B.js.map} +0 -0
- /package/dist/{client-6IOWB5AT.js.map → client-PBIUMGDL.js.map} +0 -0
- /package/dist/{config-SHIT5WJE.js.map → config-VLH5DJTH.js.map} +0 -0
- /package/dist/{config-mutate-6ACI5COM.js.map → config-mutate-G7HW2R6H.js.map} +0 -0
- /package/dist/{config-mutator-LAEX6HOH.js.map → config-mutator-XWWW3PSV.js.map} +0 -0
- /package/dist/{contributions-N7K6LNL7.js.map → contributions-GZVKJXSJ.js.map} +0 -0
- /package/dist/{doctor-T7QAQRCJ.js.map → doctor-UT32WKCP.js.map} +0 -0
- /package/dist/{follow-up-tool-HQ2GWF4K.js.map → follow-up-tool-PTKDMFA7.js.map} +0 -0
- /package/dist/{hub-53IMEYGX.js.map → hub-BHCBRQZP.js.map} +0 -0
- /package/dist/{promote-626PE5VM.js.map → promote-73ZGTRDV.js.map} +0 -0
- /package/dist/{query-GR3SOD6A.js.map → query-KHW4AERR.js.map} +0 -0
- /package/dist/{query-settings-6XZHNFXE.js.map → query-settings-P6RUUEFO.js.map} +0 -0
- /package/dist/{registry-SAY7ROZV.js.map → registry-RQBXAPUZ.js.map} +0 -0
- /package/dist/{request-planner-DWYXUVF4.js.map → request-planner-EUIMJ7R3.js.map} +0 -0
- /package/dist/{review-candidates-GXWMKZKA.js.map → review-candidates-KKGDAZIB.js.map} +0 -0
- /package/dist/{routing-TB6BBRH4.js.map → routing-FQNGOTMV.js.map} +0 -0
- /package/dist/{schedule-tool-EI2SRMZM.js.map → schedule-tool-2OWGAK4H.js.map} +0 -0
- /package/dist/{scheduler-VOZIMG5F.js.map → scheduler-JXZBVPOS.js.map} +0 -0
- /package/dist/{seat-H6F6H55Y.js.map → seat-DZB3NSZ7.js.map} +0 -0
- /package/dist/{select-OUBL6EMZ.js.map → select-YD4CA7FP.js.map} +0 -0
- /package/dist/{set-enabled-NYJHFXHY.js.map → set-enabled-UK4SE5MZ.js.map} +0 -0
- /package/dist/{tool-FWATXW5Q.js.map → tool-2PA2USUG.js.map} +0 -0
- /package/dist/{tool-HXFGNBLS.js.map → tool-DIJN4XBY.js.map} +0 -0
- /package/dist/{wiki-PG5ZBOMH.js.map → wiki-CQBXLZ2Y.js.map} +0 -0
- /package/dist/{wiki-enrich-BIQZWJRB.js.map → wiki-enrich-PA6JS2YN.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-RNAKP7WY.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-JNG3P5V2.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-HVNWI63Z.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-JNG3P5V2.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-RJCHFDF3.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-JPZBWHNZ.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(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=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(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 s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(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=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(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-RUQMUDSX.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as St,c as At}from"./chunk-5TTHN7DP.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-
|
|
1
|
+
import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as St,c as At}from"./chunk-5TTHN7DP.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-LH3GOBZP.js";import{b as ft,d as gt,e as mt}from"./chunk-PE5V2LI7.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-HVNWI63Z.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var Ft=200,nr=7,jt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ne(e,".agentx/memory"),this.ledger=new ft(ne(e,".agentx/wiki")),Mt(this.memoryDir)||er(this.memoryDir,{recursive:!0})}filePath(e){return ne(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||$e(t.content))return!1;let r=t.source.trust??dt(t.source.channel),o=t.review??lt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Xn(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Mt(t))return[];try{let{mtimeMs:r,size:o}=tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Et(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Ae);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ne(this.memoryDir,`${t}_bm25_cache.json`),i=it(s,a),d=ot(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),c=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(c.length===0)return o.slice(-r);let f=c.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Ot(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Dt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Pe(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -38,4 +38,4 @@ ${n.text}`}async function me(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
38
38
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Xe(this.file))try{let e=JSON.parse(et(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Sn(xn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Tn(4).toString("hex")}.tmp`;Rn(t,JSON.stringify(e,null,2)+`
|
|
39
39
|
`,{encoding:"utf-8",mode:384}),An(t,this.file)}};import{extname as li}from"path";var Nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Dn=/<agentx-artifact>[\s\S]*$/i;function ld(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Nn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Dn,""):s).trim(),artifacts:r}}function ud(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Nn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Dn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ui={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},cd={bytes:20*1024*1024,perMessage:20,pathChars:512};function pd(n){return ui[li(n).toLowerCase()]??null}var ci=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
40
40
|
`);function fd(n,e,t){return n==="app"&&e&&t!==!1?ci:void 0}import{lstatSync as nt,mkdirSync as pi,readdirSync as fi,realpathSync as tt,unlinkSync as gi}from"fs";import{join as be,resolve as On}from"path";var En=".agentx/outbox",mi=7*24*60*60*1e3;function hi(n,e){try{let t=tt(On(e,n)),r=be(t,En);return tt(r)===r&&nt(r).isDirectory()?r:null}catch{return null}}function wd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=tt(On(t,n));nt(be(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||pi(be(o,En),{recursive:!0})}catch{return 0}let r=hi(n,t);return r?Mn(r,(e.now??Date.now())-(e.maxAgeMs??mi)):0}function Mn(n,e){let t=0;for(let r of fi(n)){let o=be(n,r);try{let s=nt(o);s.isDirectory()?t+=Mn(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(gi(o),t++)}catch{}}return t}export{Tt as a,jt as b,Ct as c,Di as d,ir as e,Oi as f,T as g,z as h,S as i,oe as j,Ir as k,Oe as l,F as m,Fe as n,Ce as o,Ge as p,To as q,Mo as r,Qe as s,_r as t,Go as u,Na as v,Da as w,Oa as x,Ea as y,Ma as z,Vo as A,Qo as B,Fa as C,ja as D,Ca as E,_a as F,Ha as G,Ka as H,Ba as I,qa as J,za as K,Ja as L,Ya as M,Ga as N,Va as O,Qa as P,Za as Q,ri as R,Xa as S,ed as T,td as U,nd as V,Wn as W,ld as X,ud as Y,cd as Z,pd as _,fd as $,En as aa,wd as ba};
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-S5FRIHWM.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-
|
|
1
|
+
import{a as Le,b as k,c as z,d as Be,e as pe,f as ue,g as N,h as ge,i as O,j as U,n as je,o as He,p as qe,q as Fe}from"./chunk-XVTD6I34.js";import{e as Oe,i as Ue}from"./chunk-QAWKN2N4.js";import{b as ce}from"./chunk-MTX4UPNB.js";import{a as X,b as Ne}from"./chunk-CFPRIE6F.js";import{c as Me,d as le,e as P,f as de,g as j}from"./chunk-B2QYMUTD.js";import{a as We}from"./chunk-7LN4VKDU.js";import{a as Te}from"./chunk-IMLAPB7G.js";import{c as Re,e as De}from"./chunk-LQE73AZR.js";import{b as ze}from"./chunk-MRIVENBY.js";import{n as se,p as _e}from"./chunk-24QMHUU2.js";import{b as Y}from"./chunk-YMX3QCV7.js";import{G as J}from"./chunk-S5FRIHWM.js";import{a as G,b as K}from"./chunk-BFONYVOM.js";import{a as Pe}from"./chunk-RUQMUDSX.js";import{c as Ce,d as Ie}from"./chunk-OWNQ2FD4.js";import{a as Ee}from"./chunk-ROLSSYXE.js";import{Ia as oe,Ka as F,L as ae,La as Se,M as $e,T as Rt,Ua as ie,ia as Ae,pa as Dt}from"./chunk-5VPU5FHB.js";import{existsSync as H,readFileSync as Je,writeFileSync as Ye,appendFileSync as Wt,mkdirSync as Mt}from"fs";import{dirname as Nt,resolve as W}from"path";import{fileURLToPath as Ot}from"url";import{hostname as Ut}from"os";import{spawn as Lt}from"child_process";function Ge(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
|
|
2
2
|
<div class="ax-topbar__left">
|
|
3
3
|
<div class="ax-brand">
|
|
4
4
|
<span class="ax-brand__mark">AX</span>
|
|
@@ -180,8 +180,8 @@ ${m}
|
|
|
180
180
|
`)?"":`
|
|
181
181
|
`;Wt(e,o+a.join(`
|
|
182
182
|
`)+`
|
|
183
|
-
`)}}function cr(e,t){let n=Xe(),r=n.nodeName||Ut().replace(/\.local$/,""),a=Ge(n,r);t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(a)}async function pr(e,t){let n="";await new Promise(a=>{e.on("data",o=>{n+=o}),e.on("end",()=>a())});let r;try{r=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}try{let a=Bt(r);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a))}catch(a){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:a.message||"wizard failed"}))}}async function ur(e,t){t.setHeader("Content-Type","application/json");let n;try{n=Se().node?.bind||"127.0.0.1:18800"}catch(i){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`Config validation failed: ${i.message}`}));return}let r=`http://${n.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await Ke(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let a=process.argv[1]||W(Nt(Ot(import.meta.url)),"cli.js");try{Lt(process.execPath,[a,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(i){t.writeHead(500),t.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${i.message}`,manualUrl:r}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(i=>setTimeout(i,400)),await Ke(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!1}));return}t.writeHead(504),t.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:r}))}async function Ke(e){try{let t=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return t.status>0&&t.status<600}catch{return!1}}import{mkdirSync as Ft,readFileSync as Gt,renameSync as Kt,writeFileSync as Jt}from"fs";import{dirname as Yt,isAbsolute as Xt,resolve as Vt}from"path";import{createHash as Qt,randomBytes as Zt}from"crypto";var xr=".agentx/app-pins.json",yr=12,et=40,tt=2e3,en=/^pin_[a-z0-9]{6,32}$/;function tn(e,t){return Xt(t)?t:Vt(e,t)}function V(e){let t=typeof e=="string"?e.trim().replace(/\s+/g," "):"";return t?/[\p{Cc}\p{Cf}]/u.test(t)?{ok:!1,error:"Use only letters, numbers, spaces and punctuation in the name."}:[...t].length>et?{ok:!1,error:`Keep the name under ${et} characters.`}:{ok:!0,value:t}:{ok:!1,error:"Give the button a name."}}function fe(e){let t=typeof e=="string"?e.trim():"";if(!t)return{ok:!1,error:"Give the page's address."};if(t.length>tt)return{ok:!1,error:`Keep the address under ${tt} characters.`};let n;try{n=new URL(t)}catch{return{ok:!1,error:"That is not a web address. It should start with https://"}}return n.protocol!=="https:"||!n.hostname?{ok:!1,error:"Only https:// pages can be pinned."}:n.username||n.password?{ok:!1,error:"Leave the user name and password out of the address."}:{ok:!0,value:n.href}}function nn(e){return`cfg_${Qt("sha256").update(e).digest("hex").slice(0,12)}`}function rn(e){let t=[];for(let n of e){let r=V(n.label),a=fe(n.url);!r.ok||!a.ok||t.some(o=>o.url===a.value||o.label.toLowerCase()===r.value.toLowerCase())||t.push({id:nn(a.value),label:r.value,url:a.value,source:"config"})}return t}var nt="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function an(e){let t=V(e.label);if(!t.ok)return t;let n=fe(e.url);return n.ok?{ok:!0,value:{label:t.value,url:n.value}}:n}var me=class{constructor(t,n=Date.now,r=[]){this.path=t;this.now=n;this.fixed=r}list(){return[...this.fixed,...this.load().pins]}isFixed(t){return this.fixed.some(n=>n.id===t)}load(){let t;try{t=Gt(this.path,"utf-8")}catch(o){return{pins:[],damaged:o?.code!=="ENOENT"}}let n;try{n=JSON.parse(t)}catch{return{pins:[],damaged:!0}}let r=Array.isArray(n?.pins)?n.pins:[],a=r.filter(o=>{let i=o;return!!i&&typeof i.id=="string"&&en.test(i.id)&&V(i.label).ok&&fe(i.url).ok});return{pins:a,damaged:!Array.isArray(n?.pins)||a.length!==r.length}}locked(t){try{return Ie(this.path,t,{what:"The pinned pages file"})}catch(n){if(n instanceof Ce)return{ok:!1,status:409,error:n.message};throw n}}editable(){let{pins:t,damaged:n}=this.load();return n?{ok:!1,status:409,error:`The pinned pages file (${this.path}) can't be read. Fix or remove it on the computer, then try again.`}:{ok:!0,pins:t}}write(t){Ft(Yt(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;Jt(n,JSON.stringify({pins:t},null,2)+`
|
|
184
|
-
`,{mode:384}),Kt(n,this.path)}add(t,n){return this.locked(()=>this.addUnlocked(t,n))}addUnlocked(t,n){let r=this.editable();if(!r.ok)return r;let a=r.pins;if(a.length+this.fixed.length>=n)return{ok:!1,status:409,error:`You already have ${n} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...a].some(i=>i.label.toLowerCase()===t.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${t.label}.`};let o={id:`pin_${Zt(6).toString("hex")}`,...t,createdAt:new Date(this.now()).toISOString()};return a.push(o),this.write(a),{ok:!0,pin:o}}rename(t,n){return this.locked(()=>this.renameUnlocked(t,n))}renameUnlocked(t,n){if(this.isFixed(t))return{ok:!1,status:409,error:nt};let r=this.editable();if(!r.ok)return r;let a=r.pins,o=a.find(i=>i.id===t);return o?[...this.fixed,...a].some(i=>i.id!==t&&i.label.toLowerCase()===n.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${n}.`}:(o.label=n,this.write(a),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(t){return this.locked(()=>this.removeUnlocked(t))}removeUnlocked(t){if(this.isFixed(t))return{ok:!1,status:409,error:nt};let n=this.editable();if(!n.ok)return n;let r=n.pins.filter(a=>a.id!==t);return r.length===n.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function kr(e,t){let n=e.app.pins;return{store:new me(tn(t,n.file),Date.now,rn(n.pages)),max:n.max}}async function wr(e,t,n,r,a){if(n!=="/api/app/pins"&&!n.startsWith("/api/app/pins/"))return!1;let o=n.slice(13);if(r==="GET"&&o==="")return T(t,200,{pins:a.store.list(),max:a.max});if(r!=="POST")return T(t,404,{error:"not found"});let i;try{i=await Y(e,4096)}catch(l){return T(t,400,{error:l.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let l=an(i);if(!l.ok)return T(t,400,{error:l.error});let d=a.store.add(l.value,a.max);return d.ok?T(t,200,{ok:!0,pin:d.pin}):T(t,d.status,{error:d.error})}if(o==="/rename"){let l=V(i.label);if(!l.ok)return T(t,400,{error:l.error});let d=a.store.rename(s,l.value);return d.ok?T(t,200,{ok:!0,pin:d.pin}):T(t,d.status,{error:d.error})}if(o==="/remove"){let l=a.store.remove(s);return l.ok?T(t,200,{ok:!0}):T(t,l.status,{error:l.error})}return T(t,404,{error:"not found"})}function T(e,t,n){return e.writeHead(t,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(n)),!0}import{existsSync as on,readFileSync as sn}from"fs";ie();function Ir(e){let t=G(e),n={};if(on(t))try{n=F(JSON.parse(sn(t,"utf-8")))}catch{n={}}let r=oe.safeParse(n?.approvals);return r.success?r.data:oe.parse(void 0)}function Er(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function Pr(e,t={}){return K(n=>{let r=n.approvals??={};if(e.defaultExpiryDays!==void 0&&(r.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(r.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(r.laterHours=e.laterHours),e.notifyAgent!==void 0&&(r.notifyAgent=e.notifyAgent),e.forwardTo===null)delete r.forwardTo;else if(e.forwardTo!==void 0){let d=Array.isArray(n.mesh?.peers)?n.mesh.peers:[];if(!d.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${d.length?` (known: ${d.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let a=r.digest??={};e.digestEnabled!==void 0&&(a.enabled=e.digestEnabled),e.digestTime!==void 0&&(a.time=e.digestTime),e.digestTimezone===null?delete a.timezone:e.digestTimezone!==void 0&&(a.timezone=e.digestTimezone),e.destination===null?delete a.destination:e.destination!==void 0&&(a.destination=e.destination);let o=r.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let i=r.checkin??={};e.checkinEnabled!==void 0&&(i.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(i.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(i.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(i.lists=e.checkinLists),e.checkinAgent===null?delete i.agent:e.checkinAgent!==void 0&&(i.agent=e.checkinAgent);let s=r.defaultExpiryDays??3,l=r.maxExpiryDays??30;if(s>l)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${l})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as mn}from"http";var Q=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({...n,url:n.url.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let r=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=r.nodeId;for(let a of r.agents||[])(a.totalEntries>0||a.totalArticles>0)&&t.push({...a,nodeId:r.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,r){try{let a=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(r)}`);return{meta:{title:a.title,tags:a.tags||[],owner:a.owner,access:"public",created:a.created,lastUpdated:a.lastUpdated,sources:a.sources||[]},content:a.content,path:a.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let r=this.peers.find(i=>t.startsWith(`${i.url}/`))?.token,a=await fetch(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let o=await a.json();return this.cache.set(t,{data:o,ts:Date.now()}),o}};var rt=864e5;function he(e){let t=new Map;for(let n of e.entities.values()){let r=t.get(n.type)??[];r.push(n),t.set(n.type,r)}return t}function ve(e,t){if(t.type==="event")return t.date||t.updated;let n=Le(e,t,new Set(["event"]))[0],r=t.updated||t.date;return n&&n.date>r?n.date:r}function at(e,t,n=Date.now()){let r=[],a=new Date(n+14*rt).toISOString().slice(0,10),o=new Date(n).toISOString().slice(0,10);for(let s of t){let l=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),d=s.statements.some(c=>c.property==="fulfilled_by")||s.statements.some(c=>c.property==="status"&&/^(fulfilled|done|paid|filed)$/i.test(c.value));s.statements.some(c=>c.property==="status"&&/^late$/i.test(c.value))?r.push({e:s,chip:"late",why:"marked late"}):l&&!d&&l.value<o?r.push({e:s,chip:"late",why:`was due ${l.value}`}):l&&!d&&l.value<=a?r.push({e:s,chip:"due",why:`due ${l.value}`}):s.statements.some(c=>c.status==="proposed")?r.push({e:s,chip:"proposed",why:"statements wait for confirmation"}):s.type==="event"&&s.importanceProposed&&s.importanceProposed!==s.importance?r.push({e:s,chip:"proposed",why:`proposed as ${s.importanceProposed}; the owner decides`}):s.type==="event"&&s.importance==="major"&&s.date&&n-Date.parse(s.date)<=30*rt&&r.push({e:s,chip:"major",why:`major event ${s.date}`})}let i={late:0,due:1,major:2,proposed:3};return r.sort((s,l)=>i[s.chip]-i[l.chip])}function Z(e,t,n="",r){return`<div class="ox-row"><span class="ox-ic">${Be(e.ontology,t.type)}</span><div class="t"><a href="${ue(t.id)}">${k(t.title)}</a><div class="ox-sub">${k(r??`${pe(e.ontology,t.type).toLowerCase()} \xB7 ${ve(e,t)}`)}</div></div><div class="r">${n}</div></div>`}function ot(e,t){let n=t.slice(0,6).map(r=>Z(e,r.e,`<span class="ox-st ${r.chip}">${r.chip}</span>`,r.why)).join("");return`<section class="ox-card"><div class="ox-card-h"><h2>Needs attention</h2><span class="note">${t.length}</span></div>${n||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function ln(e){return e.length?`<div class="ox-err"><b>ontology.yaml has ${e.length} problem${e.length===1?"":"s"}</b> \u2014 the defaults are used where they apply. <a href="/ontology">See them</a></div>`:""}function it(e,t){let n=he(e),r=`<div class="ox-bar">${N([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${z("home")}</div><div><h1>Wiki</h1><p>${e.entities.size} things, merged from every agent's pages and typed by the <a href="/ontology">ontology</a>. <a href="/agents">Agent wikis</a> \xB7 <a href="/entries">raw entries</a></p></div></div>`,r+=ln(t),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(d=>d.pillar===o.id),s=i.reduce((d,c)=>d+(n.get(c.id)?.length??0),0),l=i.filter(d=>n.get(d.id)?.length).map(d=>`${d.plural??d.label} ${n.get(d.id).length}`).join(" \xB7 ");r+=`<a class="ox-card" href="/p/${encodeURIComponent(o.id)}" style="color:inherit"><div class="ox-card-h"><span class="ox-ic">${z(o.icon)}</span><h2>${k(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${k(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${k(l||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let a=(n.get("event")??[]).filter(o=>o.importance!=="minor").sort((o,i)=>i.date.localeCompare(o.date)).slice(0,8);return r+='<section class="ox-card"><div class="ox-card-h"><h2>Recent events</h2><span class="note">major and normal</span><a class="zin" href="/p/events">all (Z1) \u2192</a></div>'+(a.map(o=>`<div class="ox-ev"><span class="d">${k(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${ue(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=ot(e,at(e,[...e.entities.values()])),r+="</div>",U("Wiki",O(e,{home:!0}),r)}function st(e,t,n){let r=e.ontology.pillars.find(c=>c.id===t);if(!r)return null;let a=he(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===n)??o.find(c=>a.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${N([{label:r.label}])}${ge(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${z(r.icon)}</div><div><h1>${k(r.label)}</h1><p>${k(r.description??"")}</p></div></div>`,s+=`<nav class="ox-tabs">${o.map(c=>`<a class="${c.id===i?.id?"on":""}" href="/p/${encodeURIComponent(r.id)}?kind=${encodeURIComponent(c.id)}">${k(c.plural??c.label)}<small>${a.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let l=i?(a.get(i.id)??[]).map(c=>({e:c,at:ve(e,c)})).sort((c,m)=>m.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${k(i?.plural??i?.label??"")}</h2><span class="note">${l.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(l.slice(0,5).map(({e:c,at:m})=>Z(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${je(c,90)||pe(e.ontology,c.type).toLowerCase()} \xB7 ${m}`)).join("")||`<div class="ox-empty">No ${k((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let d=o.flatMap(c=>a.get(c.id)??[]);return s+=ot(e,at(e,d)),s+="</div>",U(r.label,O(e,{pillar:r.id}),s)}function lt(e,t,n,r,a){let o=a&&Ee.includes(a)?a:null,i=e.ontology.pillars.find(g=>g.id===t),s=e.ontology.types.find(g=>g.id===n&&g.pillar===t);if(!i||!s)return null;let l=[...e.entities.values()].filter(g=>g.type===s.id);o&&(l=l.filter(g=>g.importance===o));let d=l.map(g=>({e:g,at:ve(e,g)})).sort((g,f)=>f.at.localeCompare(g.at)),c=50,m=Math.max(1,Math.ceil(d.length/c)),p=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,w=`<div class="ox-bar">${N([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${ge(3)}</div>`;if(w+=`<div class="ox-head"><div class="ox-avatar">${z(s.icon)}</div><div><h1>${k(s.plural??s.label)}</h1><p>${d.length} page${d.length===1?"":"s"}${o?` \xB7 ${k(o)} only`:""}</p></div></div>`,s.id==="event"&&(w+=`<nav class="ox-tabs">${["","major","normal","minor"].map(g=>`<a class="${(o??"")===g?"on":""}" href="${p}${g?`?importance=${g}`:""}">${g||"all"}</a>`).join("")}</nav>`),w+='<section class="ox-card" style="margin-top:16px">'+(d.slice((r-1)*c,r*c).map(({e:g,at:f})=>Z(e,g,g.type==="event"?`<span class="ox-st ${g.importance}">${g.importance}</span>`:"",`${f} \xB7 ${g.pages.map(C=>C.agentId).filter((C,x,b)=>b.indexOf(C)===x).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",m>1){let g=o?`importance=${o}&`:"";w+=`<div class="ox-pager">${r>1?`<a href="${p}?${g}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${m}</span>${r<m?`<a href="${p}?${g}page=${r+1}">next \u2192</a>`:""}</div>`}return U(s.plural??s.label,O(e,{pillar:i.id}),w)}function dt(e,t){let n=t.trim().toLowerCase(),r=[];if(n)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===n?100:i.startsWith(n)?60:i.includes(n)?40:0;!s&&o.pages.some(l=>l.article.content.toLowerCase().includes(n))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let a=`<div class="ox-bar">${N([{label:"Search"}])}</div>`;return a+=`<div class="ox-head"><div class="ox-avatar">${z("search")}</div><div><h1>${n?`\u201C${k(t)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,a+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>Z(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,U(`Search: ${t}`,O(e,{}),a,"",t)}function ct(e,t,n){let r=e.ontology,a=he(e),o=`<div class="ox-bar">${N([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${z("steps")}</div><div><h1>Ontology</h1><p>${n?`Read from ${k(n)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,t.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${t.map(i=>`<li>${k(i)}</li>`).join("")}</ul></div>`),o+=`<section class="ox-card"><div class="ox-card-h"><h2>Types</h2><span class="note">${r.types.length}</span></div>`;for(let i of r.types){let s=r.pillars.find(l=>l.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${z(i.icon)}</span><div class="t"><span class="l">${k(i.label)} <span class="ox-sub">${k(i.id)}</span></span><div class="ox-sub">${k(s?.label??i.pillar)} \xB7 lens: ${k((i.lens??[]).map(l=>l.title??l.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${a.get(i.id)?.length??0}</span></div></div>`}o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Relations</h2><span class="note">${r.properties.length}</span></div>`;for(let i of r.properties)o+=`<div class="ox-kv"><span class="k">${k(i.id)}</span><span>${k(i.label)}${i.inverse?` \xB7 inverse: ${k(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${k(i.wikidata)}</span>`:""}</span></div>`;return o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Event importance</h2></div><div class="ox-kv"><span class="k">default</span><span>${k(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${k(r.importance.major_set_by)}</span></div><div class="ox-kv"><span class="k">roll-up</span><span>${r.importance.rollup.min} minor events in ${r.importance.rollup.days} days</span></div></section>`,U("Ontology",O(e,{}),o)}var ee=class{constructor(t,n){this.hub=t;this.wikiDir=n}cache=new Ue;pageAt(t){if(!t.startsWith("/e/"))return null;let{ontology:n}=ce(this.wikiDir),a=this.cache.get(this.hub,n).entities.get(t.split("/").filter(Boolean)[1]??"")?.pages[0];return a?{agentId:a.agentId,path:a.article.path,title:a.article.meta.title}:null}handle(t,n){if(!(t==="/"||t===""||t.startsWith("/p/")||t.startsWith("/e/")||t==="/find"||t==="/ontology"))return null;let{ontology:r,errors:a,file:o}=ce(this.wikiDir),i=Oe(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),l=Math.max(1,Number(n.get("page"))||1);if(t==="/"||t==="")return it(s,a);if(t==="/find")return dt(s,n.get("q")??"");if(t==="/ontology")return ct(s,a,o);let d=t.split("/").filter(Boolean);if(d[0]==="p")return d.length===2?st(s,d[1],n.get("kind")):d.length===3?lt(s,d[1],d[2],l,n.get("importance")):null;let c=s.entities.get(d[1]??"");if(!c)return null;let m={g:s,readEntries:p=>this.hub.getSharedStore().readEntries(p),versions:(p,w)=>this.hub.getAgentWiki(p).getVersions(w)};return d.length===2?He(m,c):d.length===3?qe(m,c,d[2],l):d.length===4&&d[2]==="s"?Fe(m,c,Number(d[3])):null}};var dn=`
|
|
183
|
+
`)}}function cr(e,t){let n=Xe(),r=n.nodeName||Ut().replace(/\.local$/,""),a=Ge(n,r);t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(a)}async function pr(e,t){let n="";await new Promise(a=>{e.on("data",o=>{n+=o}),e.on("end",()=>a())});let r;try{r=JSON.parse(n)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}try{let a=Bt(r);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a))}catch(a){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:a.message||"wizard failed"}))}}async function ur(e,t){t.setHeader("Content-Type","application/json");let n;try{n=Se().node?.bind||"127.0.0.1:18800"}catch(i){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`Config validation failed: ${i.message}`}));return}let r=`http://${n.replace(/^0\.0\.0\.0/,"127.0.0.1")}`;if(await Ke(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!0}));return}let a=process.argv[1]||W(Nt(Ot(import.meta.url)),"cli.js");try{Lt(process.execPath,[a,"daemon","start"],{detached:!0,stdio:"ignore",cwd:process.cwd()}).unref()}catch(i){t.writeHead(500),t.end(JSON.stringify({ok:!1,error:`Failed to spawn daemon: ${i.message}`,manualUrl:r}));return}let o=Date.now()+12e3;for(;Date.now()<o;)if(await new Promise(i=>setTimeout(i,400)),await Ke(r)){t.writeHead(200),t.end(JSON.stringify({ok:!0,url:r,alreadyRunning:!1}));return}t.writeHead(504),t.end(JSON.stringify({ok:!1,error:"Daemon spawn succeeded but never bound the port within 12s \u2014 check `agentx daemon status` and the dotfile log for errors.",manualUrl:r}))}async function Ke(e){try{let t=await fetch(e,{method:"GET",signal:AbortSignal.timeout(800)});return t.status>0&&t.status<600}catch{return!1}}import{mkdirSync as Ft,readFileSync as Gt,renameSync as Kt,writeFileSync as Jt}from"fs";import{dirname as Yt,isAbsolute as Xt,resolve as Vt}from"path";import{createHash as Qt,randomBytes as Zt}from"crypto";var xr=".agentx/app-pins.json",yr=12,et=40,tt=2e3,en=/^pin_[a-z0-9]{6,32}$/;function tn(e,t){return Xt(t)?t:Vt(e,t)}function V(e){let t=typeof e=="string"?e.trim().replace(/\s+/g," "):"";return t?/[\p{Cc}\p{Cf}]/u.test(t)?{ok:!1,error:"Use only letters, numbers, spaces and punctuation in the name."}:[...t].length>et?{ok:!1,error:`Keep the name under ${et} characters.`}:{ok:!0,value:t}:{ok:!1,error:"Give the button a name."}}function fe(e){let t=typeof e=="string"?e.trim():"";if(!t)return{ok:!1,error:"Give the page's address."};if(t.length>tt)return{ok:!1,error:`Keep the address under ${tt} characters.`};let n;try{n=new URL(t)}catch{return{ok:!1,error:"That is not a web address. It should start with https://"}}return n.protocol!=="https:"||!n.hostname?{ok:!1,error:"Only https:// pages can be pinned."}:n.username||n.password?{ok:!1,error:"Leave the user name and password out of the address."}:{ok:!0,value:n.href}}function nn(e){return`cfg_${Qt("sha256").update(e).digest("hex").slice(0,12)}`}function rn(e){let t=[];for(let n of e){let r=V(n.label),a=fe(n.url);!r.ok||!a.ok||t.some(o=>o.url===a.value||o.label.toLowerCase()===r.value.toLowerCase())||t.push({id:nn(a.value),label:r.value,url:a.value,source:"config"})}return t}var nt="This button is set in agentx.json (app.pins.pages). Change or remove it there.";function an(e){let t=V(e.label);if(!t.ok)return t;let n=fe(e.url);return n.ok?{ok:!0,value:{label:t.value,url:n.value}}:n}var me=class{constructor(t,n=Date.now,r=[]){this.path=t;this.now=n;this.fixed=r}list(){return[...this.fixed,...this.load().pins.filter(t=>!this.shadowed(t))]}shadowed(t){return this.fixed.some(n=>n.url===t.url||n.label.toLowerCase()===t.label.toLowerCase())}isFixed(t){return this.fixed.some(n=>n.id===t)}load(){let t;try{t=Gt(this.path,"utf-8")}catch(o){return{pins:[],damaged:o?.code!=="ENOENT"}}let n;try{n=JSON.parse(t)}catch{return{pins:[],damaged:!0}}let r=Array.isArray(n?.pins)?n.pins:[],a=r.filter(o=>{let i=o;return!!i&&typeof i.id=="string"&&en.test(i.id)&&V(i.label).ok&&fe(i.url).ok});return{pins:a,damaged:!Array.isArray(n?.pins)||a.length!==r.length}}locked(t){try{return Ie(this.path,t,{what:"The pinned pages file"})}catch(n){if(n instanceof Ce)return{ok:!1,status:409,error:n.message};throw n}}editable(){let{pins:t,damaged:n}=this.load();return n?{ok:!1,status:409,error:`The pinned pages file (${this.path}) can't be read. Fix or remove it on the computer, then try again.`}:{ok:!0,pins:t}}write(t){Ft(Yt(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;Jt(n,JSON.stringify({pins:t},null,2)+`
|
|
184
|
+
`,{mode:384}),Kt(n,this.path)}add(t,n){return this.locked(()=>this.addUnlocked(t,n))}addUnlocked(t,n){let r=this.editable();if(!r.ok)return r;let a=r.pins;if(a.filter(i=>!this.shadowed(i)).length+this.fixed.length>=n)return{ok:!1,status:409,error:`You already have ${n} pinned pages, the most allowed (app.pins.max). Remove one first.`};if([...this.fixed,...a].some(i=>i.label.toLowerCase()===t.label.toLowerCase()))return{ok:!1,status:409,error:`You already have a button called ${t.label}.`};if(this.fixed.some(i=>i.url===t.url))return{ok:!1,status:409,error:"This page is already a button, set in agentx.json (app.pins.pages)."};let o={id:`pin_${Zt(6).toString("hex")}`,...t,createdAt:new Date(this.now()).toISOString()};return a.push(o),this.write(a),{ok:!0,pin:o}}rename(t,n){return this.locked(()=>this.renameUnlocked(t,n))}renameUnlocked(t,n){if(this.isFixed(t))return{ok:!1,status:409,error:nt};let r=this.editable();if(!r.ok)return r;let a=r.pins,o=a.find(i=>i.id===t);return o?[...this.fixed,...a].some(i=>i.id!==t&&i.label.toLowerCase()===n.toLowerCase())?{ok:!1,status:409,error:`You already have a button called ${n}.`}:(o.label=n,this.write(a),{ok:!0,pin:o}):{ok:!1,status:404,error:"No such pinned page."}}remove(t){return this.locked(()=>this.removeUnlocked(t))}removeUnlocked(t){if(this.isFixed(t))return{ok:!1,status:409,error:nt};let n=this.editable();if(!n.ok)return n;let r=n.pins.filter(a=>a.id!==t);return r.length===n.pins.length?{ok:!1,status:404,error:"No such pinned page."}:(this.write(r),{ok:!0})}};function kr(e,t){let n=e.app.pins;return{store:new me(tn(t,n.file),Date.now,rn(n.pages)),max:n.max}}async function wr(e,t,n,r,a){if(n!=="/api/app/pins"&&!n.startsWith("/api/app/pins/"))return!1;let o=n.slice(13);if(r==="GET"&&o==="")return T(t,200,{pins:a.store.list(),max:a.max});if(r!=="POST")return T(t,404,{error:"not found"});let i;try{i=await Y(e,4096)}catch(l){return T(t,400,{error:l.message})}let s=typeof i.id=="string"?i.id:"";if(o==="/add"){let l=an(i);if(!l.ok)return T(t,400,{error:l.error});let d=a.store.add(l.value,a.max);return d.ok?T(t,200,{ok:!0,pin:d.pin}):T(t,d.status,{error:d.error})}if(o==="/rename"){let l=V(i.label);if(!l.ok)return T(t,400,{error:l.error});let d=a.store.rename(s,l.value);return d.ok?T(t,200,{ok:!0,pin:d.pin}):T(t,d.status,{error:d.error})}if(o==="/remove"){let l=a.store.remove(s);return l.ok?T(t,200,{ok:!0}):T(t,l.status,{error:l.error})}return T(t,404,{error:"not found"})}function T(e,t,n){return e.writeHead(t,{"Content-Type":"application/json","Cache-Control":"no-store"}),e.end(JSON.stringify(n)),!0}import{existsSync as on,readFileSync as sn}from"fs";ie();function Ir(e){let t=G(e),n={};if(on(t))try{n=F(JSON.parse(sn(t,"utf-8")))}catch{n={}}let r=oe.safeParse(n?.approvals);return r.success?r.data:oe.parse(void 0)}function Er(e){let t=e.indexOf(":");return t<=0||t===e.length-1?null:{channel:e.slice(0,t).trim(),chatId:e.slice(t+1).trim()}}async function Pr(e,t={}){return K(n=>{let r=n.approvals??={};if(e.defaultExpiryDays!==void 0&&(r.defaultExpiryDays=e.defaultExpiryDays),e.maxExpiryDays!==void 0&&(r.maxExpiryDays=e.maxExpiryDays),e.laterHours!==void 0&&(r.laterHours=e.laterHours),e.notifyAgent!==void 0&&(r.notifyAgent=e.notifyAgent),e.forwardTo===null)delete r.forwardTo;else if(e.forwardTo!==void 0){let d=Array.isArray(n.mesh?.peers)?n.mesh.peers:[];if(!d.some(c=>c.name===e.forwardTo))throw new Error(`"${e.forwardTo}" is not in mesh.peers${d.length?` (known: ${d.map(c=>c.name).join(", ")})`:""}; pair the machines first`);r.forwardTo=e.forwardTo}let a=r.digest??={};e.digestEnabled!==void 0&&(a.enabled=e.digestEnabled),e.digestTime!==void 0&&(a.time=e.digestTime),e.digestTimezone===null?delete a.timezone:e.digestTimezone!==void 0&&(a.timezone=e.digestTimezone),e.destination===null?delete a.destination:e.destination!==void 0&&(a.destination=e.destination);let o=r.popup??={};e.popupEnabled!==void 0&&(o.enabled=e.popupEnabled),e.popupSpeak!==void 0&&(o.speak=e.popupSpeak),e.popupVoice===null?delete o.voice:e.popupVoice!==void 0&&(o.voice=e.popupVoice),e.popupSound!==void 0&&(o.sound=e.popupSound),e.popupTimeoutSeconds!==void 0&&(o.timeoutSeconds=e.popupTimeoutSeconds),e.popupStyle!==void 0&&(o.style=e.popupStyle),e.popupTheme!==void 0&&(o.theme=e.popupTheme);let i=r.checkin??={};e.checkinEnabled!==void 0&&(i.enabled=e.checkinEnabled),e.checkinTimes!==void 0&&(i.times=e.checkinTimes),e.checkinDailyAt!==void 0&&(i.dailyAt=e.checkinDailyAt),e.checkinLists!==void 0&&(i.lists=e.checkinLists),e.checkinAgent===null?delete i.agent:e.checkinAgent!==void 0&&(i.agent=e.checkinAgent);let s=r.defaultExpiryDays??3,l=r.maxExpiryDays??30;if(s>l)throw new Error(`defaultExpiryDays (${s}) can't be more than maxExpiryDays (${l})`)},{configPath:t.configPath,reload:t.reload})}import{createServer as mn}from"http";var Q=class{peers;cache=new Map;ttl=3e4;constructor(t){this.peers=t.map(n=>({...n,url:n.url.replace(/\/$/,"")}))}async getRemoteAgents(){let t=[];return await Promise.all(this.peers.map(async n=>{try{let r=await this.fetchJson(`${n.url}/wiki/agents`);n.nodeId=r.nodeId;for(let a of r.agents||[])(a.totalEntries>0||a.totalArticles>0)&&t.push({...a,nodeId:r.nodeId,peerUrl:n.url})}catch{}})),t}async getRemoteArticles(t,n){try{return(await this.fetchJson(`${t}/wiki/articles?agent=${encodeURIComponent(n)}`)).articles||[]}catch{return[]}}async getRemoteArticle(t,n,r){try{let a=await this.fetchJson(`${t}/wiki/article?agent=${encodeURIComponent(n)}&path=${encodeURIComponent(r)}`);return{meta:{title:a.title,tags:a.tags||[],owner:a.owner,access:"public",created:a.created,lastUpdated:a.lastUpdated,sources:a.sources||[]},content:a.content,path:a.path}}catch{return null}}async fetchJson(t){let n=this.cache.get(t);if(n&&Date.now()-n.ts<this.ttl)return n.data;let r=this.peers.find(i=>t.startsWith(`${i.url}/`))?.token,a=await fetch(t,{headers:r?{Authorization:`Bearer ${r}`}:{},signal:AbortSignal.timeout(5e3)});if(!a.ok)throw new Error(`HTTP ${a.status}`);let o=await a.json();return this.cache.set(t,{data:o,ts:Date.now()}),o}};var rt=864e5;function he(e){let t=new Map;for(let n of e.entities.values()){let r=t.get(n.type)??[];r.push(n),t.set(n.type,r)}return t}function ve(e,t){if(t.type==="event")return t.date||t.updated;let n=Le(e,t,new Set(["event"]))[0],r=t.updated||t.date;return n&&n.date>r?n.date:r}function at(e,t,n=Date.now()){let r=[],a=new Date(n+14*rt).toISOString().slice(0,10),o=new Date(n).toISOString().slice(0,10);for(let s of t){let l=s.statements.find(c=>c.property==="due"&&/^\d{4}-\d{2}-\d{2}/.test(c.value)),d=s.statements.some(c=>c.property==="fulfilled_by")||s.statements.some(c=>c.property==="status"&&/^(fulfilled|done|paid|filed)$/i.test(c.value));s.statements.some(c=>c.property==="status"&&/^late$/i.test(c.value))?r.push({e:s,chip:"late",why:"marked late"}):l&&!d&&l.value<o?r.push({e:s,chip:"late",why:`was due ${l.value}`}):l&&!d&&l.value<=a?r.push({e:s,chip:"due",why:`due ${l.value}`}):s.statements.some(c=>c.status==="proposed")?r.push({e:s,chip:"proposed",why:"statements wait for confirmation"}):s.type==="event"&&s.importanceProposed&&s.importanceProposed!==s.importance?r.push({e:s,chip:"proposed",why:`proposed as ${s.importanceProposed}; the owner decides`}):s.type==="event"&&s.importance==="major"&&s.date&&n-Date.parse(s.date)<=30*rt&&r.push({e:s,chip:"major",why:`major event ${s.date}`})}let i={late:0,due:1,major:2,proposed:3};return r.sort((s,l)=>i[s.chip]-i[l.chip])}function Z(e,t,n="",r){return`<div class="ox-row"><span class="ox-ic">${Be(e.ontology,t.type)}</span><div class="t"><a href="${ue(t.id)}">${k(t.title)}</a><div class="ox-sub">${k(r??`${pe(e.ontology,t.type).toLowerCase()} \xB7 ${ve(e,t)}`)}</div></div><div class="r">${n}</div></div>`}function ot(e,t){let n=t.slice(0,6).map(r=>Z(e,r.e,`<span class="ox-st ${r.chip}">${r.chip}</span>`,r.why)).join("");return`<section class="ox-card"><div class="ox-card-h"><h2>Needs attention</h2><span class="note">${t.length}</span></div>${n||'<div class="ox-empty">Nothing waits on a person.</div>'}</section>`}function ln(e){return e.length?`<div class="ox-err"><b>ontology.yaml has ${e.length} problem${e.length===1?"":"s"}</b> \u2014 the defaults are used where they apply. <a href="/ontology">See them</a></div>`:""}function it(e,t){let n=he(e),r=`<div class="ox-bar">${N([])}</div>`;r+=`<div class="ox-head"><div class="ox-avatar">${z("home")}</div><div><h1>Wiki</h1><p>${e.entities.size} things, merged from every agent's pages and typed by the <a href="/ontology">ontology</a>. <a href="/agents">Agent wikis</a> \xB7 <a href="/entries">raw entries</a></p></div></div>`,r+=ln(t),r+='<div class="ox-grid3">';for(let o of e.ontology.pillars){let i=e.ontology.types.filter(d=>d.pillar===o.id),s=i.reduce((d,c)=>d+(n.get(c.id)?.length??0),0),l=i.filter(d=>n.get(d.id)?.length).map(d=>`${d.plural??d.label} ${n.get(d.id).length}`).join(" \xB7 ");r+=`<a class="ox-card" href="/p/${encodeURIComponent(o.id)}" style="color:inherit"><div class="ox-card-h"><span class="ox-ic">${z(o.icon)}</span><h2>${k(o.label)}</h2><span class="zin">${s}</span></div><div class="ox-sub" style="white-space:normal">${k(o.description??"")}</div><div class="ox-sub" style="margin-top:6px;white-space:normal">${k(l||"nothing yet")}</div></a>`}r+='</div><div class="ox-grid2">';let a=(n.get("event")??[]).filter(o=>o.importance!=="minor").sort((o,i)=>i.date.localeCompare(o.date)).slice(0,8);return r+='<section class="ox-card"><div class="ox-card-h"><h2>Recent events</h2><span class="note">major and normal</span><a class="zin" href="/p/events">all (Z1) \u2192</a></div>'+(a.map(o=>`<div class="ox-ev"><span class="d">${k(o.date)}</span><span class="ox-st ${o.importance}">${o.importance}</span><a href="${ue(o.id)}">${k(o.title)}</a></div>`).join("")||'<div class="ox-empty">No events yet.</div>')+"</section>",r+=ot(e,at(e,[...e.entities.values()])),r+="</div>",U("Wiki",O(e,{home:!0}),r)}function st(e,t,n){let r=e.ontology.pillars.find(c=>c.id===t);if(!r)return null;let a=he(e),o=e.ontology.types.filter(c=>c.pillar===r.id),i=o.find(c=>c.id===n)??o.find(c=>a.get(c.id)?.length)??o[0],s=`<div class="ox-bar">${N([{label:r.label}])}${ge(1)}</div>`;s+=`<div class="ox-head"><div class="ox-avatar">${z(r.icon)}</div><div><h1>${k(r.label)}</h1><p>${k(r.description??"")}</p></div></div>`,s+=`<nav class="ox-tabs">${o.map(c=>`<a class="${c.id===i?.id?"on":""}" href="/p/${encodeURIComponent(r.id)}?kind=${encodeURIComponent(c.id)}">${k(c.plural??c.label)}<small>${a.get(c.id)?.length??0}</small></a>`).join("")}</nav>`;let l=i?(a.get(i.id)??[]).map(c=>({e:c,at:ve(e,c)})).sort((c,m)=>m.at.localeCompare(c.at)):[];s+='<div class="ox-grid2">',s+=`<section class="ox-card"><div class="ox-card-h"><h2>${k(i?.plural??i?.label??"")}</h2><span class="note">${l.length} \xB7 most active first</span>`+(i?`<a class="zin" href="/p/${encodeURIComponent(r.id)}/${encodeURIComponent(i.id)}">open list (Z3) \u2192</a>`:"")+"</div>"+(l.slice(0,5).map(({e:c,at:m})=>Z(e,c,c.type==="event"?`<span class="ox-st ${c.importance}">${c.importance}</span>`:"",`${je(c,90)||pe(e.ontology,c.type).toLowerCase()} \xB7 ${m}`)).join("")||`<div class="ox-empty">No ${k((i?.plural??"pages").toLowerCase())} yet.</div>`)+"</section>";let d=o.flatMap(c=>a.get(c.id)??[]);return s+=ot(e,at(e,d)),s+="</div>",U(r.label,O(e,{pillar:r.id}),s)}function lt(e,t,n,r,a){let o=a&&Ee.includes(a)?a:null,i=e.ontology.pillars.find(g=>g.id===t),s=e.ontology.types.find(g=>g.id===n&&g.pillar===t);if(!i||!s)return null;let l=[...e.entities.values()].filter(g=>g.type===s.id);o&&(l=l.filter(g=>g.importance===o));let d=l.map(g=>({e:g,at:ve(e,g)})).sort((g,f)=>f.at.localeCompare(g.at)),c=50,m=Math.max(1,Math.ceil(d.length/c)),p=`/p/${encodeURIComponent(i.id)}/${encodeURIComponent(s.id)}`,w=`<div class="ox-bar">${N([{label:i.label,href:`/p/${encodeURIComponent(i.id)}`},{label:s.plural??s.label}])}${ge(3)}</div>`;if(w+=`<div class="ox-head"><div class="ox-avatar">${z(s.icon)}</div><div><h1>${k(s.plural??s.label)}</h1><p>${d.length} page${d.length===1?"":"s"}${o?` \xB7 ${k(o)} only`:""}</p></div></div>`,s.id==="event"&&(w+=`<nav class="ox-tabs">${["","major","normal","minor"].map(g=>`<a class="${(o??"")===g?"on":""}" href="${p}${g?`?importance=${g}`:""}">${g||"all"}</a>`).join("")}</nav>`),w+='<section class="ox-card" style="margin-top:16px">'+(d.slice((r-1)*c,r*c).map(({e:g,at:f})=>Z(e,g,g.type==="event"?`<span class="ox-st ${g.importance}">${g.importance}</span>`:"",`${f} \xB7 ${g.pages.map(C=>C.agentId).filter((C,x,b)=>b.indexOf(C)===x).join(", ")}`)).join("")||'<div class="ox-empty">None.</div>')+"</section>",m>1){let g=o?`importance=${o}&`:"";w+=`<div class="ox-pager">${r>1?`<a href="${p}?${g}page=${r-1}">\u2190 previous</a>`:""}<span>page ${r} of ${m}</span>${r<m?`<a href="${p}?${g}page=${r+1}">next \u2192</a>`:""}</div>`}return U(s.plural??s.label,O(e,{pillar:i.id}),w)}function dt(e,t){let n=t.trim().toLowerCase(),r=[];if(n)for(let o of e.entities.values()){let i=o.title.toLowerCase(),s=i===n?100:i.startsWith(n)?60:i.includes(n)?40:0;!s&&o.pages.some(l=>l.article.content.toLowerCase().includes(n))&&(s=10),s&&r.push({e:o,s})}r.sort((o,i)=>i.s-o.s||i.e.updated.localeCompare(o.e.updated));let a=`<div class="ox-bar">${N([{label:"Search"}])}</div>`;return a+=`<div class="ox-head"><div class="ox-avatar">${z("search")}</div><div><h1>${n?`\u201C${k(t)}\u201D`:"Search"}</h1><p>${r.length} match${r.length===1?"":"es"}</p></div></div>`,a+=`<section class="ox-card">${r.slice(0,60).map(({e:o})=>Z(e,o)).join("")||'<div class="ox-empty">No page matches.</div>'}</section>`,U(`Search: ${t}`,O(e,{}),a,"",t)}function ct(e,t,n){let r=e.ontology,a=he(e),o=`<div class="ox-bar">${N([{label:"Ontology"}])}</div>`;o+=`<div class="ox-head"><div class="ox-avatar">${z("steps")}</div><div><h1>Ontology</h1><p>${n?`Read from ${k(n)}`:"Built-in defaults. Run <code>agentx wiki ontology init</code> to write an ontology.yaml you can edit."}</p></div></div>`,t.length&&(o+=`<div class="ox-err"><b>Problems</b><ul>${t.map(i=>`<li>${k(i)}</li>`).join("")}</ul></div>`),o+=`<section class="ox-card"><div class="ox-card-h"><h2>Types</h2><span class="note">${r.types.length}</span></div>`;for(let i of r.types){let s=r.pillars.find(l=>l.id===i.pillar);o+=`<div class="ox-row"><span class="ox-ic">${z(i.icon)}</span><div class="t"><span class="l">${k(i.label)} <span class="ox-sub">${k(i.id)}</span></span><div class="ox-sub">${k(s?.label??i.pillar)} \xB7 lens: ${k((i.lens??[]).map(l=>l.title??l.panel).join(" \u2192 "))}</div></div><div class="r"><span class="ox-chip">${a.get(i.id)?.length??0}</span></div></div>`}o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Relations</h2><span class="note">${r.properties.length}</span></div>`;for(let i of r.properties)o+=`<div class="ox-kv"><span class="k">${k(i.id)}</span><span>${k(i.label)}${i.inverse?` \xB7 inverse: ${k(i.inverse)}`:""}${i.wikidata?` <span class="ox-sub">${k(i.wikidata)}</span>`:""}</span></div>`;return o+=`</section><section class="ox-card" style="margin-top:16px"><div class="ox-card-h"><h2>Event importance</h2></div><div class="ox-kv"><span class="k">default</span><span>${k(r.importance.default)}</span></div><div class="ox-kv"><span class="k">major set by</span><span>${k(r.importance.major_set_by)}</span></div><div class="ox-kv"><span class="k">roll-up</span><span>${r.importance.rollup.min} minor events in ${r.importance.rollup.days} days</span></div></section>`,U("Ontology",O(e,{}),o)}var ee=class{constructor(t,n){this.hub=t;this.wikiDir=n}cache=new Ue;pageAt(t){if(!t.startsWith("/e/"))return null;let{ontology:n}=ce(this.wikiDir),a=this.cache.get(this.hub,n).entities.get(t.split("/").filter(Boolean)[1]??"")?.pages[0];return a?{agentId:a.agentId,path:a.article.path,title:a.article.meta.title}:null}handle(t,n){if(!(t==="/"||t===""||t.startsWith("/p/")||t.startsWith("/e/")||t==="/find"||t==="/ontology"))return null;let{ontology:r,errors:a,file:o}=ce(this.wikiDir),i=Oe(this.wikiDir,this.hub.listAgents([]),r.agent_names),s=this.cache.get(this.hub,r,i),l=Math.max(1,Number(n.get("page"))||1);if(t==="/"||t==="")return it(s,a);if(t==="/find")return dt(s,n.get("q")??"");if(t==="/ontology")return ct(s,a,o);let d=t.split("/").filter(Boolean);if(d[0]==="p")return d.length===2?st(s,d[1],n.get("kind")):d.length===3?lt(s,d[1],d[2],l,n.get("importance")):null;let c=s.entities.get(d[1]??"");if(!c)return null;let m={g:s,readEntries:p=>this.hub.getSharedStore().readEntries(p),versions:(p,w)=>this.hub.getAgentWiki(p).getVersions(w)};return d.length===2?He(m,c):d.length===3?qe(m,c,d[2],l):d.length===4&&d[2]==="s"?Fe(m,c,Number(d[3])):null}};var dn=`
|
|
185
185
|
.wc-root{--wc-bg:#fff;--wc-ink:#1b1f1e;--wc-muted:#5d6664;--wc-edge:#d9dedc;--wc-soft:#f3f5f4;--wc-accent:#2f6fde;--wc-on-accent:#fff;--wc-add:#e6f4ea;--wc-add-ink:#1e6b34;--wc-del:#fbe9e9;--wc-del-ink:#9b2c2c;
|
|
186
186
|
font:14px/1.45 'IBM Plex Sans',system-ui,-apple-system,sans-serif;color:var(--wc-ink)}
|
|
187
187
|
[data-theme=dark] .wc-root{--wc-bg:#181c1b;--wc-ink:#e9eeec;--wc-muted:#a3adab;--wc-edge:#2c3331;--wc-soft:#1f2422;--wc-accent:#6b9cff;--wc-on-accent:#0b1020;--wc-add:#173823;--wc-add-ink:#9be3b0;--wc-del:#3b1d1d;--wc-del-ink:#f3a9a9}
|
|
@@ -859,4 +859,4 @@ tr:hover td { background: var(--bg-hover); }
|
|
|
859
859
|
WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
|
|
860
860
|
${r}`).all(t,...n,...a).map(i=>({id:i.id,state:i.state,channel:i.channel,agentId:i.agent_id,text:i.text,createdAt:i.created_at})):[]}function Ta(e,t){return wt(e,t,ae,"ORDER BY created_at")}function Ra(e,t,n=50){return wt(e,t,[...ae,...$e],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}Dt();var we="member:",Mn=90,Nn="members",On="tailscale-user-login",Un=400,Ln=60*60*1e3;function Bn(e){let t=e.scopes.find(n=>n.startsWith(we));return t?t.slice(we.length):null}function At(e,t){if(!e)return null;let n=t.verify(e),r=n?Bn(n):null;return n&&r?{rec:n,personId:r}:null}function Oa(e,t){let n=e.people().find(s=>s.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${we}${n.id}`],expiresInDays:Mn}),{code:o,expiresAt:i}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:i,tokenId:a.id,person:n}}var jn=Math.round(Re/6e4);function Hn(e){return e==="client"?"Your project":"My work"}function Ua(e){let t=Hn(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${De(e.code)}`,` The code works once, for ${jn} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
|
|
861
861
|
`)}var qn="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",Fn="Too many machines are waiting for the owner's answer. Try again later.",$t="That code didn't work. Check it, or ask the person who invited you for a new one.",St=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Ct(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function Gn(e){if(!Ct(e))return null;let t=St(e,On).toLowerCase();return t?t.slice(0,80):null}function Kn(e){let t=e.socket?.remoteAddress||"unknown";if(!Ct(e))return t;let n=St(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function Jn(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function Yn(e){return e.identities.map(Ae).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function La(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(v=>console.log(v)),o=Kn(e),i=t.limiter.retryAfter(o);if(i>0)return a(`[member] pair-code refused from ${o}: locked out for ${i}s more`),{status:429,body:{error:"too many attempts",retryAfter:i},retryAfter:i};let s=null,l="";try{let v=await Y(e,2048);s=v.code,l=Jn(v.machine)}catch{}let d=t.codes.redeem(s),c=d?At(d.token,t.tokens):null;if(await Vn(n,t.minMs??Un),!d||!c)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:$t}};t.limiter.succeed(o);let{rec:m,personId:p}=c,w=t.people().find(v=>v.id===p);if(!w)return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${p} refused from ${o}: person no longer listed`),{status:403,body:{error:$t}};let g=Gn(e),f=Yn(w);if(f.length&&(!g||!f.includes(g)))return t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:`network login ${g??"missing"}; expected ${f.join(" or ")}`}),a(`[member] ${p}: pairing from ${o} refused: the network says "${g??"nobody"}", expected ${f.join(" or ")}`),{status:403,body:{error:qn}};let C=l||"Unnamed machine",x=w.name.slice(0,40),b=_e(t.root,{title:`New machine for ${x}`,ask:`From ${o}, ${g?`network login ${g}`:"no network login reported"}. Machine name, as typed there: "${C}". Let it see ${x}'s own work?`,recommend:`Yes if ${x} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:Nn},{now:r()});return b.ok?(t.members.add({tokenId:m.id,personId:p,name:C,state:"pending",cardId:b.card.id,address:o,...g?{network:g}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:p,device:m.id,event:"paired",address:o,detail:C}),a(`[member] ${p} paired "${C}" from ${o}; waiting for the owner (card ${b.card.id})`),{status:200,body:{person:p,name:C,state:"pending"},token:d.token}):(t.tokens.revoke(m.id),t.members.log({person:p,device:m.id,event:"refused",address:o,detail:b.error}),a(`[member] ${p}: pairing from ${o} refused: ${b.error}`),{status:503,body:{error:Fn}})}var re="this machine is not paired",Xn="waiting for the owner to approve this machine";function It(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function Ba(e,t){return t.state==="pending"&&t.cardId?It(se(e,t.cardId)):null}function ja(e,t,n){let r=t.now??Date.now,a=t.log??(c=>console.log(c)),o=At(e,t.tokens);if(!o)return{ok:!1,status:401,error:re};let{rec:i,personId:s}=o,l=t.members.byToken(i.id);if(!l||l.state==="removed"||l.personId!==s)return{ok:!1,status:401,error:re};if(t.people&&!t.people().some(c=>c.id===s))return Et(t,i.id,"person no longer listed"),a(`[member] ${s}: "${l.name}" ended: person no longer listed`),{ok:!1,status:401,error:re};if(l.state==="pending"){let c=l.cardId?se(t.root,l.cardId):null,m=It(c);if(m==="yes")l=t.members.update(i.id,{state:"active",approvedAt:new Date(r()).toISOString()})??l,t.members.log({person:s,device:i.id,event:"approved",detail:c?.decided_by}),a(`[member] ${s}: "${l.name}" approved`);else if(m==="no"){let p=c?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(i.id),t.members.update(i.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:p}),t.members.log({person:s,device:i.id,event:"refused",detail:p}),a(`[member] ${s}: "${l.name}" refused: ${p}`),{ok:!1,status:401,error:re}}else return{ok:!1,status:403,error:Xn,waiting:!0}}let d=l.lastSeenAt?Date.parse(l.lastSeenAt):0;return n&&(r()-d>=Ln||l.lastAddress!==n)&&(l=t.members.update(i.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??l,t.members.log({person:s,device:i.id,event:"signed-in",address:n})),{ok:!0,device:l,personId:s,rec:i}}function Et(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function Ha(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Et(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Vn(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pt=["gitlab","github"];function Qn(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pt.includes(r))throw new Error(`Request status works on ${Pt.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function Ga(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Ka(e){let{summary:t}=X(n=>Qn(n,e?.channel,!!e?.enabled));return{summary:t}}function Ya(e){return new Set(Object.entries(e).filter(([,t])=>t?.wiki?.absorb?.enabled===!1).map(([t])=>t))}function Xa(e,t){return t.only?{agents:[t.only],skipped:[]}:{agents:e.filter(n=>!t.off.has(n)),skipped:e.filter(n=>t.off.has(n))}}function Va(e,t){return`absorb is off for this agent (agents.${e}.wiki.absorb.enabled); skipped.${e===t?" It reads the wiki notes inbox, so the inbox was not read.":""} Use --agent ${e} to run it anyway.`}function Qa(e,t){if(t){if(!e.wiki?.absorb)return;delete e.wiki.absorb.enabled,Object.keys(e.wiki.absorb).length===0&&delete e.wiki.absorb,Object.keys(e.wiki).length===0&&delete e.wiki;return}e.wiki??={},e.wiki.absorb??={},e.wiki.absorb.enabled=!1}var Zn="https://ntfy.sh";function eo(e){return{enabled:!!e?.enabled,server:e?.server||Zn,topicSet:!!e?.topic,tokenSet:!!e?.token}}function to(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{Xe as a,cr as b,pr as c,ur as d,xr as e,yr as f,tn as g,an as h,me as i,kr as j,wr as k,kt as l,Sa as m,Ca as n,Ir as o,Er as p,Pr as q,Pa as r,Ta as s,Ra as t,Mn as u,Oa as v,jn as w,Hn as x,Ua as y,Kn as z,La as A,Ba as B,ja as C,Et as D,Ha as E,Pt as F,Qn as G,Ga as H,Ka as I,Ya as J,Xa as K,Va as L,Qa as M,eo as N,to as O,Cn as P,Vr as Q,ra as R,aa as S};
|
|
862
|
-
//# sourceMappingURL=chunk-
|
|
862
|
+
//# sourceMappingURL=chunk-SW6HCRLU.js.map
|