agentix-cli 0.75.2 → 0.76.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/README.md +21 -6
- package/dist/{App-N2ZWRJKV.js → App-NCTXMA2P.js} +2 -2
- package/dist/{ChatApp-PGQKQBHF.js → ChatApp-CQIQEKZ2.js} +2 -2
- package/dist/{agent-B46X7Y6V.js → agent-5GQLISLJ.js} +2 -2
- package/dist/{board-dashboard-W64VXH6Y.js → board-dashboard-E4CXJUK5.js} +5 -4
- package/dist/board-dashboard-E4CXJUK5.js.map +1 -0
- package/dist/{chunk-6CCJMHBA.js → chunk-2KOWJNQJ.js} +2 -2
- package/dist/{chunk-TS4JCBSP.js → chunk-676OIOHG.js} +30 -30
- package/dist/chunk-676OIOHG.js.map +1 -0
- package/dist/{chunk-NWL5KPBJ.js → chunk-72P53PGX.js} +2 -2
- package/dist/{chunk-663BLK67.js → chunk-7GC42WAK.js} +32 -32
- package/dist/chunk-7GC42WAK.js.map +1 -0
- package/dist/{chunk-S5JGQKON.js → chunk-A4ACRRRP.js} +2 -2
- package/dist/{chunk-JGEHN4VE.js → chunk-B556VD7A.js} +2 -2
- package/dist/{chunk-PUU2ESI2.js → chunk-CW42OBFL.js} +2 -2
- package/dist/{chunk-Q2FFZX7Y.js → chunk-EAMSULHF.js} +2 -2
- package/dist/{chunk-KIXYU2DD.js → chunk-GT6ZDLXU.js} +197 -189
- package/dist/chunk-GT6ZDLXU.js.map +1 -0
- package/dist/{chunk-UJ5JLS6Z.js → chunk-IYLQBBON.js} +2 -2
- package/dist/{chunk-CUXYJNWT.js → chunk-LQ3PEMBH.js} +2 -2
- package/dist/{chunk-55RM7V4N.js → chunk-MODPTVA6.js} +2 -2
- package/dist/chunk-N3Y3NORE.js +7 -0
- package/dist/chunk-N3Y3NORE.js.map +1 -0
- package/dist/{chunk-PBUJBWOF.js → chunk-P27P7GFY.js} +5 -5
- package/dist/{chunk-KHEI4VNM.js → chunk-PDSCFOC4.js} +2 -2
- package/dist/{chunk-F2RIMHW5.js → chunk-PK6EBDBU.js} +2 -2
- package/dist/{chunk-2HMI5PJG.js → chunk-QGTQ4PIL.js} +2 -2
- package/dist/chunk-R5BXA7TL.js +3 -0
- package/dist/chunk-R5BXA7TL.js.map +1 -0
- package/dist/{chunk-BYJ3A55Y.js → chunk-S2GAEH2F.js} +2 -2
- package/dist/{chunk-IR2Q63IV.js → chunk-SC6Q5M4C.js} +2 -2
- package/dist/{chunk-RGTHA2EI.js → chunk-SY7ENNNK.js} +2 -2
- package/dist/{chunk-CXZ4YDHJ.js → chunk-SZZSUW42.js} +2 -2
- package/dist/{chunk-CXZ4YDHJ.js.map → chunk-SZZSUW42.js.map} +1 -1
- package/dist/{chunk-7ZO2UZRI.js → chunk-URINHGJF.js} +233 -233
- package/dist/chunk-URINHGJF.js.map +1 -0
- package/dist/{chunk-CAVAMWI5.js → chunk-ZPM7SSJM.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-HLCKITQJ.js +2 -0
- package/dist/{config-A23CU2XT.js → config-QLCPWIJN.js} +2 -2
- package/dist/config-mutator-BCTMKRPT.js +2 -0
- package/dist/doctor-74P5CWVW.js +2 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/program-ONWCNXKS.js +2 -0
- package/dist/{promote-PMMUU4G2.js → promote-VFL66JD2.js} +2 -2
- package/dist/{query-CB6FV6JU.js → query-MCCWN6XA.js} +2 -2
- package/dist/{registry-A2LPURNS.js → registry-43X3DQTI.js} +2 -2
- package/dist/{request-planner-44WOTYCY.js → request-planner-GSGBUGNG.js} +2 -2
- package/dist/{review-candidates-BZLS37MN.js → review-candidates-4Z6QTMN2.js} +2 -2
- package/dist/{routing-CPLPRA2E.js → routing-T66LO3JY.js} +2 -2
- package/dist/schedule-tool-ORNG6HMN.js +2 -0
- package/dist/scheduler-VIWJITKR.js +2 -0
- package/dist/{seat-CBAZAYGY.js → seat-4H7TTV5X.js} +2 -2
- package/dist/{select-4CW3CXBU.js → select-YCVNOR5Q.js} +2 -2
- package/dist/{set-enabled-QNSLVBGT.js → set-enabled-6UGUPYW4.js} +2 -2
- package/dist/tool-EID3ZKQK.js +4 -0
- package/dist/tool-EID3ZKQK.js.map +1 -0
- package/dist/wiki-SHHIVZPT.js +2 -0
- package/package.json +2 -2
- package/dist/board-dashboard-W64VXH6Y.js.map +0 -1
- package/dist/chunk-663BLK67.js.map +0 -1
- package/dist/chunk-7ZO2UZRI.js.map +0 -1
- package/dist/chunk-GZAGG3ES.js +0 -7
- package/dist/chunk-GZAGG3ES.js.map +0 -1
- package/dist/chunk-KIXYU2DD.js.map +0 -1
- package/dist/chunk-TS4JCBSP.js.map +0 -1
- package/dist/client-5DVNJ4VZ.js +0 -2
- package/dist/config-mutator-WDZ6F6Q4.js +0 -2
- package/dist/doctor-MVV47YVK.js +0 -2
- package/dist/program-3DBXC6DX.js +0 -2
- package/dist/schedule-tool-4I3QUXJK.js +0 -2
- package/dist/scheduler-LJ32FB5N.js +0 -2
- package/dist/tool-544FGIJK.js +0 -2
- package/dist/tool-544FGIJK.js.map +0 -1
- package/dist/wiki-4LKOLCP4.js +0 -2
- /package/dist/{App-N2ZWRJKV.js.map → App-NCTXMA2P.js.map} +0 -0
- /package/dist/{ChatApp-PGQKQBHF.js.map → ChatApp-CQIQEKZ2.js.map} +0 -0
- /package/dist/{agent-B46X7Y6V.js.map → agent-5GQLISLJ.js.map} +0 -0
- /package/dist/{chunk-6CCJMHBA.js.map → chunk-2KOWJNQJ.js.map} +0 -0
- /package/dist/{chunk-NWL5KPBJ.js.map → chunk-72P53PGX.js.map} +0 -0
- /package/dist/{chunk-S5JGQKON.js.map → chunk-A4ACRRRP.js.map} +0 -0
- /package/dist/{chunk-JGEHN4VE.js.map → chunk-B556VD7A.js.map} +0 -0
- /package/dist/{chunk-PUU2ESI2.js.map → chunk-CW42OBFL.js.map} +0 -0
- /package/dist/{chunk-Q2FFZX7Y.js.map → chunk-EAMSULHF.js.map} +0 -0
- /package/dist/{chunk-UJ5JLS6Z.js.map → chunk-IYLQBBON.js.map} +0 -0
- /package/dist/{chunk-CUXYJNWT.js.map → chunk-LQ3PEMBH.js.map} +0 -0
- /package/dist/{chunk-55RM7V4N.js.map → chunk-MODPTVA6.js.map} +0 -0
- /package/dist/{chunk-PBUJBWOF.js.map → chunk-P27P7GFY.js.map} +0 -0
- /package/dist/{chunk-KHEI4VNM.js.map → chunk-PDSCFOC4.js.map} +0 -0
- /package/dist/{chunk-F2RIMHW5.js.map → chunk-PK6EBDBU.js.map} +0 -0
- /package/dist/{chunk-2HMI5PJG.js.map → chunk-QGTQ4PIL.js.map} +0 -0
- /package/dist/{chunk-BYJ3A55Y.js.map → chunk-S2GAEH2F.js.map} +0 -0
- /package/dist/{chunk-IR2Q63IV.js.map → chunk-SC6Q5M4C.js.map} +0 -0
- /package/dist/{chunk-RGTHA2EI.js.map → chunk-SY7ENNNK.js.map} +0 -0
- /package/dist/{chunk-CAVAMWI5.js.map → chunk-ZPM7SSJM.js.map} +0 -0
- /package/dist/{client-5DVNJ4VZ.js.map → client-HLCKITQJ.js.map} +0 -0
- /package/dist/{config-A23CU2XT.js.map → config-QLCPWIJN.js.map} +0 -0
- /package/dist/{config-mutator-WDZ6F6Q4.js.map → config-mutator-BCTMKRPT.js.map} +0 -0
- /package/dist/{doctor-MVV47YVK.js.map → doctor-74P5CWVW.js.map} +0 -0
- /package/dist/{program-3DBXC6DX.js.map → program-ONWCNXKS.js.map} +0 -0
- /package/dist/{promote-PMMUU4G2.js.map → promote-VFL66JD2.js.map} +0 -0
- /package/dist/{query-CB6FV6JU.js.map → query-MCCWN6XA.js.map} +0 -0
- /package/dist/{registry-A2LPURNS.js.map → registry-43X3DQTI.js.map} +0 -0
- /package/dist/{request-planner-44WOTYCY.js.map → request-planner-GSGBUGNG.js.map} +0 -0
- /package/dist/{review-candidates-BZLS37MN.js.map → review-candidates-4Z6QTMN2.js.map} +0 -0
- /package/dist/{routing-CPLPRA2E.js.map → routing-T66LO3JY.js.map} +0 -0
- /package/dist/{schedule-tool-4I3QUXJK.js.map → schedule-tool-ORNG6HMN.js.map} +0 -0
- /package/dist/{scheduler-LJ32FB5N.js.map → scheduler-VIWJITKR.js.map} +0 -0
- /package/dist/{seat-CBAZAYGY.js.map → seat-4H7TTV5X.js.map} +0 -0
- /package/dist/{select-4CW3CXBU.js.map → select-YCVNOR5Q.js.map} +0 -0
- /package/dist/{set-enabled-QNSLVBGT.js.map → set-enabled-6UGUPYW4.js.map} +0 -0
- /package/dist/{wiki-4LKOLCP4.js.map → wiki-SHHIVZPT.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as C}from"./chunk-CECHWYJ2.js";import{a as L,b as _,c as R,d as j,e as M,j as I}from"./chunk-
|
|
1
|
+
import{b as C}from"./chunk-CECHWYJ2.js";import{a as L,b as _,c as R,d as j,e as M,j as I}from"./chunk-72P53PGX.js";import{v as x,w as O}from"./chunk-PDSCFOC4.js";import{c as A,d as D}from"./chunk-QOYAX2FT.js";import{readFileSync as y,writeFileSync as b,appendFileSync as P,existsSync as w,mkdirSync as $,readdirSync as v,statSync as B}from"fs";import{resolve as u,join as N,relative as k,dirname as U}from"path";O();var T=class{baseDir;rawDir;log;constructor(t=u(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=u(t,"raw/entries"),this.log=e,$(this.rawDir,{recursive:!0}),$(u(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,r=u(this.rawDir,e),n=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&n.push(`context: ${t.sourceContext}`),t.meta)for(let[a,s]of Object.entries(t.meta))n.push(`${a}: ${JSON.stringify(s)}`);return n.push("---","",t.content),b(r,n.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}listEntries(t){if(!w(this.rawDir))return[];let e=v(this.rawDir).filter(n=>n.endsWith(".md")).sort(),r=[];for(let n of e){let a=y(u(this.rawDir,n),"utf-8"),s=this.parseEntry(a,n);s&&(t?.agentId&&s.agentId!==t.agentId||t?.after&&s.date<t.after||t?.before&&s.date>t.before||r.push(s))}return r}parseEntry(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let n=r[1],a=r[2].trim(),s=c=>n.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",o=new Set(["id","date","agent","source","context"]),i={};for(let c of n.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||o.has(l[1])))try{i[l[1]]=JSON.parse(l[2])}catch{i[l[1]]=l[2].trim()}}return{id:s("id")||e.replace(".md",""),date:s("date"),agentId:s("agent"),source:s("source"),sourceContext:s("context")||void 0,content:a,meta:Object.keys(i).length>0?i:void 0}}writeArticle(t,e,r,n){let a=this.readArticle(t);if(a&&!this.canWrite(a.meta,n))return this.log(`Permission denied: "${n}" cannot write "${t}" (owner: ${a.meta.owner})`),!1;e.type&&!C(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let s=u(this.baseDir,t);a&&this.saveVersion(t,s),$(U(s),{recursive:!0});let o=["---",`title: "${e.title}"`];e.type&&o.push(`type: ${e.type}`),e.related?.length&&o.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),o.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&o.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),o.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&o.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),o.push("---","",r),b(s,o.join(`
|
|
4
4
|
`));let i=a?"update":"create";return this.appendLog(i,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${n} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let r=y(e,"utf-8"),n=new Date().toISOString().replace(/[:.]/g,"-"),a=u(this.baseDir,"_versions",t.replace(/\.md$/,""));$(a,{recursive:!0}),b(u(a,`${n}.md`),r)}catch{}}getVersions(t){let e=u(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return v(e).filter(r=>r.endsWith(".md")).sort().reverse().map(r=>({timestamp:r.replace(/\.md$/,"").replace(/-/g,(n,a)=>a<19?a===10?"T":a===13||a===16?":":"-":n),path:u(e,r)}))}catch{return[]}}restoreVersion(t,e){let n=this.getVersions(t).find(a=>a.timestamp.startsWith(e));if(!n)return!1;try{let a=y(n.path,"utf-8"),s=u(this.baseDir,t);return this.saveVersion(t,s),b(s,a),this.appendLog("restore",`${t} restored to ${e}`),!0}catch{return!1}}readArticle(t){let e=u(this.baseDir,t);if(!w(e))return null;let r=y(e,"utf-8");return this.parseArticle(r,t)}readArticleAs(t,e){let r=this.readArticle(t);return!r||!this.canRead(r.meta,e)?null:r}parseArticle(t,e){let r=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!r)return null;let n=r[1],a=r[2].trim(),s=m=>n.match(new RegExp(`^${m}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",o=m=>{let h=n.match(new RegExp(`^${m}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},i=s("type")||s("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(i)?i:void 0,p=o("tags").filter((m,h,f)=>m&&f.indexOf(m)===h),d=o("related"),g=o("graph_path");return{meta:{title:s("title"),type:l,related:d.length?d:void 0,tags:p,owner:s("owner"),access:s("access")||"public",sharedWith:o("shared_with"),created:s("created"),lastUpdated:s("last_updated"),sources:o("sources"),graphPath:g.length?g:void 0},content:a,path:e}}listCache=new Map;listArticles(t){let e=[],r=[];this.walkDir(this.baseDir,(o,i)=>{if(!o.endsWith(".md"))return;let c=k(this.baseDir,o);c.startsWith("raw/")||c.startsWith("_")||(e.push(c),r.push(`${c}:${i?.mtimeMs??"?"}:${i?.size??"?"}`))});let n=r.join("|"),a=this.listCache.get(t);if(a&&a.signature===n)return a.articles.slice();let s=[];for(let o of e){let i=this.readArticle(o);i&&this.canRead(i.meta,t)&&s.push(i)}return this.listCache.set(t,{signature:n,articles:s}),s.slice()}search(t,e,r=10){let n=t.toLowerCase(),a=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let g=k(this.baseDir,d);if(g.startsWith("raw/")||g.startsWith("_"))return;let m=this.readArticle(g);!m||!this.canRead(m.meta,e)||a.push(m)}),a.length===0)return[];let s=a.map(d=>d.content),o=u(this.baseDir,"_bm25_cache.json"),i=D(s,o),c=A(t,i),l=new Map(c.map(d=>[d.docIndex,d.score]));return a.map((d,g)=>{let m=l.get(g)??0;return d.meta.title.toLowerCase().includes(n)&&(m+=10),d.meta.tags?.some(h=>h.toLowerCase().includes(n))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,g)=>g.score-d.score).slice(0,r).map(d=>d.article)}async findRelevantReranked(t,e,r=10,n={}){let a=Math.max(r,n.shortlist??_),s=this.findRelevant(t,e,a);if(s.length<2)return s.slice(0,r);let o=s.map((l,p)=>({id:`c${p}`,title:l.meta.title||`(untitled ${p})`,tags:l.meta.tags,excerpt:l.content})),i=await x(L,R({query:t,candidates:o,excerptChars:n.excerptChars}),j(o),{incumbent:{best:o[0].id},features:{agent:e??"unknown"}});return!i||i.mode!=="active"?s.slice(0,r):M(i.answers,o).ranked.map(l=>s[Number(l.slice(1))]).filter(l=>!!l).slice(0,r)}findRelevant(t,e,r=3,n,a={graph:.6,bm25:.4}){let s=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=k(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let W=this.readArticle(f);!W||!this.canRead(W.meta,e)||s.push(W)}),s.length===0)return[];let o=s.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),i=u(this.baseDir,"_bm25_relevance_cache.json"),c=D(o,i),l=A(t,c),p=l.reduce((h,f)=>Math.max(h,f.score),0)||1,d=new Map(l.map(h=>[h.docIndex,h.score/p])),g=!!(n&&n.length>0);return s.map((h,f)=>{let W=d.get(f)??0,S=0;g&&h.meta.graphPath?.length&&(S=I(n,h.meta.graphPath));let E=g?a.graph*S+a.bm25*W:W;return{article:h,score:E}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,r).map(h=>h.article)}buildContext(t,e=4e3){if(t.length===0)return"";let r=["[Wiki Knowledge]"],n=0;for(let a of t){let s=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${r}`}walkDir(t,e){if(w(t))for(let r of v(t)){let n=N(t,r),a=B(n);a.isDirectory()?this.walkDir(n,e):e(n,a)}}};export{T as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-IYLQBBON.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,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 q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-A4ACRRRP.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-SC6Q5M4C.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 A(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",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
|
|
2
2
|
`)}async function k(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(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).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}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" 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:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
|
|
4
4
|
`),H=await k(h,t,G);return[`Requested schedule "${d}": ${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=p[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 d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.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:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await k(h,t,f);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)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-LQ3PEMBH.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-72P53PGX.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{v as C,w as I}from"./chunk-PDSCFOC4.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -46,4 +46,4 @@ ${o}
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
48
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-MODPTVA6.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{f as j,i as x,p as O,r as I}from"./chunk-S2GAEH2F.js";import{A as S,D as _}from"./chunk-SZZSUW42.js";_();import{Command as q}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{accessSync as E,constants as T,existsSync as y,readFileSync as b,readdirSync as $,statSync as z}from"fs";import{join as P,resolve as m}from"path";import{homedir as X}from"os";import{createRequire as B}from"module";import{execFile as L}from"child_process";var M=(n,t)=>new Promise(e=>{try{L(n,t,{timeout:5e3},(i,s)=>e(i?null:String(s)))}catch{e(null)}}),R="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function N(n={}){if((n.platform??process.platform)!=="darwin")return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let t=n.helper===void 0?I():n.helper;if(!t)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(n.run??M)(t,["notify-status"]),i=null;try{i=e?JSON.parse(e):null}catch{i=null}return i?i.authorization==="notDetermined"?{state:"not-asked",path:t,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:t,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:R}:i.alertStyle==="none"?{state:"hidden",path:t,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:R}:{state:"ready",path:t,message:"AgentX Helper posts banners with the AgentX icon."}:{state:"outdated",path:t,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}}async function F(n={}){let t=[];await Z(t),U(t);let e=K(t);return e&&Q(t,e),e&&Y(t,e),e&&ee(t,e),e&&te(t,e),e&&oe(t,e),e&&await J(t,e),e&&G(t,e),n.running!==!1&&e&&await ie(t,e),{checks:t,summary:H(t)}}var be=new q().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 n=>{let{checks:t,summary:e}=await F({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:t,summary:e},null,2)+`
|
|
2
|
+
`):se(t),process.exit(e.errors>0?1:0)});async function J(n,t,e=N){if(!O(t.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&n.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}function G(n,t,e=process.platform,i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}}){let s=t.reminders;if(!s?.enabled)return;if(e!=="darwin"){n.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);n.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."})}function V(n){let[t,e]=n.split(".").map(Number);return t===22&&e>=19||t>=23&&t<=26}async function Z(n){let t=V(process.versions.node);n.push({severity:t?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:t?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:t?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
|
+
`)[0]}catch{return null}},i=e("npm");n.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{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:s})}else n.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{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:r})}else n.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{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else n.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{B(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){n.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(n){if(process.platform!=="darwin")return;let t=P(X(),"Library/LaunchAgents"),e=[];try{e=$(t).filter(s=>/agentx\.voice.*\.plist$/.test(s))}catch{return}let i=s=>{try{return E(s,T.X_OK),!0}catch{return!1}};for(let s of e){let r=j(b(P(t,s),"utf-8")),a=x("ffmpeg",r,i);n.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(n){let t=m(process.cwd(),"agentx.json");if(!y(t))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${t}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(t,"utf-8"))}catch(a){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{S(t),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){n.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}})()||n.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}})()||n.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}})()||n.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(n,t){let e=new Set;if(C(t,e),e.size===0){n.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?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.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&&n.push({severity:"warn",group:"Secrets",title:`${a.length} env var(s) set but empty`,detail:a.join(", ")}))}function C(n,t){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))t.add(e[1]);else if(Array.isArray(n))for(let e of n)C(e,t);else if(n&&typeof n=="object")for(let e of Object.values(n))C(e,t)}function Y(n,t){let e=[];for(let[i,s]of Object.entries(t.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{z(r).isDirectory()||e.push(`${i}: ${r} (exists but not a directory)`)}catch{e.push(`${i}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
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(n,t){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[s,r]of Object.entries(t.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){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(t.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of i)n.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(n,t){let e=t.webhooks??[],i=[],s=m(process.cwd(),t.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 ${t.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((t.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(t.agents??{}));for(let o of t.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(t.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(t.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 W=g.credentials||{};for(let[D,v]of Object.entries(W))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}].${D} -> $${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){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(t.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let o of i)n.push({severity:o.severity,group:"Routing",title:o.title,fix:o.fix})}function ne(n){return typeof n?.canMeasure!="boolean"?null:n.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:n.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(n,t){let e=t.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};t.dashboard?.token&&(i.Authorization=`Bearer ${t.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){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();n.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&&n.push(u)}catch{n.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(n,t){let e=Object.entries(t.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
|
+
`)[0]||null}catch{i=null}if(i){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:i})}else n.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)){n.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)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:a}):n.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 H(n){return{errors:n.filter(t=>t.severity==="fail").length,warnings:n.filter(t=>t.severity==="warn").length,ok:n.filter(t=>t.severity==="ok").length}}function se(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let t=new Map;for(let i of n)t.has(i.group)||t.set(i.group,[]),t.get(i.group).push(i);for(let[i,s]of t){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
|
+
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=H(n);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{N as a,F as b,be as c,J as d,G as e,V as f,ne as g};
|
|
7
|
+
//# sourceMappingURL=chunk-N3Y3NORE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/doctor.ts","../src/notify/helper-status.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { join, resolve } from \"path\"\nimport { homedir } from \"os\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\nimport { findOnPath, plistPathEnv } from \"@/desktop/install\"\nimport { localSettings } from \"@/notify/local\"\nimport { helperStatus } from \"@/notify/helper-status\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n runDesktopChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (cfg) await runNotificationChecks(checks, cfg)\n if (cfg) runReminderChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\n/** On a Mac with banners on: can AgentX Helper post them with its icon? */\nexport async function runNotificationChecks(checks: Check[], cfg: any, status = helperStatus): Promise<void> {\n if (!localSettings(cfg.notifications?.local).banner) return\n const helper = await status()\n if (helper.state === \"unsupported\") return\n checks.push({\n severity: helper.state === \"ready\" ? \"ok\" : \"warn\",\n group: \"Notifications\",\n title: helper.message,\n detail: helper.path,\n fix: helper.fix,\n })\n}\n\n/** reminders.enabled: macOS only, and the daemon needs remindctl. */\nexport function runReminderChecks(\n checks: Check[],\n cfg: any,\n platform: NodeJS.Platform = process.platform,\n isExecutable: (file: string) => boolean = (file) => { try { accessSync(file, constants.X_OK); return true } catch { return false } },\n): void {\n const r = cfg.reminders\n if (!r?.enabled) return\n if (platform !== \"darwin\") {\n checks.push({\n severity: \"warn\",\n group: \"Reminders\",\n title: \"Reminders hand-back unavailable on this machine\",\n detail: \"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.\",\n fix: \"Set reminders.enabled to false here, or enable it on the Mac node instead.\",\n })\n return\n }\n const command = r.command || \"remindctl\"\n const found = command.includes(\"/\") ? (isExecutable(command) ? command : null) : findOnPath(command, process.env.PATH || \"\", isExecutable)\n checks.push(found\n ? { severity: \"ok\", group: \"Reminders\", title: `Watching ${(r.lists || []).join(\", \")} for due reminders`, detail: found }\n : {\n severity: \"fail\",\n group: \"Reminders\",\n title: `${command} not found`,\n detail: \"The daemon reads Apple Reminders through remindctl.\",\n fix: \"brew install steipete/tap/remindctl, or set reminders.command to its full path.\",\n })\n}\n\n// Keep in step with package.json \"engines\": undici 8 needs 22.19, and\n// better-sqlite3 ships prebuilt binaries up to Node 26.\nexport function nodeVersionSupported(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number)\n return (major === 22 && minor >= 19) || (major >= 23 && major <= 26)\n}\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const supported = nodeVersionSupported(process.versions.node)\n checks.push({\n severity: supported ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: supported ? undefined : \"AgentX requires Node 22.19 or newer, up to Node 26.\",\n fix: supported ? undefined : \"Install Node 22 (nvm install 22 && nvm use 22)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\n/** The desktop app's login item runs with only the PATH its plist sets, so\n * check that local Whisper's ffmpeg is reachable there, not in this shell. */\nfunction runDesktopChecks(checks: Check[]): void {\n if (process.platform !== \"darwin\") return\n // Older installs used another label; apps/mac-voice/install.sh keeps it.\n const agents = join(homedir(), \"Library/LaunchAgents\")\n let names: string[] = []\n try { names = readdirSync(agents).filter(n => /agentx\\.voice.*\\.plist$/.test(n)) } catch { return }\n const isExecutable = (file: string) => { try { accessSync(file, constants.X_OK); return true } catch { return false } }\n for (const name of names) {\n const path = plistPathEnv(readFileSync(join(agents, name), \"utf-8\"))\n const ffmpeg = findOnPath(\"ffmpeg\", path, isExecutable)\n checks.push(ffmpeg\n ? { severity: \"ok\", group: \"Desktop\", title: \"ffmpeg reachable by the desktop app\", detail: `${ffmpeg} (${name})` }\n : {\n severity: \"warn\",\n group: \"Desktop\",\n title: \"ffmpeg not reachable by the desktop app\",\n detail: `Local Whisper transcription fails without it. ${name} sets PATH to ${path}.`,\n fix: \"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install.\",\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\n/** Whether the running daemon can measure phone recordings, from its own\n * /health: the service's PATH, not this shell's (#233). Null for a daemon\n * too old to say. */\nexport function daemonVoiceCheck(voice: { canMeasure?: boolean; allowUnmeasured?: boolean } | undefined): Check | null {\n if (typeof voice?.canMeasure !== \"boolean\") return null\n if (voice.canMeasure) return { severity: \"ok\", group: \"Runtime\", title: \"Daemon finds ffmpeg to measure phone recordings\" }\n return {\n severity: \"warn\",\n group: \"Runtime\",\n title: voice.allowUnmeasured\n ? \"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)\"\n : \"Daemon can't find ffmpeg: phone voice input is refused\",\n 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.\",\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n const voice = daemonVoiceCheck(body.voice)\n if (voice) checks.push(voice)\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n","import { execFile } from \"child_process\"\nimport { findHelper } from \"./local\"\n\n// Why a banner shows the Script Editor icon instead of the AgentX logo,\n// in words a person can act on. `agentx notify` falls back to osascript\n// silently — it must never fail to notify — so this is where the reason\n// surfaces: `agentx notifications show` and `agentx doctor` print it.\n//\n// Reading the status never posts a banner and never shows the macOS\n// \"allow notifications\" prompt.\n\nexport type HelperState = \"ready\" | \"unsupported\" | \"missing\" | \"outdated\" | \"not-asked\" | \"not-allowed\" | \"hidden\"\n\nexport interface HelperStatus {\n state: HelperState\n /** One plain sentence on what the person will see. */\n message: string\n /** What to do about it; absent when nothing needs doing. */\n fix?: string\n /** The helper binary that was checked, when there is one. */\n path?: string\n}\n\n/** Runs a command and resolves its stdout, or null when it failed. */\ntype Capture = (file: string, args: string[]) => Promise<string | null>\n\nconst capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: 5_000 }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nconst SETTINGS = \"Open System Settings › Notifications › AgentX Helper, turn on Allow notifications and choose Banners.\"\n\nexport async function helperStatus(\n deps: { platform?: NodeJS.Platform; helper?: string | null; run?: Capture } = {},\n): Promise<HelperStatus> {\n if ((deps.platform ?? process.platform) !== \"darwin\") {\n return { state: \"unsupported\", message: \"Desktop banners are only shown on a Mac.\" }\n }\n const path = deps.helper === undefined ? findHelper() : deps.helper\n if (!path) {\n return {\n state: \"missing\",\n message: \"AgentX Helper is not installed, so banners come from Script Editor and show its icon.\",\n fix: \"Run agentx desktop install, then run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow.\",\n }\n }\n const out = await (deps.run ?? capture)(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) {\n return {\n state: \"outdated\",\n path,\n message: \"AgentX Helper is too old to report whether it may notify.\",\n fix: \"Run agentx desktop install to update it.\",\n }\n }\n if (status.authorization === \"notDetermined\") {\n return {\n state: \"not-asked\",\n path,\n message: \"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.\",\n fix: \"Run agentx notify \\\"Hello\\\" --title \\\"Test\\\" and click Allow when macOS asks.\",\n }\n }\n if (status.authorization === \"denied\") {\n return { state: \"not-allowed\", path, message: \"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.\", fix: SETTINGS }\n }\n if (status.alertStyle === \"none\") {\n return { state: \"hidden\", path, message: \"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.\", fix: SETTINGS }\n }\n return { state: \"ready\", path, message: \"AgentX Helper posts banners with the AgentX icon.\" }\n}\n"],"mappings":"4GAOAA,IAPA,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KACvF,OAAS,QAAAC,EAAM,WAAAC,MAAe,OAC9B,OAAS,WAAAC,MAAe,KACxB,OAAS,iBAAAC,MAAqB,SCN9B,OAAS,YAAAC,MAAgB,gBA0BzB,IAAMC,EAAmB,CAACC,EAAMC,IAC9B,IAAI,QAASC,GAAS,CACpB,GAAI,CACFC,EAASH,EAAMC,EAAM,CAAE,QAAS,GAAM,EAAG,CAACG,EAAKC,IAAWH,EAAKE,EAAM,KAAO,OAAOC,CAAM,CAAC,CAAC,CAC7F,MAAE,CACAH,EAAK,IAAI,CACX,CACF,CAAC,EAEGI,EAAW,kHAEjB,eAAsBC,EACpBC,EAA8E,CAAC,EACxD,CACvB,IAAKA,EAAK,UAAY,QAAQ,YAAc,SAC1C,MAAO,CAAE,MAAO,cAAe,QAAS,0CAA2C,EAErF,IAAMC,EAAOD,EAAK,SAAW,OAAYE,EAAW,EAAIF,EAAK,OAC7D,GAAI,CAACC,EACH,MAAO,CACL,MAAO,UACP,QAAS,wFACT,IAAK,4FACP,EAEF,IAAME,EAAM,MAAOH,EAAK,KAAOT,GAASU,EAAM,CAAC,eAAe,CAAC,EAC3DG,EAAiE,KACrE,GAAI,CAAEA,EAASD,EAAM,KAAK,MAAMA,CAAG,EAAI,IAAK,MAAE,CAAQC,EAAS,IAAK,CACpE,OAAKA,EAQDA,EAAO,gBAAkB,gBACpB,CACL,MAAO,YACP,KAAAH,EACA,QAAS,+GACT,IAAK,2E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,IACtF,kBAAkBA,EAAE,SAAW,EAAI,GAAK,gBAAgB,EACjDA,EAAE,SAAW,EACtB,QAAQ,IAAIL,EAAM,OAAO,KAAK,KAAKK,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,MAAM,EAAIL,EAAM,IAAI,2BAA2B,CAAC,EAEhI,QAAQ,IAAIA,EAAM,MAAM,KAAK,wBAAwBK,EAAE,MAAM,CAAC,EAEhE,QAAQ,IAAI,CACd","names":["init_config","Command","chalk","execFileSync","accessSync","constants","existsSync","readFileSync","readdirSync","statSync","join","resolve","homedir","createRequire","execFile","capture","file","args","done","execFile","err","stdout","SETTINGS","helperStatus","deps","path","findHelper","out","status","runDoctorChecks","opts","checks","runEnvChecks","runDesktopChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runNotificationChecks","runReminderChecks","runRuntimeChecks","summarize","doctor","Command","summary","printHumanReport","status","helperStatus","localSettings","helper","platform","isExecutable","file","accessSync","constants","r","command","found","findOnPath","nodeVersionSupported","version","major","minor","supported","which","bin","execFileSync","npmPath","claudePath","ver","codexPath","openCodePath","createRequire","e","agents","join","homedir","names","readdirSync","n","name","path","plistPathEnv","readFileSync","ffmpeg","cfgPath","resolve","existsSync","loadDaemonConfig","claudeCodeAgents","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","raw","node","into","item","v","a","abs","statSync","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","daemonVoiceCheck","voice","url","headers","ac","timer","body","optedIn","cgPath","def","dbPath","c","chalk","groups","group","items","marker","s"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Zn,b as es,d as ns,f as st,l as hs,r as ms,x as fs,z as ys}from"./chunk-
|
|
1
|
+
import{a as Zn,b as es,d as ns,f as st,l as hs,r as ms,x as fs,z as ys}from"./chunk-QGTQ4PIL.js";import{a as Vn}from"./chunk-WP6KLXTP.js";import{a as Rt}from"./chunk-N6EWZGIX.js";import{b as ts}from"./chunk-DP7RTNDM.js";import{a as ps}from"./chunk-W4YR2RO2.js";import{b as rs,c as Et,d as is,e as as,h as cs}from"./chunk-CW42OBFL.js";import{a as Yn}from"./chunk-ZPM7SSJM.js";import{a as Pt,b as ss}from"./chunk-J3SOEFRE.js";import{a as _t,b as os}from"./chunk-SIU6STB2.js";import{e as ds,i as us,j as ls,k as gs}from"./chunk-X5C5W3E4.js";import{a as Hn}from"./chunk-2KOWJNQJ.js";import{a as jn,c as Un}from"./chunk-MYVHVJWZ.js";import{a as Bn,b as Wn,c as qn,d as Kn,f as Gn}from"./chunk-DWADWDMU.js";import{a as Jn,b as Qn}from"./chunk-23A5K5UW.js";import{g as zn,h as Xn}from"./chunk-72P53PGX.js";import{a as nt,c as De}from"./chunk-2GIDVZ4H.js";import{q as Nn,t as Ln,v as xe,w as Fn}from"./chunk-PDSCFOC4.js";import{a as Ee,b as tt,f as Mt}from"./chunk-72SZI2UW.js";import{a as we,b as At}from"./chunk-FCPTN6NF.js";import{c as Rn,d as Pn}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{D as Ao,d as _n,e as ae,f as En,g as Dn,h as $t,u as On}from"./chunk-SZZSUW42.js";Fn();Mt();var bs="session-continuity",ws={continues:Ee("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Ee("Does the new request refer to something stated earlier in the conversation?")};function xs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Dt(s.message,1200),previousRequest:s.previousMessage?Dt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Dt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Ts(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Dt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as dt}from"execa";import{spawn as $o}from"node:child_process";import{createHash as Mo}from"node:crypto";import{createInterface as Ro}from"node:readline";var ce=class extends Error{},Po=s=>$o("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Ot=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Ro({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Nt=class{constructor(e=Po,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=Mo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([y],[v])=>y.localeCompare(v))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ce("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let y=[...this.entries].find(([,v])=>!v.connection.busy);if(!y)throw new ce("Codex warm process capacity reached");y[1].connection.close(),this.entries.delete(y[0])}try{r={fingerprint:n,connection:new Ot(e,this.launchProcess)}}catch{throw new ce("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,g=!1,m=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",m,{once:!0});let f=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let y={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...y,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((O,D)=>{i.failTurn=D,i.notify=(C,_)=>{if(_?.threadId!==l)return;let L=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...L?{item:{...L,type:E[L.type]||L.type}}:{}}),C==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let F=_.tokenUsage.last,H=F.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?O():D(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(y){if(i.close(),!a&&!e.signal?.aborted)throw new ce(y.message);return{content:c,codexSessionId:l,usage:u,error:y.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(f),e.signal?.removeEventListener("abort",m),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Is=new Nt;import{execFile as Jo}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as Ns,readFileSync as Ls,rmSync as Fs}from"fs";import{join as at}from"path";import{tmpdir as Hs}from"os";function rt(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ot(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ks=null;function it(){return ks}function mc(s){ks=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function _o(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var Te=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Ss=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Oe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=_o(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new Te(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new Te(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Oe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Oe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Eo}from"child_process";import{existsSync as Do,readFileSync as Oo}from"fs";import{resolve as No}from"path";function Lo(s){let e=No(s,"CLAUDE.md");if(!Do(e))return null;try{let t=Oo(e,"utf8");return Gn(t)}catch{return null}}var Fo=20*60*1e3,Ho=5e3,Ne=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Le=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function jo(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var vs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Lt(e,t,this.opts)}},Lt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Eo(r,o,{cwd:t.workspace,env:De(jo({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Lo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??Fo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ne(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Le(this.killReason);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ho);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};$t();import{resolve as Cs,join as As}from"path";At();var Uo=4e3;function $s(s){try{let e=As(Cs(s.root),".agentx","db.sqlite"),t=Rt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=we(),r=s.input.command?s.input.command.slice(0,Uo):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function zo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};D.stdout?.on("data",k=>{E+=H.write(k);let b=E.split(`
|
|
28
28
|
`);E=b.pop()||"";for(let x of b)B(x)}),D.stderr?.on("data",k=>{F+=j.write(k)});let A=await D;if(i&&i.removeEventListener("abort",L),E+=H.end(),E.trim()&&B(E),F+=j.end(),C)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:m};if(A.exitCode!==0||f){let k=A,b;return k.timedOut?b=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:f?b=f:k.code==="ENOENT"||/ENOENT|spawn opencode/i.test((k.shortMessage||"")+" "+F)?b=Es():b=F.trim()||`OpenCode exited with code ${k.exitCode??"unknown"}`,{content:"",...Q(b),duration:Date.now()-c,usage:g,opencodeSessionId:m}}return y=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:m}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let O=/ENOENT|spawn opencode/i.test(I?.message||"")?Es():I?.message;return{content:u,...Q(O||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:m}}finally{v?.(),T?.release(y)}}async function ii(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ue(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function ai(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,g=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let f=setTimeout(()=>{g=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);f.unref?.();let T=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let y=s.provider||"claude-code",v=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,O=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),D=e.context?.channel==="web-chat"&&O?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=Kn(s),_=Object.keys(C).length>0,L={task:v,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:D,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:B}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,O=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),D=e.context?.channel==="web-chat"&&O?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=Kn(s),_=Object.keys(C).length>0,L={task:v,cwd:s.workspace,provider:y,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:D,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:B}=await import("./agent-5GQLISLJ.js"),A="",k,b,x,N;for await(let M of B(L)){if(c)try{c(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let w=M.result.content.slice(A.length);w?(A=M.result.content,r(w,A)):A=M.result.content}k=M.result.tokensUsed,M.result.inputTokens!=null&&(b=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let w=M.result.content.slice(A.length);w?(A=M.result.content,r(w,A)):A=M.result.content}M.result.tokensUsed!=null&&(k=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?g?T():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-d}:((b===void 0||x===void 0)&&k&&(b=Math.round(k*.7),x=k-b),{content:A||"Done.",tokensUsed:k,usage:b!==void 0||x!==void 0?{inputTokens:b||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:E}=await import("./agent-5GQLISLJ.js"),F=await E(L),H=F.inputTokens,j=F.outputTokens;if((H===void 0||j===void 0)&&F.tokensUsed){let B=F.tokensUsed;H=Math.round(B*.7),j=B-H}return{content:F.content||"Done.",tokensUsed:F.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(y){return g?T():y?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...Q(`Orchestrator error: ${y.message}`),duration:Date.now()-d}}finally{clearTimeout(f),a&&a.removeEventListener("abort",m)}}var ci=1e3;async function di(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),ci),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function ui(s,e,t,n,r,o,i){let a=it();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let g,m=!1;try{let A=a.list().length;g=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),m=a.list().length>A}catch(A){return A instanceof Te,null}m&&Wt(e.agentId,s,e.model,n,"persistent");let f=ue(s,e,t),T="",y,v,I,O,D,C,_,L="",E="",F=A=>{if(!i||!A)return;let k;if(E&&A.startsWith(E)?k=A.slice(E.length):k=L&&!L.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${A}`:A,E=A,!!k){L+=k;try{i(k,L)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let B=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let k of g.runTurn({message:f,taskId:e.taskId??"unknown",deadlineMs:A})){if(B=!0,r)try{r(k.raw)}catch{}if(k.type==="assistant"){let b=k.raw.message?.content??[];for(let N of b)N.type==="text"&&typeof N.text=="string"?(T=N.text,F(N.text)):N.type==="tool_use"&&(E="");let x=k.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(O=N)}}if(k.type==="result"){let b=k.raw;if(b.is_error){let x=Q(typeof b.result=="string"?b.result:"claude error");y=x.error,v=x.errorKind}else typeof b.result=="string"&&b.result.length>0&&(T=b.result,L||F(b.result));typeof b.session_id=="string"&&(_=b.session_id),b.usage&&(I={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(D=b.num_turns),typeof b.message?.model=="string"?C=b.message.model:typeof b.model=="string"&&(C=b.model)}}}catch(A){if(H)y="task cancelled by operator",v="cancelled";else if(B)if(A instanceof Le)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,v="interrupted";else if(A instanceof Ne){let k=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);y=k.error,v=k.errorKind}else{let k=Q(`persistent claude process error: ${A?.message||String(A)}`);y=k.error,v=k.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!y&&(y="task cancelled by operator",v="cancelled"),{content:H?"":T,error:y,errorKind:v,duration:Date.now()-c,usage:I,contextTokens:O,numTurns:D,billedModel:C,claudeSessionId:_}}function Qs(s){return ae(s.autonomy)?s.taskId?Rs(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function li(s,e,t,n,r,o,i){let a=e.autonomy,c=Ps(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Dn(a)}
|
|
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:Fi,maxTokens:512})).content.trim().match(/\[[
|
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(d){i={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,n,r);if(c){let d=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=i.error?st(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";rs().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return i}async executeInternal(e,t,n,r){let o=ae(e.autonomy),i=o?null:wr().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let p=await i;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let p=this.meshFallback.directory().find(h=>h.healthy&&h.skills.some(S=>S.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let h=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:h}),viaMesh:p.peer}}catch(h){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${h?.message??h}`),{content:"",error:`mesh fallback failed: ${h?.message??h}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="a2a"||c==="mcp"||c==="reminder"||c==="events"||o){let p=Date.now(),h=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let p=Date.now(),h=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-p>h)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(h/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let p=a.def.queueMode||"collect",h=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context,queuedAt:e.queuedAt});if(h==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(h){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${h}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:ns(h,S)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,h)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(h/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};if(e.queuedAt!==void 0){let p=ur(e.queuedAt);p&&(e.message=`${p}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let g={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(g),e.runningTaskId=g.id,this.runningContexts.set(g.id,e.context??{}),e.onStart)try{e.onStart(g.id)}catch{}let m=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:m});let f={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,f);let T=p=>{if(p){f.buffer+=p,f.buffer.length>Vr&&(f.buffer=f.buffer.slice(f.buffer.length-Vr));for(let h of f.subscribers)try{h(p)}catch{}}},y=we();e.taskId=y;let v=new Map,I=(p,h,S)=>{try{Z().emit("task:step",{taskId:y,agentId:e.agentId,name:"pipeline",action:p,status:S,ms:Date.now()-h,at:new Date().toISOString()})}catch{}},O=0,D=!1,C=()=>{D||(D=!0,O&&I("first-event",O,"ok"))},_;if(t){let p=ic();_=h=>{C();let S=p(h);if(S&&T(S),to(y,e.agentId,h),eo(v,h),r)try{r(h)}catch{}}}else _=p=>{if(C(),to(y,e.agentId,p),eo(v,p),r)try{r(p)}catch{}};let L=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=L?setTimeout(()=>m.abort(new Error(`timed out after ${Math.round(L/1e3)}s`)),L):void 0;E?.unref?.();let F=(a.def.preSpawnTimeoutSec??Za)*1e3,H=setTimeout(()=>{m.abort(new Error(`timed out before spawn after ${Math.round(F/1e3)}s in step "${g.step??"start"}"`))},F);H.unref?.();let j=()=>{H&&clearTimeout(H),H=void 0},B=()=>`task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`,A;m.signal.addEventListener("abort",()=>{let p=qe(m.signal).message;/^timed out/.test(p)&&(A=g.step??"start"),this.log(`[${e.agentId}] task ${g.id} aborted in step "${g.step??"start"}" \u2014 ${p} ${B()}`)},{once:!0});let k=p=>{g.step=p,this.log(`[${e.agentId}] step ${p} ${B()}`)},b=(p,h,S=0)=>{if(m.signal.aborted)return Promise.reject(qe(m.signal));k(p),(p==="agent"||p==="workflow-auto-run")&&(j(),O=Date.now());let P=Date.now(),W=Xr(h(),Xa[p]??0,p);return zr(W,m.signal,S).then(K=>(I(p,P,"ok"),K),K=>{throw I(p,P,"error"),K instanceof $e&&this.log(`[${e.agentId}] ${K.message}; continuing without it ${B()}`),K})},x=async(p,h,S,P=0)=>{try{return await b(p,h,P)}catch(W){if(W instanceof $e)return S();throw W}},N=!1,M=p=>{if(N)return;N=!0,this.runReleases.delete(g.id),E&&clearTimeout(E),j(),a.activeTasks--;let h=a.runningTasks.findIndex(S=>S.id===g.id);h!==-1&&a.runningTasks.splice(h,1),this.runningContexts.delete(g.id),this.taskAborts.delete(g.id),f.done=!0,f.endedAt=new Date;for(let S of f.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}f.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Ya).unref?.();try{let S=f.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:f.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let K=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:K,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(K=>this.postQueuedResponseToChannel(e.agentId,W,K)).catch(K=>{this.log(`[${e.agentId}] queued message failed: ${K.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(g.id,M),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${B()}`);let w=e.context?.channel||"api",{evaluateRequest:ro,selectRequestContext:oo}=await import("./request-planner-
|
|
134
|
+
`)}catch{}f.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Ya).unref?.();try{let S=f.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:f.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let K=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:K,at:S,ok:P.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(S=>{if(S.length!==0){this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of S){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(K=>this.postQueuedResponseToChannel(e.agentId,W,K)).catch(K=>{this.log(`[${e.agentId}] queued message failed: ${K.message}`)})}}}).catch(S=>{this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(g.id,M),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${B()}`);let w=e.context?.channel||"api",{evaluateRequest:ro,selectRequestContext:oo}=await import("./request-planner-GSGBUGNG.js"),ge=await x("request-gate",()=>ro(e.message,e.agentId,w),()=>({active:!1,preprocess:!1}));ge.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let $=e.context?.chatId||e.context?.group||e.context?.sender||"default",bt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,w,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${$}`),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await x("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,$,e.seedHistory),()=>{});let io=[...this.sessions.getSession(e.agentId,w,$).messages].reverse().find(p=>p.role==="agent")?.content;Qr({agent:e.agentId,channel:w,chatId:$,message:e.message,previousReply:io,taskId:y}),this.sessions.addUserMessage(e.agentId,w,$,bt,e.message);let dn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:w,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(dn).toISOString(),taskId:y,resumeOrigin:cr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,wt,un=this.classifier;if(un&&w!=="a2a"&&!te){k("classify");let p=Date.now();wt=un.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:$,agentId:e.agentId}).then(h=>{Y=h||void 0,Y?.path?.length&&(g.intentPath=Y.path.slice()),I("classify",p,"ok")},h=>{this.log(`[classifier] classify failed for ${e.agentId}: ${h?.message||h}`),I("classify",p,"error")})}let ln=async p=>{if(!wt)return;let h;await Promise.race([wt,new Promise(S=>{h=setTimeout(S,p),h.unref?.()})]),h&&clearTimeout(h)};await ln(Ka);let Re=this.config.workflows?.matching,be;if(this.config.workflows?.enabled&&Re?.enabled&&!o)try{let p=new hs({baseDir:G(process.cwd(),this.config.workflows.dir)}),h=ms({agentId:e.agentId,channel:w,message:e.message,intentPath:Y?.path},p.list());h&&h.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${h.workflow.id} confidence=${h.confidence.toFixed(2)} mode=${Re.mode} reasons=${h.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&h.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?be={workflowId:h.workflow.id,confidence:h.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ao=this.wikiHub.getAgentWiki(e.agentId),gn=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),pn=this.memoryStore.buildContext(gn),hn=this.memoryStore.contextFacts(gn),co=this.patternStore.findRelevant(e.message,e.agentId,5),uo=this.patternStore.buildContext(co),mn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:h}=await import("./loader-YFVSSYSL.js"),S=await b("skills",()=>p(a.def.workspace));mn=h(S,e.message)}catch{}let U=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,$):void 0;if(U&&this.sessions.isSessionStale(e.agentId,w,$)&&(this.log(`[${e.agentId}] session stale for ${w}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,w,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,w,$);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,w,$)){let p=this.sessions.getTurnCount(e.agentId,w,$);this.log(`[${e.agentId}] max-turns rotation for ${w}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,U,w,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,$),Z().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:$,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&a.def.tier==="claude-code"){let p=U;await x("rotate",()=>this.maybeRotateForContinuity(e,a,w,$,p),()=>!1)&&(U=void 0)}try{let p=await b("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,$,this.memoryStore));if(p.compacted){let h=p.qualityScore??"?",S=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${$} (quality: ${h}%, ${S} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let P=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let lo=process.env.AGENTX_CONTEXT_SURGERY==="1",go=te?{maxMessages:8,maxChars:2400}:lo&&Yr(w,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,po=!U&&!te?sc(ao,e.agentId):void 0,Je=U?void 0:this.sessions.buildHistoryContext(e.agentId,w,$,go),ho=U?void 0:this.sessions.getRotationMemo(e.agentId,w,$)??void 0,fn,yn=[];if(this.config.procedures?.injection?.enabled&&!U&&!te)try{let p=new We({baseDir:G(process.cwd(),this.config.procedures.dir)}),h=tn(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(h.length>0){fn=nn(h),yn=h.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of h)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(he&&he.cat)try{let h=this.sessions.getSession(e.agentId,w,$).messages,S=h[0],P=h[h.length-1],W=Je===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Je.length}c/${Je.split(`
|
|
135
135
|
`).length}L`,K=`[${e.agentId}] ${w}:${$} ${W} | session.messages=${h.length}`+(h.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",K)}catch(p){he.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let bn;if(a.def.contextReferences&&!U)try{let p=a.def.workspace,h=this.referencesCache.get(p);if(!h){let[P,W]=await b("references",()=>Promise.all([Pt(a.def.workspace),_t(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[K,pe]=await b("references",()=>Promise.all([Pt(process.cwd()),_t(process.cwd())]));h={refs:K,recipes:pe}}else h={refs:P,recipes:W};this.referencesCache.set(p,h)}let S=os({agentId:e.agentId,intentTags:Y?.path,message:e.message},h.recipes,h.refs);S.cards.length>0&&(bn=ss(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let wn=this.sessions.getCrossSessionSummary(e.agentId,w,$,e.message),xn,Qe=Vs(e.message);if(Qe)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:$,lookbackDays:Qe.lookbackDays,limit:12});if(p.turns.length>0){let h=[`[Long-memory recall \u2014 last ${Qe.lookbackDays}d on this chat (cue-triggered)]`],S=[...p.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of S){let W=P.ts.slice(11,16)+" "+P.day,K=P.role==="user"?P.senderName||"User":P.senderName||"Agent";h.push(`${W} ${K}: ${P.content}`)}p.hasMore&&h.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),h.push("[End of long-memory recall \u2014 respond to the latest message above]"),xn=h.join(`
|
|
136
136
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Qe.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let mo=te?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",Tn,In,kn=!1;if(mo==="planner"&&!ge.active&&w!=="voice"&&w!=="desktop"){try{let{planContext:p}=await import("./context-planner-JU7CNXCB.js"),h=await b("plan-context",()=>p({agentId:e.agentId,channel:w,chatId:$,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));h?(kn=!0,Tn=h.sessionHistory,pn=h.memoryContext,hn=h.memoryFacts,wn=h.crossChatContext,In=h.debug,this.log(`[${e.agentId}] planner: turns=${h.debug.recentTurns}, mem=${h.debug.memoryIncluded?"yes":"no"}, xchat=${h.debug.crossChatIncluded?"yes":"no"} (${h.debug.planLatencyMs}ms) \u2014 ${h.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}kn&&U&&(this.sessions.clearClaudeSessionId(e.agentId,w,$),U=void 0)}let xt=`${e.agentId}:${w}:${$}`,ze=qn(e.message);ze&&(ze==="default"?(this.activeSouls.delete(xt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(xt,ze),this.log(`[${e.agentId}] Soul switched to: ${ze}`)));let fo=this.activeSouls.get(xt),yo=Bn(a.def.workspace,fo),bo=Wn(yo),wo=this.agentMemory.indexMarkdown(e.agentId),xo=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
137
137
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",To=ac(a.def.richMessages,w),Sn="";if(a.def.workspace){let p=G(a.def.workspace,"CLAUDE.md");if(ee(p))try{let h=Ke(p,"utf-8");Sn=`[Project CLAUDE.md]
|
|
@@ -144,9 +144,9 @@ ${R}`),h+=R.length}catch{}}}let Io=Tt.length>0?Tt.join(`
|
|
|
144
144
|
|
|
145
145
|
`):"",It=[a.def.systemPrompt||"",xo,To,Sn,Io,bo||"",wo||""].filter(p=>p.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,kt={channel:w,chatId:$,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:a.def.systemPrompt,sender:bt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||Yr(w,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:te?void 0:uo||void 0,procedureContext:fn,references:bn,skillInjection:mn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Tn??Je,memoryContext:pn||void 0,crossChatContext:wn||void 0,longMemoryRecall:xn||void 0,wikiContext:po,handoverNote:this.buildHandoverNote(e.agentId,w,$),rotationMemo:ho,eventDigest:U?void 0:nc(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=fs(w,!U,a.def.richMessages);return p?rc(a.def.workspace,p):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},Ye=ge.active&&ge.preprocess?await x("select-context",()=>oo(kt),()=>({input:kt,excluded:[]})):{input:kt,excluded:[]};Ye.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ye.excluded.join(", ")}`);let Ve=ar(Ye.input,te?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),ko=Vn(Ve,{memory:hn,procedures:yn,wikiContext:Ye.input.wikiContext}),St=(Ve?.length??0)+(It?.length??0)+(e.message?.length??0),Ze={history:Ve?.length??0,sysPrompt:It?.length??0,message:e.message?.length??0},vn=$r(e.agentId,w,$);Mr(vn,St,Ze);let Cn=Rr(vn);Cn&&this.log(`[${e.agentId}] ${Cn}`),St>16e3&&this.log(`[${e.agentId}] large context for ${w}:${$}: ${St} bytes (history=${Ze.history}, sysPrompt=${Ze.sysPrompt}, message=${Ze.message})`);let vt,An=Hn(a.def.tier,this.config.decisions.routing);if(!e.model&&An&&(!ge.active||ge.preprocess))try{let{routeTaskModel:p}=await import("./routing-
|
|
147
|
+
`)||void 0,kt={channel:w,chatId:$,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:a.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:a.def.systemPrompt,sender:bt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:te||Yr(w,a.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:te?void 0:uo||void 0,procedureContext:fn,references:bn,skillInjection:mn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Tn??Je,memoryContext:pn||void 0,crossChatContext:wn||void 0,longMemoryRecall:xn||void 0,wikiContext:po,handoverNote:this.buildHandoverNote(e.agentId,w,$),rotationMemo:ho,eventDigest:U?void 0:nc(e.agentId,this.config.agents[e.agentId]?.subscriptions??a.def.subscriptions),attachHint:(()=>{let p=fs(w,!U,a.def.richMessages);return p?rc(a.def.workspace,p):void 0})(),intent:Y?{path:Y.path,pathLabel:Y.pathLabel,pathId:Y.pathId,axes:Y.axes,leaf:Y.leaf,status:Y.status}:void 0,message:e.message},Ye=ge.active&&ge.preprocess?await x("select-context",()=>oo(kt),()=>({input:kt,excluded:[]})):{input:kt,excluded:[]};Ye.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${Ye.excluded.join(", ")}`);let Ve=ar(Ye.input,te?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),ko=Vn(Ve,{memory:hn,procedures:yn,wikiContext:Ye.input.wikiContext}),St=(Ve?.length??0)+(It?.length??0)+(e.message?.length??0),Ze={history:Ve?.length??0,sysPrompt:It?.length??0,message:e.message?.length??0},vn=$r(e.agentId,w,$);Mr(vn,St,Ze);let Cn=Rr(vn);Cn&&this.log(`[${e.agentId}] ${Cn}`),St>16e3&&this.log(`[${e.agentId}] large context for ${w}:${$}: ${St} bytes (history=${Ze.history}, sysPrompt=${Ze.sysPrompt}, message=${Ze.message})`);let vt,An=Hn(a.def.tier,this.config.decisions.routing);if(!e.model&&An&&(!ge.active||ge.preprocess))try{let{routeTaskModel:p}=await import("./routing-T66LO3JY.js"),h=await b("route-model",()=>p({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,w,$),cheapModel:An}));h.downgraded&&(vt=h.model,this.log(`[${e.agentId}] ${h.reason}`))}catch{}let So={...e,systemPromptAppend:It,...vt?{model:vt}:{}},re,$n=!1,Mn=Kr({agent:e.agentId,request:e.message,taskId:y,budgetMinutes:a.def.maxExecutionMinutes??20}),vo=_;_=p=>{Mn.observe(p),vo?.(p)};try{let p=this.workflowAutoRunner;if(be&&p){let q=be;try{let z=await b("workflow-auto-run",()=>p({workflowId:q.workflowId,agentId:e.agentId,channel:w,chatId:$,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:w,chatId:$,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:Y?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${be.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:be.workflowId,workflowRunId:z.runId,workflowMatchConfidence:be.confidence}},re}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(a.def.tier==="claude-code"){k("dispatch-gate");let q=a.def.persistentProcess?it():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:w,chatId:$}),ie=!!U||z,ne=[xr(ie),Cr(ie)].find(_e=>_e&&_e.abort);if(ne){a.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ne.reason}`);let _e={content:"",error:ne.message,duration:0};if(!t){f.buffer=`[error] ${ne.message}`;for(let Co of f.subscribers)try{Co(f.buffer)}catch{}}return re=_e,_e}Sr();let Pe=Ar();Pe&&this.log(`[${e.agentId}] ${Pe}`)}let h=a.def.tier==="claude-code",S=h?t:(q,z)=>{q&&T(q),t&&t(q,z)},P=!1,W=h?n:q=>{q&&(P?T(q):(T(`\u{1F4AD} ${q}`),P=!0)),n&&n(q)},K=()=>{P&&(T(`
|
|
148
148
|
`),P=!1)},pe=h?S:S?(q,z)=>{K(),S(q,z)}:void 0,R=await b("agent",()=>zs(a.def,So,this.providers,pe,Ve,U,_,m.signal,W),Va);if(!R.error){let q=oc(a.def.toolUseRequired,v);if(q){let z=Array.from(v.entries()).map(([ie,et])=>`${ie}=${et}`).join(", ")||"none";R.error=`tool_required_not_called: ${q} (invoked: ${z})`,R.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let Ct=this.interruptedRuns.get(g.id);Ct&&(R.content="",R.error=Ct,R.errorKind="interrupted"),re=R;let oe=R.usage?or(R.usage):void 0;if($n=!0,Z().emit("task:completed",{taskId:y,agentId:e.agentId,channel:w,chatId:$,durationMs:Date.now()-dn,error:R.error||void 0,interrupted:Ct?!0:void 0,inputTokens:oe?.inputTokens,outputTokens:oe?.outputTokens,cacheReadTokens:oe?.cacheReadTokens,cacheCreateTokens:oe?.cacheCreateTokens,tier2InputTokens:oe?.tier2InputTokens,tier2OutputTokens:oe?.tier2OutputTokens,tier2CacheReadTokens:oe?.tier2CacheReadTokens,tier2CacheCreateTokens:oe?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:ge.arm,numTurns:R.numTurns,injectedContext:ko,finalResponse:R.content||void 0,billedModel:R.billedModel||a.def.model||void 0,at:new Date().toISOString()}),!t&&(R.content||R.error)){let q=R.error?`[error] ${R.error}`:R.content;f.buffer=q;for(let z of f.subscribers)try{z(q)}catch{}}if(R.error)a.errors++,this.log(`[${e.agentId}] error: ${R.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,$,R.content),Jr({agent:e.agentId,channel:w,chatId:$,request:e.message,reply:R.content,taskId:y}),R.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,$,R.claudeSessionId),R.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,$,R.codexSessionId),R.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,$,R.opencodeSessionId),(R.claudeSessionId||R.codexSessionId||R.opencodeSessionId)&&R.usage&&this.sessions.recordTurnUsage(e.agentId,w,$,R.usage,R.contextTokens),R.usage){let ne=R.contextTokens,Pe=(R.usage.inputTokens||0)+(R.usage.cacheReadTokens||0)+(R.usage.cacheCreateTokens||0);(ne??Pe)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${$}: context=${ne??"n/a"} tokens (cumulative turn total=${Pe}) \u2014 next turn will rotate`)}if(Jn({channel:w,content:`User: ${e.message}`,responseLength:R.content.length}).capture){await ln(Ga);try{let ne=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ne,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
150
|
Agent: ${R.content}`,meta:tc(Y,e.context)})}catch{}Qn(e.agentId,e.message,R.content,{channel:w,chatId:$,sender:bt},this.memoryStore).catch(()=>{}),hr(e.agentId,e.message,R.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=R.billedModel||e.model||a.def.model,ie=e.context?.channel,et=ie&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ie}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,R.duration||0,R.usage,e.message.length,R.content.length,!1,z,ie,et),this.log(`[${e.agentId}] completed in ${R.duration}ms`+(R.tokensUsed?` (${R.tokensUsed} tokens)`:"")+` ${B()}`)}return R}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let h=rt(p.message);return re={content:"",error:ot(h),errorKind:h.kind},re}finally{if(Mn.stop(),!$n)try{Z().emit("task:completed",{taskId:y,agentId:e.agentId,channel:c,chatId:d,durationMs:Date.now()-g.startedAt.getTime(),error:re?.error||(m.signal.aborted?qe(m.signal).message:"run ended before completion"),interrupted:this.interruptedRuns.has(g.id)?!0:void 0,at:new Date().toISOString()})}catch{}M(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=G(process.cwd(),Me,this.safe(e.agentId),t);ee(n)||Ja(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);za(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=G(process.cwd(),Me,this.safe(e));if(!ee(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let g=G(a,u);if(ee(g))try{for(let m of se(g)){if(!m.endsWith(".json"))continue;let f=m.split("-")[0],T=parseInt(f,10);if(!Number.isFinite(T)||T<i||T>n)continue;let y=Math.floor((n-T)/36e5),v=t-1-y;v>=0&&v<t&&o[v]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Me);if(!ee(e))return 0;let t=0;for(let n of se(e)){let r=G(e,n),o;try{o=se(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),c;try{c=se(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ke(G(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let g=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=ec){let t=G(process.cwd(),Me);if(!ee(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of se(t)){let i=G(t,o),a;try{a=se(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Qa(G(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Me,this.safe(e));if(!ee(n))return[];let r=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(n,i),c;try{c=se(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(Ke(G(a,d),"utf-8")),{transcript:u,responseText:g,...m}=l;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Me,this.safe(e));if(!ee(n))return null;let r=this.safe(t),o=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(ee(a))try{return JSON.parse(Ke(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ps();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||st(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),m=!1;if(r.replace){let f=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(f))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${f}`),m=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:m,edited:u,pending:g}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let l=!1,u=g=>{l||(l=!0,d(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{st(g.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?u({ok:!1,status:500,error:g.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>u({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function ac(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{Is as a,mc as b,Ss as c,Lo as d,vs as e,$s as f,Ac as g,Pc as h,_c as i,ei as j,Gs as k,oi as l,ii as m,ai as n,zs as o,lt as p,gt as q,Ei as r,ad as s,cd as t,zt as u,Z as v,mr as w,Wi as x,Ji as y,br as z,vd as A,wr as B,We as C,Pa as D,_a as E,Ea as F,Da as G,Oa as H,tn as I,ol as J,il as K,tc as L,nc as M,sc as N,cn as O,Zr as P,eo as Q,oc as R,to as S,no as T,ac as U};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-P27P7GFY.js.map
|