agentix-cli 0.75.3 → 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/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-7EZ2VOUK.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-NZZVUEWI.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-VJ7AFHJ6.js → chunk-N3Y3NORE.js} +2 -2
- 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-QIN6PV4J.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-6RUMFTIH.js → doctor-74P5CWVW.js} +2 -2
- 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 +1 -1
- package/dist/board-dashboard-7EZ2VOUK.js.map +0 -1
- package/dist/chunk-663BLK67.js.map +0 -1
- package/dist/chunk-NZZVUEWI.js.map +0 -1
- package/dist/chunk-QIN6PV4J.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/program-MVCIUWJ5.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-VJ7AFHJ6.js.map → chunk-N3Y3NORE.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-6RUMFTIH.js.map → doctor-74P5CWVW.js.map} +0 -0
- /package/dist/{program-MVCIUWJ5.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
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{f as j,i as x,p as O,
|
|
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
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
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
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
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
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-
|
|
7
|
+
//# sourceMappingURL=chunk-N3Y3NORE.js.map
|
|
@@ -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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{C as Ze,D as et}from"./chunk-
|
|
1
|
+
import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as tt,b as nt,c as rt,d as S,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as ne,b as We}from"./chunk-FCPTN6NF.js";import{o as we,p as He}from"./chunk-5MUJZODV.js";import{C as Ze,D as et}from"./chunk-SZZSUW42.js";import{a as ot,b as st,c as it,d as at,e as ct,f as ut,g as lt,h as dt,i as pt,j as mt,k as bt,l as ft}from"./chunk-RGDKHYY2.js";import{a as E,b as Ke,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function yt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import ht from"better-sqlite3";import{createHash as wt}from"crypto";import{mkdirSync as Tt}from"fs";import{dirname as Et,resolve as kt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function xt(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function St(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&_t(e),t<2&&Rt(e),t<3&&At(e)}function At(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Rt(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as Te,b as gt}from"./chunk-FX3D7YON.js";import{a as tt,b as nt,c as rt,
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${h}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let x=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=x.answer,x.repaired&&(L=!0)}return{model:a,answers:M,usage:y,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Vt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:U,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:U}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===U),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function zt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Jt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Gt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Bt,qt,Xt,Ue,$t,be=E(()=>{"use strict";He();Fe();gt();j();Y();v();z();Bt="claude-code",qt="claude-haiku-4-5-20251001",Xt=24e3,Ue=2e3,$t=3e4});import{readFileSync as Yt}from"fs";import{homedir as Kt}from"os";import{join as Ht}from"path";function N(e={}){let t=(e.baseUrl??Wt).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??en,s=e.maxChoiceOptions??tn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),sn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=an(a.abortSignal,a.timeoutMs??e.timeoutMs??Zt);try{let b={"Content-Type":"application/json"},y=on(e.apiKeyEnv,e.apiKeyFile);y&&(b.Authorization=`Bearer ${y}`);let w=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:rn(a.questions)}),signal:g}),g);if(!w.ok){let k=await w.text().catch(()=>"");throw new Error(`${n} ${w.status}: ${k.slice(0,300)}`)}let f=await qe(w.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${F(m.error)}`);let h=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let x=_(q,h[k]);M[k]=x.answer,x.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function rn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:nn[n.type]};return t}function on(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Ht(Kt(),t.slice(2)):t;if(!Z.has(n))try{let o=Yt(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function sn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function an(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Wt,Zt,en,tn,nn,Z,fe=E(()=>{"use strict";j();v();z();Y();Wt="http://127.0.0.1:8000/v1",Zt=3e4,en=6e3,tn=50;nn={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};Ke(Xe,{DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>U,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>yt,agreement:()=>ot,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>dt,askSeat:()=>mn,band:()=>Ie,bootstrapInterval:()=>mt,brier:()=>ct,buildDesign:()=>ve,calibrationReport:()=>bt,choice:()=>nt,compareCalibrators:()=>Dt,confidenceFor:()=>re,configureDecisions:()=>un,coverageCurve:()=>lt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>dn,describeIssues:()=>F,ece:()=>it,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>pt,getDecisionBackend:()=>D,getSeatMode:()=>ze,labelsOf:()=>S,listDecisionBackends:()=>Ee,logLoss:()=>ut,logit:()=>le,mce:()=>at,measureConsistency:()=>jt,normalizeDistribution:()=>xe,normalizedNegEntropy:()=>oe,noul:()=>tt,pMax:()=>Se,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>pn,registerBuiltinDecisionBackends:()=>cn,registerDecisionBackend:()=>R,reliabilityBins:()=>st,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>ln,score:()=>rt,seatEnvVar:()=>Ve,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function cn(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();ft();Me();je();Je();pe();be();fe();C();pe();be();fe()});function un(e){T={...ye,...T,...e},ee=!0}function ln(){T={...ye,seats:{}},ee=!1}function bn(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(et(),he(Ze)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}T={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function dn(){return T}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return fn.includes(t)?t:null}function Ve(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function ze(e,t=process.env){bn();let r=ge(t[Ve(e)]);return r||(T.enabled?ge(T.seats[e]?.mode)??"off":"off")}function pn(e,t,r=!1){if(!(!e||!T.store))try{T.store.recordOutcome(e,t,r)}catch{}}async function mn(e,t,r,n={}){let o=ze(e);if(o==="off")return null;let s=T.seats[e]??{mode:o},i=n.backend??s.backend??T.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs}),l=gn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return yn(e,o,t,r,i,n,s,a,u),hn(e,i,u),null}}function gn(e,t,r,n,o,s,i){if(!T.store)return null;try{return T.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:Ye(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function yn(e,t,r,n,o,s,i,a,u){if(T.store)try{T.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:Ye(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function Ye(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function hn(e,t,r){let n=Date.now();n-Ge<6e4||(Ge=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var ye,T,ee,fn,Ge,Je=E(()=>{C();V();ye={enabled:!1,defaultBackend:"local",seats:{},store:null},T={...ye},ee=!1;fn=["off","shadow","active"];Ge=0});export{D as a,Ee as b,C as c,I as d,V as e,Dt as f,Me as g,jt as h,je as i,me as j,Un as k,Fe as l,cn as m,$e as n,un as o,ln as p,dn as q,ge as r,Ve as s,ze as t,pn as u,mn as v,Je as w};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-PDSCFOC4.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-43X3DQTI.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-PK6EBDBU.js.map
|