agentix-cli 0.143.0 → 0.144.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-UTDCBFZI.js → App-N2U77ED7.js} +2 -2
- package/dist/{ChatApp-7P22XAL2.js → ChatApp-GYVTECF6.js} +2 -2
- package/dist/{absorb-eval-EGO6JJOV.js → absorb-eval-WSAVWCZV.js} +2 -2
- package/dist/{agent-AI6LNZV2.js → agent-SLRGXBMK.js} +2 -2
- package/dist/{board-dashboard-ZKN5Y3GJ.js → board-dashboard-B3T7VCRQ.js} +4 -4
- package/dist/{chunk-SDSSRNSU.js → chunk-2GJFLPS7.js} +3 -3
- package/dist/{chunk-NYWIN4BW.js → chunk-3LAQ74H7.js} +2 -2
- package/dist/{chunk-THWDSPX4.js → chunk-45TKVOJX.js} +2 -2
- package/dist/{chunk-RB5W3FVO.js → chunk-4JHMV3D3.js} +2 -2
- package/dist/{chunk-QSKG754X.js → chunk-5TTHN7DP.js} +12 -8
- package/dist/chunk-5TTHN7DP.js.map +1 -0
- package/dist/{chunk-PYI7ZAU3.js → chunk-BAO77R4L.js} +2 -2
- package/dist/{chunk-YYPTXXCJ.js → chunk-CZWEXRIE.js} +2 -2
- package/dist/{chunk-OMO7UTWW.js → chunk-DFWPTNZ5.js} +2 -2
- package/dist/chunk-DG2DC43E.js +11 -0
- package/dist/chunk-DG2DC43E.js.map +1 -0
- package/dist/chunk-DPIQCHXB.js +62 -0
- package/dist/chunk-DPIQCHXB.js.map +1 -0
- package/dist/{chunk-3WBOWXAN.js → chunk-EX4AREN5.js} +2 -2
- package/dist/{chunk-MFUN3ZS3.js → chunk-GOAMSJ2D.js} +2 -2
- package/dist/{chunk-YVNGPYXN.js → chunk-GWBBWYGM.js} +58 -55
- package/dist/chunk-GWBBWYGM.js.map +1 -0
- package/dist/{chunk-WY5ZOEOE.js → chunk-JGX5IWNX.js} +2 -2
- package/dist/chunk-KV4ZA7FS.js +4 -0
- package/dist/chunk-KV4ZA7FS.js.map +1 -0
- package/dist/{chunk-YXFTUOZR.js → chunk-LLJZMS23.js} +2 -2
- package/dist/{chunk-L4RCA3OC.js → chunk-LVQHNTXV.js} +2 -2
- package/dist/{chunk-UNIXYV3U.js → chunk-M7527M7D.js} +2 -2
- package/dist/{chunk-IABJLTZN.js → chunk-MXWAREAQ.js} +2 -2
- package/dist/{chunk-GB4YT5IG.js → chunk-PJGLIAEP.js} +247 -240
- package/dist/chunk-PJGLIAEP.js.map +1 -0
- package/dist/{chunk-ERG5OUKH.js → chunk-Q73QQPDB.js} +2 -2
- package/dist/{chunk-O2CYERSX.js → chunk-QI4FYJGJ.js} +2 -2
- package/dist/{chunk-HPQ3AAG3.js → chunk-R5VGRKUW.js} +2 -2
- package/dist/{chunk-N2HLL25P.js → chunk-RGBQULXX.js} +2 -2
- package/dist/{chunk-6CTQPGBR.js → chunk-RV4WJZW5.js} +2 -2
- package/dist/{chunk-QVPBSV5Z.js → chunk-SFUNL7RV.js} +2 -2
- package/dist/{chunk-7H6HDN3K.js → chunk-SVNYI6GR.js} +2 -2
- package/dist/{chunk-DKLVB5L6.js → chunk-TTBCXVPJ.js} +6 -6
- package/dist/chunk-TTBCXVPJ.js.map +1 -0
- package/dist/{chunk-XWHD2Z3Z.js → chunk-UII54DAP.js} +2 -2
- package/dist/{chunk-5BXAKMYK.js → chunk-UNZRZOED.js} +2 -2
- package/dist/{chunk-Y4CYQV7G.js → chunk-VY7TBMJU.js} +2 -2
- package/dist/chunk-VY7TBMJU.js.map +1 -0
- package/dist/{chunk-AJUWIBLV.js → chunk-VYLMC5DO.js} +2 -2
- package/dist/{chunk-SHEUCITK.js → chunk-WBG6NA7R.js} +2 -2
- package/dist/{chunk-SHEUCITK.js.map → chunk-WBG6NA7R.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{client-E66ELJK7.js → client-B7FXDTYK.js} +2 -2
- package/dist/config-MLP33NWR.js +2 -0
- package/dist/{config-mutate-QBDKJNHA.js → config-mutate-XQRUAVEH.js} +2 -2
- package/dist/config-mutator-5JFTMQ43.js +2 -0
- package/dist/{contributions-L5XZJ3DP.js → contributions-ESUSYUQG.js} +2 -2
- package/dist/{doctor-3ZUFSE6R.js → doctor-DIYZGSIS.js} +2 -2
- package/dist/{failure-candidates-XZSZP4HT.js → failure-candidates-NQX2JMMS.js} +2 -2
- package/dist/{follow-up-tool-6OCQUSC3.js → follow-up-tool-QXEYEWX7.js} +2 -2
- package/dist/{grants-CEUGZBQ4.js → grants-MM7U6GCK.js} +2 -2
- package/dist/{hub-MOQRSVCQ.js → hub-OC7PH2AR.js} +2 -2
- package/dist/index.d.ts +213 -76
- package/dist/index.js +1 -1
- package/dist/{program-AR6F763U.js → program-LZPM6I2Q.js} +289 -254
- package/dist/program-LZPM6I2Q.js.map +1 -0
- package/dist/{promote-ZGJEPCBE.js → promote-SIC6RWCX.js} +2 -2
- package/dist/{query-JLTHESIZ.js → query-OP2MSR2G.js} +2 -2
- package/dist/{query-settings-GMEL3EKR.js → query-settings-67332F5V.js} +2 -2
- package/dist/{registry-MFD3XJBR.js → registry-G2ZG5TIN.js} +2 -2
- package/dist/{request-planner-4ORFYSAT.js → request-planner-THTPE3FP.js} +2 -2
- package/dist/{review-candidates-77NDFTGM.js → review-candidates-7PS7CHXF.js} +2 -2
- package/dist/{routing-3FL3KYPJ.js → routing-PE7DB7WA.js} +2 -2
- package/dist/schedule-tool-3FXRKJGN.js +2 -0
- package/dist/{scheduler-QLL7ZHYW.js → scheduler-YTXCIQTZ.js} +2 -2
- package/dist/{seat-RBKONP63.js → seat-6DMK4274.js} +2 -2
- package/dist/{select-MOUDR6PQ.js → select-CLDYPAOS.js} +2 -2
- package/dist/{set-enabled-JKYF3QIA.js → set-enabled-ZH2DH4GU.js} +2 -2
- package/dist/tool-4AO3ZMAY.js +6 -0
- package/dist/tool-4AO3ZMAY.js.map +1 -0
- package/dist/{tool-Y3ZTSZGE.js → tool-MKDTKBJ4.js} +3 -3
- package/dist/{tool-Y3ZTSZGE.js.map → tool-MKDTKBJ4.js.map} +1 -1
- package/dist/traces-GVEQZX24.js +2 -0
- package/dist/{wiki-3FSSLQAE.js → wiki-CH2HYJVI.js} +2 -2
- package/dist/wiki-enrich-VEAYFVR2.js +2 -0
- package/dist/wiki-enrich-VEAYFVR2.js.map +1 -0
- package/dist/workflow-pilot-HCPSMGIC.js +2 -0
- package/dist/workflow-pilot-HCPSMGIC.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-3W2BHUGM.js +0 -11
- package/dist/chunk-3W2BHUGM.js.map +0 -1
- package/dist/chunk-AKWBDCMU.js +0 -4
- package/dist/chunk-AKWBDCMU.js.map +0 -1
- package/dist/chunk-DKLVB5L6.js.map +0 -1
- package/dist/chunk-GB4YT5IG.js.map +0 -1
- package/dist/chunk-K22XMF6M.js +0 -62
- package/dist/chunk-K22XMF6M.js.map +0 -1
- package/dist/chunk-QSKG754X.js.map +0 -1
- package/dist/chunk-Y4CYQV7G.js.map +0 -1
- package/dist/chunk-YVNGPYXN.js.map +0 -1
- package/dist/config-3C3Z7VKG.js +0 -2
- package/dist/config-mutator-ZI3SQIUN.js +0 -2
- package/dist/program-AR6F763U.js.map +0 -1
- package/dist/schedule-tool-5KJMXBRZ.js +0 -2
- package/dist/tool-C4JNMTEF.js +0 -6
- package/dist/tool-C4JNMTEF.js.map +0 -1
- package/dist/wiki-enrich-HQWXZRID.js +0 -2
- /package/dist/{App-UTDCBFZI.js.map → App-N2U77ED7.js.map} +0 -0
- /package/dist/{ChatApp-7P22XAL2.js.map → ChatApp-GYVTECF6.js.map} +0 -0
- /package/dist/{absorb-eval-EGO6JJOV.js.map → absorb-eval-WSAVWCZV.js.map} +0 -0
- /package/dist/{agent-AI6LNZV2.js.map → agent-SLRGXBMK.js.map} +0 -0
- /package/dist/{board-dashboard-ZKN5Y3GJ.js.map → board-dashboard-B3T7VCRQ.js.map} +0 -0
- /package/dist/{chunk-SDSSRNSU.js.map → chunk-2GJFLPS7.js.map} +0 -0
- /package/dist/{chunk-NYWIN4BW.js.map → chunk-3LAQ74H7.js.map} +0 -0
- /package/dist/{chunk-THWDSPX4.js.map → chunk-45TKVOJX.js.map} +0 -0
- /package/dist/{chunk-RB5W3FVO.js.map → chunk-4JHMV3D3.js.map} +0 -0
- /package/dist/{chunk-PYI7ZAU3.js.map → chunk-BAO77R4L.js.map} +0 -0
- /package/dist/{chunk-YYPTXXCJ.js.map → chunk-CZWEXRIE.js.map} +0 -0
- /package/dist/{chunk-OMO7UTWW.js.map → chunk-DFWPTNZ5.js.map} +0 -0
- /package/dist/{chunk-3WBOWXAN.js.map → chunk-EX4AREN5.js.map} +0 -0
- /package/dist/{chunk-MFUN3ZS3.js.map → chunk-GOAMSJ2D.js.map} +0 -0
- /package/dist/{chunk-WY5ZOEOE.js.map → chunk-JGX5IWNX.js.map} +0 -0
- /package/dist/{chunk-YXFTUOZR.js.map → chunk-LLJZMS23.js.map} +0 -0
- /package/dist/{chunk-L4RCA3OC.js.map → chunk-LVQHNTXV.js.map} +0 -0
- /package/dist/{chunk-UNIXYV3U.js.map → chunk-M7527M7D.js.map} +0 -0
- /package/dist/{chunk-IABJLTZN.js.map → chunk-MXWAREAQ.js.map} +0 -0
- /package/dist/{chunk-ERG5OUKH.js.map → chunk-Q73QQPDB.js.map} +0 -0
- /package/dist/{chunk-O2CYERSX.js.map → chunk-QI4FYJGJ.js.map} +0 -0
- /package/dist/{chunk-HPQ3AAG3.js.map → chunk-R5VGRKUW.js.map} +0 -0
- /package/dist/{chunk-N2HLL25P.js.map → chunk-RGBQULXX.js.map} +0 -0
- /package/dist/{chunk-6CTQPGBR.js.map → chunk-RV4WJZW5.js.map} +0 -0
- /package/dist/{chunk-QVPBSV5Z.js.map → chunk-SFUNL7RV.js.map} +0 -0
- /package/dist/{chunk-7H6HDN3K.js.map → chunk-SVNYI6GR.js.map} +0 -0
- /package/dist/{chunk-XWHD2Z3Z.js.map → chunk-UII54DAP.js.map} +0 -0
- /package/dist/{chunk-5BXAKMYK.js.map → chunk-UNZRZOED.js.map} +0 -0
- /package/dist/{chunk-AJUWIBLV.js.map → chunk-VYLMC5DO.js.map} +0 -0
- /package/dist/{client-E66ELJK7.js.map → client-B7FXDTYK.js.map} +0 -0
- /package/dist/{config-3C3Z7VKG.js.map → config-MLP33NWR.js.map} +0 -0
- /package/dist/{config-mutate-QBDKJNHA.js.map → config-mutate-XQRUAVEH.js.map} +0 -0
- /package/dist/{config-mutator-ZI3SQIUN.js.map → config-mutator-5JFTMQ43.js.map} +0 -0
- /package/dist/{contributions-L5XZJ3DP.js.map → contributions-ESUSYUQG.js.map} +0 -0
- /package/dist/{doctor-3ZUFSE6R.js.map → doctor-DIYZGSIS.js.map} +0 -0
- /package/dist/{failure-candidates-XZSZP4HT.js.map → failure-candidates-NQX2JMMS.js.map} +0 -0
- /package/dist/{follow-up-tool-6OCQUSC3.js.map → follow-up-tool-QXEYEWX7.js.map} +0 -0
- /package/dist/{grants-CEUGZBQ4.js.map → grants-MM7U6GCK.js.map} +0 -0
- /package/dist/{hub-MOQRSVCQ.js.map → hub-OC7PH2AR.js.map} +0 -0
- /package/dist/{promote-ZGJEPCBE.js.map → promote-SIC6RWCX.js.map} +0 -0
- /package/dist/{query-JLTHESIZ.js.map → query-OP2MSR2G.js.map} +0 -0
- /package/dist/{query-settings-GMEL3EKR.js.map → query-settings-67332F5V.js.map} +0 -0
- /package/dist/{registry-MFD3XJBR.js.map → registry-G2ZG5TIN.js.map} +0 -0
- /package/dist/{request-planner-4ORFYSAT.js.map → request-planner-THTPE3FP.js.map} +0 -0
- /package/dist/{review-candidates-77NDFTGM.js.map → review-candidates-7PS7CHXF.js.map} +0 -0
- /package/dist/{routing-3FL3KYPJ.js.map → routing-PE7DB7WA.js.map} +0 -0
- /package/dist/{schedule-tool-5KJMXBRZ.js.map → schedule-tool-3FXRKJGN.js.map} +0 -0
- /package/dist/{scheduler-QLL7ZHYW.js.map → scheduler-YTXCIQTZ.js.map} +0 -0
- /package/dist/{seat-RBKONP63.js.map → seat-6DMK4274.js.map} +0 -0
- /package/dist/{select-MOUDR6PQ.js.map → select-CLDYPAOS.js.map} +0 -0
- /package/dist/{set-enabled-JKYF3QIA.js.map → set-enabled-ZH2DH4GU.js.map} +0 -0
- /package/dist/{wiki-3FSSLQAE.js.map → traces-GVEQZX24.js.map} +0 -0
- /package/dist/{wiki-enrich-HQWXZRID.js.map → wiki-CH2HYJVI.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-HPQ3AAG3.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
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-R5VGRKUW.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
5
|
`),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-UII54DAP.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{
|
|
1
|
+
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{a as R}from"./chunk-JXF54PT7.js";import{Ka as S,Sa as L}from"./chunk-DPIQCHXB.js";L();import{Command as z}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as T,constants as H,existsSync as y,readFileSync as b,readdirSync as $,statSync as X}from"fs";import{join as E,resolve as m}from"path";import{homedir as B}from"os";import{createRequire as F}from"module";import{execFile as M}from"child_process";var q=(t,n)=>new Promise(e=>{try{M(t,n,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),N="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){if((t.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let n=t.helper===void 0?I():t.helper;if(!n)return{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'};let e=await(t.run??q)(n,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i.authorization==="denied"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:N}:i.alertStyle==="none"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:N}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function J(t={}){let n=[];await Z(n),U(n);let e=K(n);return e&&Q(n,e),e&&Y(n,e),e&&ee(n,e),e&&te(n,e),e&&oe(n,e),e&&await G(n,e),e&&V(n,e),t.running!==!1&&e&&await ie(n,e),{checks:n,summary:W(n)}}var ke=new z().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await J({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):se(n),process.exit(e.errors>0?1:0)});async function G(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function V(t,n,e=process.platform,i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}}){let s=n.reminders;if(!s?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let r=s.command||"remindctl",a=r.includes("/")?i(r)?r:null:x(r,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(s.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${r} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Z(t){let n=R(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return h(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let s=e("claude");if(s){let l;try{l=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let l;try{l=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{F(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function U(t){if(process.platform!=="darwin")return;let n=E(B(),"Library/LaunchAgents"),e=[];try{e=$(n).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return T(s,H.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(E(n,s),"utf-8")),a=x("ffmpeg",r,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${s})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${s} sets PATH to ${r}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function K(t){let n=m(process.cwd(),"agentx.json");if(!y(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function Q(t,n){let e=new Set;if(C(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=m(process.cwd(),".env"),s={};if(y(i))for(let l of b(i,"utf-8").split(/\r?\n/)){let u=l.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);u&&(s[u[1]]=u[2])}let r=[],a=[];for(let l of e){let u=process.env[l]??s[l];u===void 0?r.push(l):(!u.trim()||/^["']?\s*["']?$/.test(u))&&a.push(l)}r.length===0&&a.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&t.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),a.length>0&&t.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)C(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))C(e,n)}function Y(t,n){let e=[];for(let[i,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{X(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function ee(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(n.agents||{})){if(!r.workspace)continue;let a=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let l of["settings.json","settings.local.json"]){let u=m(a,".claude",l);if(!y(u))continue;let w;try{w=JSON.parse(b(u,"utf-8"))}catch(d){i.push({severity:"fail",agent:s,msg:`${l}: JSON parse error \u2014 ${d.message}`});continue}let k=w.env||{};for(let[d,p]of Object.entries(k)){if(typeof p!="string")continue;let g=p.match(e);g&&i.push({severity:"fail",agent:s,msg:`${l} env.${d} contains unexpanded ${[...new Set(g)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let o=k.PATH;if(typeof o=="string"){let d=o.split(":").filter(Boolean);d.includes("/usr/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||i.push({severity:"fail",agent:s,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&i.push({severity:"warn",agent:s,msg:`${l} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)t.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function te(t,n){let e=n.webhooks??[],i=[],s=m(process.cwd(),n.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let o of $(s))o.endsWith(".json")&&!o.startsWith("_")&&!o.endsWith(".disabled.json")&&r.add(o.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let o of e){if(!o.enabled||!a.has(o.source))continue;!(o.triggers&&Object.keys(o.triggers).length>0)&&!o.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${o.id}" (${o.source} -> ${o.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let o of e)if(!(!o.enabled||!o.triggers)){for(let[c,d]of Object.entries(o.triggers))r.size>0&&!r.has(d)&&i.push({severity:"fail",title:`webhook "${o.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});o.defaultWorkflow&&r.size>0&&!r.has(o.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${o.id}".defaultWorkflow -> "${o.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let o of $(s))if(!(!o.endsWith(".json")||o.startsWith("_")||o.endsWith(".disabled.json")))try{let c=JSON.parse(b(m(s,o),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${c.id??o}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(o=>o.name));for(let o of e)!o.enabled||!o.node||l.has(o.node)||i.push({severity:"fail",title:`webhook "${o.id}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let o of e){if(!o.enabled)continue;let c=`${o.source}:${o.agentId}`,d=u.get(c);d?i.push({severity:"warn",title:`webhook entries "${d}" and "${o.id}" both enabled for ${o.source} -> ${o.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(c,o.id)}let w=new Set(Object.keys(n.agents??{}));for(let o of n.channels?.gitlab?.agentMappings??[])if(o?.agentId){if(o.node){l.has(o.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${o.agentId}" routes to mesh peer "${o.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(o.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${o.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[o,c]of Object.entries(n.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||i.push({severity:"fail",title:`telegram account "${o}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${o}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let k=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[o,c]of Object.entries(n.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let g of d){let A=`${g.kind}::${g.label}`;p.has(A)&&i.push({severity:"warn",title:`agents.${o}.integrations: duplicate (${g.kind}, ${g.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(A),k.has(g.kind)||i.push({severity:"warn",title:`agents.${o}.integrations: unknown kind "${g.kind}" on integration "${g.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let D=g.credentials||{};for(let[_,v]of Object.entries(D))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${o}.integrations[${g.kind}/${g.label}].${_} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)t.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function ie(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:s.signal});if(clearTimeout(r),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=ne(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function oe(t,n){let e=Object.entries(n.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=m(r.workspace,".codegraph","codegraph.db");y(a)?t.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function W(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function se(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,s]of n){console.log(f.bold(" "+i));for(let r of s){let a=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
6
|
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=W(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,J as b,ke as c,G as d,V as e,ne as f};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-UNZRZOED.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var n={count:
|
|
1
|
+
var n={count:3,label:120,draft:2e3,say:160,context:600,text:4e3},f="{choice}";function a(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function h(e){return typeof e=="string"?e.replace(/\r\n?/g,`
|
|
2
2
|
`).trim():""}function u(e){let t={};if(e.choices!==void 0&&e.choices!==null){if(!Array.isArray(e.choices))return{ok:!1,error:"choices must be a list of short labels"};let r=e.choices.map(a).filter(Boolean);if(r.length!==e.choices.length)return{ok:!1,error:"every choice must be a non-empty label"};if(r.length>n.count)return{ok:!1,error:`at most ${n.count} choices`};if(r.some(c=>c.length>n.label))return{ok:!1,error:`a choice is longer than ${n.label} characters`};if(new Set(r).size!==r.length)return{ok:!1,error:"choices must be different from each other"};r.length&&(t.choices=r)}let o=h(e.draft);if(o){if(o.length>n.draft)return{ok:!1,error:`draft is longer than ${n.draft} characters`};t.draft=o}let i=a(e.say);if(i){if(i.length>n.say)return{ok:!1,error:`say is longer than ${n.say} characters`};t.say=i}let s=h(e.context);if(s){if(s.length>n.context)return{ok:!1,error:`context is longer than ${n.context} characters`};t.context=s}return{ok:!0,value:t}}function l(e,t){return e?t?e.split(f).join(t):e:""}function g(e,t,o){if(t==="no")return{ok:!0};let i,s=e.choices??[];if(o.choice!==void 0&&o.choice!==""){if(!s.length)return{ok:!1,error:"this card has no choices"};let c=typeof o.choice=="number"?o.choice:Number(o.choice);if(Number.isInteger(c)&&c>=1&&c<=s.length)i=s[c-1];else if(s.includes(a(o.choice)))i=a(o.choice);else return{ok:!1,error:`choice must be 1-${s.length} or one of the labels`}}else if(s.length)return{ok:!1,error:"this card offers choices: pick one (Mac popup, or `agentx approvals approve <key> --choice <n>`)"};let r=h(o.text);return!r&&e.draft&&(r=l(e.draft,i)),r.length>n.text?{ok:!1,error:`text is longer than ${n.text} characters`}:{ok:!0,...i?{choice:i}:{},...r?{text:r}:{}}}function x(e){let t=[];return e.choice&&t.push(`Chosen: ${e.choice}`),e.text&&t.push("Approved text (send exactly this, the operator may have edited it):",e.text),t}export{n as a,f as b,u as c,l as d,g as e,x as f};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-VY7TBMJU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/approvals/choices.ts"],"sourcesContent":["// --- Ready-made answers on a decision card ---\n//\n// A card can offer a few choices (say, three free meeting slots), a\n// suggested message the operator may edit before it goes, and a short\n// context (what the other person said) shown above the question. The operator's\n// pick and the final text are stored on the card and handed to the agent\n// that raised it; the agent does the sending. Nothing here sends anything.\n//\n// All optional: a card without them is the plain yes/no card it always was.\n\nexport const CHOICE_LIMITS = {\n /** Most options a card may offer. More is a form, not a choice; the\n * screen gate (#394) allows 3. */\n count: 3,\n label: 120,\n draft: 2000,\n say: 160,\n context: 600,\n /** The operator's final text, after editing. */\n text: 4000,\n} as const\n\n/** The spot in `draft` that takes the picked label. */\nexport const CHOICE_PLACEHOLDER = \"{choice}\"\n\nexport interface CardChoices {\n choices?: string[]\n draft?: string\n say?: string\n /** A few lines of background, shown above the question. */\n context?: string\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/** A draft keeps its line breaks: it is a message, not a label. */\nfunction block(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\r\\n?/g, \"\\n\").trim() : \"\"\n}\n\n/** Validate what an agent sent. Empty input gives an empty object. */\nexport function buildChoices(input: { choices?: unknown; draft?: unknown; say?: unknown; context?: unknown }): { ok: true; value: CardChoices } | { ok: false; error: string } {\n const value: CardChoices = {}\n if (input.choices !== undefined && input.choices !== null) {\n if (!Array.isArray(input.choices)) return { ok: false, error: \"choices must be a list of short labels\" }\n const labels = input.choices.map(oneLine).filter(Boolean)\n if (labels.length !== input.choices.length) return { ok: false, error: \"every choice must be a non-empty label\" }\n if (labels.length > CHOICE_LIMITS.count) return { ok: false, error: `at most ${CHOICE_LIMITS.count} choices` }\n if (labels.some((l) => l.length > CHOICE_LIMITS.label)) return { ok: false, error: `a choice is longer than ${CHOICE_LIMITS.label} characters` }\n if (new Set(labels).size !== labels.length) return { ok: false, error: \"choices must be different from each other\" }\n if (labels.length) value.choices = labels\n }\n const draft = block(input.draft)\n if (draft) {\n if (draft.length > CHOICE_LIMITS.draft) return { ok: false, error: `draft is longer than ${CHOICE_LIMITS.draft} characters` }\n value.draft = draft\n }\n const say = oneLine(input.say)\n if (say) {\n if (say.length > CHOICE_LIMITS.say) return { ok: false, error: `say is longer than ${CHOICE_LIMITS.say} characters` }\n value.say = say\n }\n const context = block(input.context)\n if (context) {\n if (context.length > CHOICE_LIMITS.context) return { ok: false, error: `context is longer than ${CHOICE_LIMITS.context} characters` }\n value.context = context\n }\n return { ok: true, value }\n}\n\n/** The suggested message for a pick, with `{choice}` filled in. */\nexport function draftFor(draft: string | undefined, choice: string | undefined): string {\n if (!draft) return \"\"\n return choice ? draft.split(CHOICE_PLACEHOLDER).join(choice) : draft\n}\n\n/**\n * Check the operator's answer against the card. A yes on a card with\n * choices must say which one: approving \"the meeting\" without a date would\n * leave the agent to guess, which is the thing the card exists to avoid.\n */\nexport function resolveAnswer(\n card: CardChoices,\n verdict: \"yes\" | \"no\",\n answer: { choice?: string | number; text?: string },\n): { ok: true; choice?: string; text?: string } | { ok: false; error: string } {\n if (verdict === \"no\") return { ok: true }\n let choice: string | undefined\n const list = card.choices ?? []\n if (answer.choice !== undefined && answer.choice !== \"\") {\n if (!list.length) return { ok: false, error: \"this card has no choices\" }\n const n = typeof answer.choice === \"number\" ? answer.choice : Number(answer.choice)\n if (Number.isInteger(n) && n >= 1 && n <= list.length) choice = list[n - 1]\n else if (list.includes(oneLine(answer.choice))) choice = oneLine(answer.choice)\n else return { ok: false, error: `choice must be 1-${list.length} or one of the labels` }\n } else if (list.length) {\n return { ok: false, error: \"this card offers choices: pick one (Mac popup, or `agentx approvals approve <key> --choice <n>`)\" }\n }\n let text = block(answer.text)\n if (!text && card.draft) text = draftFor(card.draft, choice)\n if (text.length > CHOICE_LIMITS.text) return { ok: false, error: `text is longer than ${CHOICE_LIMITS.text} characters` }\n return { ok: true, ...(choice ? { choice } : {}), ...(text ? { text } : {}) }\n}\n\n/** Lines for the agent's result message. Empty for a plain card. */\nexport function answerLines(card: { choice?: string; text?: string }): string[] {\n const lines: string[] = []\n if (card.choice) lines.push(`Chosen: ${card.choice}`)\n if (card.text) lines.push(\"Approved text (send exactly this, the operator may have edited it):\", card.text)\n return lines\n}\n"],"mappings":"AAUO,IAAMA,EAAgB,CAG3B,MAAO,EACP,MAAO,IACP,MAAO,IACP,IAAK,IACL,QAAS,IAET,KAAM,GACR,EAGaC,EAAqB,WAUlC,SAASC,EAAQC,EAAoB,CACnC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAI,EACjE,CAGA,SAASC,EAAMD,EAAoB,CACjC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,SAAU;AAAA,CAAI,EAAE,KAAK,EAAI,EACpE,CAGO,SAASE,EAAaC,EAAkJ,CAC7K,IAAMC,EAAqB,CAAC,EAC5B,GAAID,EAAM,UAAY,QAAaA,EAAM,UAAY,KAAM,CACzD,GAAI,CAAC,MAAM,QAAQA,EAAM,OAAO,EAAG,MAAO,CAAE,GAAI,GAAO,MAAO,wCAAyC,EACvG,IAAME,EAASF,EAAM,QAAQ,IAAIJ,CAAO,EAAE,OAAO,OAAO,EACxD,GAAIM,EAAO,SAAWF,EAAM,QAAQ,OAAQ,MAAO,CAAE,GAAI,GAAO,MAAO,wCAAyC,EAChH,GAAIE,EAAO,OAASR,EAAc,MAAO,MAAO,CAAE,GAAI,GAAO,MAAO,WAAWA,EAAc,eAAgB,EAC7G,GAAIQ,EAAO,KAAMC,GAAMA,EAAE,OAAST,EAAc,KAAK,EAAG,MAAO,CAAE,GAAI,GAAO,MAAO,2BAA2BA,EAAc,kBAAmB,EAC/I,GAAI,IAAI,IAAIQ,CAAM,EAAE,OAASA,EAAO,OAAQ,MAAO,CAAE,GAAI,GAAO,MAAO,2CAA4C,EAC/GA,EAAO,SAAQD,EAAM,QAAUC,GAErC,IAAME,EAAQN,EAAME,EAAM,KAAK,EAC/B,GAAII,EAAO,CACT,GAAIA,EAAM,OAASV,EAAc,MAAO,MAAO,CAAE,GAAI,GAAO,MAAO,wBAAwBA,EAAc,kBAAmB,EAC5HO,EAAM,MAAQG,EAEhB,IAAMC,EAAMT,EAAQI,EAAM,GAAG,EAC7B,GAAIK,EAAK,CACP,GAAIA,EAAI,OAASX,EAAc,IAAK,MAAO,CAAE,GAAI,GAAO,MAAO,sBAAsBA,EAAc,gBAAiB,EACpHO,EAAM,IAAMI,EAEd,IAAMC,EAAUR,EAAME,EAAM,OAAO,EACnC,GAAIM,EAAS,CACX,GAAIA,EAAQ,OAASZ,EAAc,QAAS,MAAO,CAAE,GAAI,GAAO,MAAO,0BAA0BA,EAAc,oBAAqB,EACpIO,EAAM,QAAUK,EAElB,MAAO,CAAE,GAAI,GAAM,MAAAL,CAAM,CAC3B,CAGO,SAASM,EAASH,EAA2BI,EAAoC,CACtF,OAAKJ,EACEI,EAASJ,EAAM,MAAMT,CAAkB,EAAE,KAAKa,CAAM,EAAIJ,EAD5C,EAErB,CAOO,SAASK,EACdC,EACAC,EACAC,EAC6E,CAC7E,GAAID,IAAY,KAAM,MAAO,CAAE,GAAI,EAAK,EACxC,IAAIH,EACEK,EAAOH,EAAK,SAAW,CAAC,EAC9B,GAAIE,EAAO,SAAW,QAAaA,EAAO,SAAW,GAAI,CACvD,GAAI,CAACC,EAAK,OAAQ,MAAO,CAAE,GAAI,GAAO,MAAO,0BAA2B,EACxE,IAAMC,EAAI,OAAOF,EAAO,QAAW,SAAWA,EAAO,OAAS,OAAOA,EAAO,MAAM,EAClF,GAAI,OAAO,UAAUE,CAAC,GAAKA,GAAK,GAAKA,GAAKD,EAAK,OAAQL,EAASK,EAAKC,EAAI,CAAC,UACjED,EAAK,SAASjB,EAAQgB,EAAO,MAAM,CAAC,EAAGJ,EAASZ,EAAQgB,EAAO,MAAM,MACzE,OAAO,CAAE,GAAI,GAAO,MAAO,oBAAoBC,EAAK,6BAA8B,UAC9EA,EAAK,OACd,MAAO,CAAE,GAAI,GAAO,MAAO,kGAAmG,EAEhI,IAAIE,EAAOjB,EAAMc,EAAO,IAAI,EAE5B,MADI,CAACG,GAAQL,EAAK,QAAOK,EAAOR,EAASG,EAAK,MAAOF,CAAM,GACvDO,EAAK,OAASrB,EAAc,KAAa,CAAE,GAAI,GAAO,MAAO,uBAAuBA,EAAc,iBAAkB,EACjH,CAAE,GAAI,GAAM,GAAIc,EAAS,CAAE,OAAAA,CAAO,EAAI,CAAC,EAAI,GAAIO,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,CAAG,CAC9E,CAGO,SAASC,EAAYN,EAAoD,CAC9E,IAAMO,EAAkB,CAAC,EACzB,OAAIP,EAAK,QAAQO,EAAM,KAAK,WAAWP,EAAK,QAAQ,EAChDA,EAAK,MAAMO,EAAM,KAAK,sEAAuEP,EAAK,IAAI,EACnGO,CACT","names":["CHOICE_LIMITS","CHOICE_PLACEHOLDER","oneLine","v","block","buildChoices","input","value","labels","l","draft","say","context","draftFor","choice","resolveAnswer","card","verdict","answer","list","n","text","answerLines","lines"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-JGX5IWNX.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-SFUNL7RV.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
2
|
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-VYLMC5DO.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as i}from"fs";import{homedir as c}from"os";import{join as u}from"path";var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{readFileSync as i}from"fs";import{homedir as c}from"os";import{join as u}from"path";var l=u(c(),"Library","DoNotDisturb","DB","Assertions.json"),d=u(c(),".agentx","focus.json");function S(e=l,t=d){let r=f(t);return r.active?r:m(e)}function f(e=d){try{if(JSON.parse(i(e,"utf-8"))?.active===!0)return{active:!0,mode:"widget",reason:"holding \u2014 switched on from the widget"}}catch{}return{active:!1,mode:null,reason:"widget hold is off"}}function m(e=l){let t;try{t=i(e,"utf-8")}catch(s){return s?.code==="EPERM"||s?.code==="EACCES"?{active:!1,mode:null,reason:"Focus database not readable \u2014 grant Full Disk Access to the app running agentx"}:{active:!1,mode:null,reason:"no Focus database on this machine"}}let r;try{r=JSON.parse(t)}catch{return{active:!1,mode:null,reason:"Focus database was not readable JSON"}}let n=(Array.isArray(r?.data)?r.data[0]:null)?.storeAssertionRecords;if(!Array.isArray(n)||n.length===0)return{active:!1,mode:null,reason:"no active Focus assertion"};let a=n[0],o=a?.assertionDetails?.assertionDetailsModeIdentifier??a?.assertionDetails?.assertionDetailsModeID??null;return{active:!0,mode:typeof o=="string"?o:null,reason:`Focus assertion present${o?` (${o})`:""}`}}function y(e){return e.active?e.mode==="widget"?"holding (widget)":e.mode==="call"?"in a call":e.mode?`in ${(e.mode.split(".").pop()??e.mode).replace(/-/g," ")}`:"in Focus":"not in Focus"}export{S as a,y as b};
|
|
2
|
+
//# sourceMappingURL=chunk-WBG6NA7R.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notify/focus.ts"],"sourcesContent":["import { readFileSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { join } from \"path\"\n\n// Is the person currently in Do Not Disturb / a Focus mode?\n//\n// macOS keeps the answer in a JSON file rather than behind an API a\n// non-sandboxed CLI can reach. An ACTIVE focus appears as an entry under\n// `data[0].storeAssertionRecords`; when nothing is active the key is not\n// merely empty, it is absent, and the file instead holds the invalidation\n// records for the focus that was just switched off.\n//\n// Verified on this machine at both ends:\n//\n// focus off data[0] = { storeInvalidationRequestRecords,\n// storeInvalidationRecords } (no assertions)\n// focus on data[0] gains storeAssertionRecords with one entry per\n// active mode\n//\n// Reading a private file is a compromise and it is worth naming. The\n// alternative is to ignore Focus entirely and interrupt someone who has\n// explicitly asked not to be, which is worse. The failure mode is chosen\n// to match: anything unexpected — file missing, shape changed after an OS\n// update, unreadable — is reported as NOT in focus, so notifications keep\n// flowing. A notification that arrives during Focus is a small annoyance;\n// one that is swallowed forever because a file moved is a broken feature.\n\nexport interface FocusState {\n /** True when a Focus / Do Not Disturb mode is on. */\n active: boolean\n /** The mode's identifier when macOS names one, e.g. com.apple.sleep.sleep-mode. */\n mode: string | null\n /** Why we believe this — recorded so a wrong answer is diagnosable. */\n reason: string\n}\n\nconst ASSERTIONS = join(homedir(), \"Library\", \"DoNotDisturb\", \"DB\", \"Assertions.json\")\n\n/** Where the widget records a hold the person switched on themselves. */\nconst WIDGET_HOLD = join(homedir(), \".agentx\", \"focus.json\")\n\n/**\n * Focus, from either source: the widget's own toggle or the system's.\n *\n * The widget toggle exists because macOS Focus is a heavy instrument —\n * turning it on silences everything on every device, which is more than\n * someone wants when they only mean \"let me finish this\". A switch on the\n * widget is a hold you can flick on for twenty minutes without negotiating\n * with the operating system.\n *\n * Either source being on is enough. They are not ranked: both are the\n * same person saying the same thing by different means, and a rule that\n * let one override the other would mean ignoring an explicit instruction\n * because it arrived through the wrong switch.\n */\nexport function readFocus(path = ASSERTIONS, holdPath = WIDGET_HOLD): FocusState {\n const held = readWidgetHold(holdPath)\n if (held.active) return held\n return readSystemFocus(path)\n}\n\n/** The widget's own toggle. Absent file means not held. */\nexport function readWidgetHold(path = WIDGET_HOLD): FocusState {\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\"))\n if (parsed?.active === true) {\n return { active: true, mode: \"widget\", reason: \"holding — switched on from the widget\" }\n }\n } catch {\n /* no file, or unreadable: not held */\n }\n return { active: false, mode: null, reason: \"widget hold is off\" }\n}\n\nexport function readSystemFocus(path = ASSERTIONS): FocusState {\n let raw: string\n try {\n raw = readFileSync(path, \"utf-8\")\n } catch (e: any) {\n // The file exists on every recent macOS but is private: without Full\n // Disk Access for the process reading it, the answer is \"denied\", and\n // saying so is the difference between a fixable setup and a mystery.\n if (e?.code === \"EPERM\" || e?.code === \"EACCES\") {\n return { active: false, mode: null, reason: \"Focus database not readable — grant Full Disk Access to the app running agentx\" }\n }\n return { active: false, mode: null, reason: \"no Focus database on this machine\" }\n }\n\n let parsed: any\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { active: false, mode: null, reason: \"Focus database was not readable JSON\" }\n }\n\n const record = Array.isArray(parsed?.data) ? parsed.data[0] : null\n const assertions = record?.storeAssertionRecords\n if (!Array.isArray(assertions) || assertions.length === 0) {\n return { active: false, mode: null, reason: \"no active Focus assertion\" }\n }\n\n // The mode identifier lives a few levels down and its exact path has\n // moved between OS versions, so it is treated as a nicety: the presence\n // of the assertion is what decides, the name only improves the message.\n const first = assertions[0]\n const mode =\n first?.assertionDetails?.assertionDetailsModeIdentifier ??\n first?.assertionDetails?.assertionDetailsModeID ??\n null\n\n return {\n active: true,\n mode: typeof mode === \"string\" ? mode : null,\n reason: `Focus assertion present${mode ? ` (${mode})` : \"\"}`,\n }\n}\n\n/** A short phrase for logs and for telling someone why a message waited. */\nexport function focusLabel(state: FocusState): string {\n if (!state.active) return \"not in Focus\"\n if (state.mode === \"widget\") return \"holding (widget)\"\n if (!state.mode) return \"in Focus\"\n // com.apple.sleep.sleep-mode -> sleep mode\n const tail = state.mode.split(\".\").pop() ?? state.mode\n return `in ${tail.replace(/-/g, \" \")}`\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,MAAoB,KAC7B,OAAS,WAAAC,MAAe,KACxB,OAAS,QAAAC,MAAY,OAkCrB,IAAMC,EAAaD,EAAKD,EAAQ,EAAG,UAAW,eAAgB,KAAM,iBAAiB,EAG/EG,EAAcF,EAAKD,EAAQ,EAAG,UAAW,YAAY,EAgBpD,SAASI,EAAUC,EAAOH,EAAYI,EAAWH,EAAyB,CAC/E,IAAMI,EAAOC,EAAeF,CAAQ,EACpC,OAAIC,EAAK,OAAeA,EACjBE,EAAgBJ,CAAI,CAC7B,CAGO,SAASG,EAAeH,EAAOF,EAAyB,CAC7D,GAAI,CAEF,GADe,KAAK,MAAMJ,EAAaM,EAAM,OAAO,CAAC,GACzC,SAAW,GACrB,MAAO,CAAE,OAAQ,GAAM,KAAM,SAAU,OAAQ,4CAAwC,CAE3F,MAAE,CAEF,CACA,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,oBAAqB,CACnE,CAEO,SAASI,EAAgBJ,EAAOH,EAAwB,CAC7D,IAAIQ,EACJ,GAAI,CACFA,EAAMX,EAAaM,EAAM,OAAO,CAClC,OAASM,EAAP,CAIA,OAAIA,GAAG,OAAS,SAAWA,GAAG,OAAS,SAC9B,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,qFAAiF,EAExH,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,mCAAoC,CAClF,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAS,KAAK,MAAMF,CAAG,CACzB,MAAE,CACA,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,sCAAuC,CACrF,CAGA,IAAMG,GADS,MAAM,QAAQD,GAAQ,IAAI,EAAIA,EAAO,KAAK,CAAC,EAAI,OACnC,sBAC3B,GAAI,CAAC,MAAM,QAAQC,CAAU,GAAKA,EAAW,SAAW,EACtD,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,2BAA4B,EAM1E,IAAMC,EAAQD,EAAW,CAAC,EACpBE,EACJD,GAAO,kBAAkB,gCACzBA,GAAO,kBAAkB,wBACzB,KAEF,MAAO,CACL,OAAQ,GACR,KAAM,OAAOC,GAAS,SAAWA,EAAO,KACxC,OAAQ,0BAA0BA,EAAO,KAAKA,KAAU,IAC1D,CACF,CAGO,SAASC,EAAWC,EAA2B,CACpD,OAAKA,EAAM,OACPA,EAAM,OAAS,SAAiB,
|
|
1
|
+
{"version":3,"sources":["../src/notify/focus.ts"],"sourcesContent":["import { readFileSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { join } from \"path\"\n\n// Is the person currently in Do Not Disturb / a Focus mode?\n//\n// macOS keeps the answer in a JSON file rather than behind an API a\n// non-sandboxed CLI can reach. An ACTIVE focus appears as an entry under\n// `data[0].storeAssertionRecords`; when nothing is active the key is not\n// merely empty, it is absent, and the file instead holds the invalidation\n// records for the focus that was just switched off.\n//\n// Verified on this machine at both ends:\n//\n// focus off data[0] = { storeInvalidationRequestRecords,\n// storeInvalidationRecords } (no assertions)\n// focus on data[0] gains storeAssertionRecords with one entry per\n// active mode\n//\n// Reading a private file is a compromise and it is worth naming. The\n// alternative is to ignore Focus entirely and interrupt someone who has\n// explicitly asked not to be, which is worse. The failure mode is chosen\n// to match: anything unexpected — file missing, shape changed after an OS\n// update, unreadable — is reported as NOT in focus, so notifications keep\n// flowing. A notification that arrives during Focus is a small annoyance;\n// one that is swallowed forever because a file moved is a broken feature.\n\nexport interface FocusState {\n /** True when a Focus / Do Not Disturb mode is on. */\n active: boolean\n /** The mode's identifier when macOS names one, e.g. com.apple.sleep.sleep-mode. */\n mode: string | null\n /** Why we believe this — recorded so a wrong answer is diagnosable. */\n reason: string\n}\n\nconst ASSERTIONS = join(homedir(), \"Library\", \"DoNotDisturb\", \"DB\", \"Assertions.json\")\n\n/** Where the widget records a hold the person switched on themselves. */\nconst WIDGET_HOLD = join(homedir(), \".agentx\", \"focus.json\")\n\n/**\n * Focus, from either source: the widget's own toggle or the system's.\n *\n * The widget toggle exists because macOS Focus is a heavy instrument —\n * turning it on silences everything on every device, which is more than\n * someone wants when they only mean \"let me finish this\". A switch on the\n * widget is a hold you can flick on for twenty minutes without negotiating\n * with the operating system.\n *\n * Either source being on is enough. They are not ranked: both are the\n * same person saying the same thing by different means, and a rule that\n * let one override the other would mean ignoring an explicit instruction\n * because it arrived through the wrong switch.\n */\nexport function readFocus(path = ASSERTIONS, holdPath = WIDGET_HOLD): FocusState {\n const held = readWidgetHold(holdPath)\n if (held.active) return held\n return readSystemFocus(path)\n}\n\n/** The widget's own toggle. Absent file means not held. */\nexport function readWidgetHold(path = WIDGET_HOLD): FocusState {\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf-8\"))\n if (parsed?.active === true) {\n return { active: true, mode: \"widget\", reason: \"holding — switched on from the widget\" }\n }\n } catch {\n /* no file, or unreadable: not held */\n }\n return { active: false, mode: null, reason: \"widget hold is off\" }\n}\n\nexport function readSystemFocus(path = ASSERTIONS): FocusState {\n let raw: string\n try {\n raw = readFileSync(path, \"utf-8\")\n } catch (e: any) {\n // The file exists on every recent macOS but is private: without Full\n // Disk Access for the process reading it, the answer is \"denied\", and\n // saying so is the difference between a fixable setup and a mystery.\n if (e?.code === \"EPERM\" || e?.code === \"EACCES\") {\n return { active: false, mode: null, reason: \"Focus database not readable — grant Full Disk Access to the app running agentx\" }\n }\n return { active: false, mode: null, reason: \"no Focus database on this machine\" }\n }\n\n let parsed: any\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { active: false, mode: null, reason: \"Focus database was not readable JSON\" }\n }\n\n const record = Array.isArray(parsed?.data) ? parsed.data[0] : null\n const assertions = record?.storeAssertionRecords\n if (!Array.isArray(assertions) || assertions.length === 0) {\n return { active: false, mode: null, reason: \"no active Focus assertion\" }\n }\n\n // The mode identifier lives a few levels down and its exact path has\n // moved between OS versions, so it is treated as a nicety: the presence\n // of the assertion is what decides, the name only improves the message.\n const first = assertions[0]\n const mode =\n first?.assertionDetails?.assertionDetailsModeIdentifier ??\n first?.assertionDetails?.assertionDetailsModeID ??\n null\n\n return {\n active: true,\n mode: typeof mode === \"string\" ? mode : null,\n reason: `Focus assertion present${mode ? ` (${mode})` : \"\"}`,\n }\n}\n\n/** A short phrase for logs and for telling someone why a message waited. */\nexport function focusLabel(state: FocusState): string {\n if (!state.active) return \"not in Focus\"\n if (state.mode === \"widget\") return \"holding (widget)\"\n if (state.mode === \"call\") return \"in a call\"\n if (!state.mode) return \"in Focus\"\n // com.apple.sleep.sleep-mode -> sleep mode\n const tail = state.mode.split(\".\").pop() ?? state.mode\n return `in ${tail.replace(/-/g, \" \")}`\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,MAAoB,KAC7B,OAAS,WAAAC,MAAe,KACxB,OAAS,QAAAC,MAAY,OAkCrB,IAAMC,EAAaD,EAAKD,EAAQ,EAAG,UAAW,eAAgB,KAAM,iBAAiB,EAG/EG,EAAcF,EAAKD,EAAQ,EAAG,UAAW,YAAY,EAgBpD,SAASI,EAAUC,EAAOH,EAAYI,EAAWH,EAAyB,CAC/E,IAAMI,EAAOC,EAAeF,CAAQ,EACpC,OAAIC,EAAK,OAAeA,EACjBE,EAAgBJ,CAAI,CAC7B,CAGO,SAASG,EAAeH,EAAOF,EAAyB,CAC7D,GAAI,CAEF,GADe,KAAK,MAAMJ,EAAaM,EAAM,OAAO,CAAC,GACzC,SAAW,GACrB,MAAO,CAAE,OAAQ,GAAM,KAAM,SAAU,OAAQ,4CAAwC,CAE3F,MAAE,CAEF,CACA,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,oBAAqB,CACnE,CAEO,SAASI,EAAgBJ,EAAOH,EAAwB,CAC7D,IAAIQ,EACJ,GAAI,CACFA,EAAMX,EAAaM,EAAM,OAAO,CAClC,OAASM,EAAP,CAIA,OAAIA,GAAG,OAAS,SAAWA,GAAG,OAAS,SAC9B,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,qFAAiF,EAExH,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,mCAAoC,CAClF,CAEA,IAAIC,EACJ,GAAI,CACFA,EAAS,KAAK,MAAMF,CAAG,CACzB,MAAE,CACA,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,sCAAuC,CACrF,CAGA,IAAMG,GADS,MAAM,QAAQD,GAAQ,IAAI,EAAIA,EAAO,KAAK,CAAC,EAAI,OACnC,sBAC3B,GAAI,CAAC,MAAM,QAAQC,CAAU,GAAKA,EAAW,SAAW,EACtD,MAAO,CAAE,OAAQ,GAAO,KAAM,KAAM,OAAQ,2BAA4B,EAM1E,IAAMC,EAAQD,EAAW,CAAC,EACpBE,EACJD,GAAO,kBAAkB,gCACzBA,GAAO,kBAAkB,wBACzB,KAEF,MAAO,CACL,OAAQ,GACR,KAAM,OAAOC,GAAS,SAAWA,EAAO,KACxC,OAAQ,0BAA0BA,EAAO,KAAKA,KAAU,IAC1D,CACF,CAGO,SAASC,EAAWC,EAA2B,CACpD,OAAKA,EAAM,OACPA,EAAM,OAAS,SAAiB,mBAChCA,EAAM,OAAS,OAAe,YAC7BA,EAAM,KAGJ,OADMA,EAAM,KAAK,MAAM,GAAG,EAAE,IAAI,GAAKA,EAAM,MAChC,QAAQ,KAAM,GAAG,IAHX,WAHE,cAO5B","names":["readFileSync","homedir","join","ASSERTIONS","WIDGET_HOLD","readFocus","path","holdPath","held","readWidgetHold","readSystemFocus","raw","e","parsed","assertions","first","mode","focusLabel","state"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-LZPM6I2Q.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-SVNYI6GR.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-B7FXDTYK.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Aa as g,Ba as h,Ca as i,Da as j,Ea as k,Fa as l,Ga as m,Ha as n,Ia as o,Ja as p,Ka as q,La as r,Ma as s,Na as t,Oa as u,Pa as v,Qa as w,Sa as x,ua as a,va as b,wa as c,xa as d,ya as e,za as f}from"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";x();export{a as INTEGRATION_KINDS,s as WIKI_CONTRIBUTE_JOB,t as WIKI_CONTRIBUTE_MERGE_JOB,v as WIKI_SUMMARIZE_JOB,n as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,o as daemonConfigSchema,b as eventSubscriptionSchema,p as expandEnvVars,d as isCronExpression,q as loadDaemonConfig,k as membersConfigSchema,j as peopleConfigSchema,i as personSchema,m as qualityReportConfigSchema,l as requestStatusConfigSchema,h as requestsConfigSchema,f as reviewGateConfigSchema,r as validateWorkspaces,g as watchersConfigSchema,u as withContributionJobs,w as withSummariesJob};
|
|
2
|
+
//# sourceMappingURL=config-MLP33NWR.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-mutate-
|
|
1
|
+
import{a,b}from"./chunk-CZWEXRIE.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-XQRUAVEH.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-SFUNL7RV.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-5JFTMQ43.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-
|
|
1
|
+
import{a as ee}from"./chunk-EX4AREN5.js";import"./chunk-DFWPTNZ5.js";import{f as Q,k as V}from"./chunk-5TTHN7DP.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-2GJFLPS7.js";import"./chunk-SKSYII3K.js";import"./chunk-UII54DAP.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-R5VGRKUW.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
3
|
${k.join(`
|
|
4
4
|
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
|
|
|
54
54
|
`).replace(/\n{3,}/g,`
|
|
55
55
|
|
|
56
56
|
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
-
//# sourceMappingURL=contributions-
|
|
57
|
+
//# sourceMappingURL=contributions-ESUSYUQG.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-UNZRZOED.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-DIYZGSIS.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=failure-candidates-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-LLJZMS23.js";import"./chunk-5TTHN7DP.js";import"./chunk-FCPTN6NF.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_MIN_SESSIONS,a as FAILURE_STAMP_PREFIX,c as MAX_FAILURE_EXAMPLES,d as errorClass,i as failingTool,e as failureSignature,f as failureStamp,j as failuresToCandidates,h as loadFailedTraces,g as sessionOf};
|
|
2
|
+
//# sourceMappingURL=failure-candidates-NQX2JMMS.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-VYLMC5DO.js";import"./chunk-RKPAVWXF.js";import{b as I}from"./chunk-DG2DC43E.js";import"./chunk-WBG6NA7R.js";import"./chunk-JGX5IWNX.js";import"./chunk-3LAQ74H7.js";import"./chunk-SFUNL7RV.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
|
|
2
2
|
`)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
3
|
`)).join(`
|
|
4
4
|
`):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
5
|
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
|
|
6
6
|
`):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
7
|
-
//# sourceMappingURL=follow-up-tool-
|
|
7
|
+
//# sourceMappingURL=follow-up-tool-QXEYEWX7.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=grants-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-M7527M7D.js";import"./chunk-KV4ZA7FS.js";import"./chunk-VY7TBMJU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{c as DEFAULT_GRANT_DAYS,a as GUEST_SCOPE_PREFIX,b as JOIN_CARD_BY,h as JOIN_FAILED,d as MAX_GRANT_DAYS,j as NO_GRANT,l as PAUSED,k as WAITING_HOST,s as endGrant,o as grantBrief,u as grantForGuest,e as grantIdOf,n as guestAccess,p as guestTask,g as inviteGuest,i as joinGuest,f as newGrantId,q as pauseGrant,r as resumeGrant,m as settleGrant,t as updateGrant};
|
|
2
|
+
//# sourceMappingURL=grants-MM7U6GCK.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=hub-
|
|
1
|
+
import{a}from"./chunk-Q73QQPDB.js";import"./chunk-RV4WJZW5.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-UII54DAP.js";import"./chunk-WPNRDEHW.js";import"./chunk-R5VGRKUW.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DPIQCHXB.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
|
|
2
|
+
//# sourceMappingURL=hub-OC7PH2AR.js.map
|