agentix-cli 0.153.1 → 0.154.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-2SWSYFED.js → App-OL5GYZBS.js} +2 -2
- package/dist/{ChatApp-NYTNFLIB.js → ChatApp-EEHKOZQX.js} +2 -2
- package/dist/{absorb-eval-SYX5QN4H.js → absorb-eval-PVCA7UE6.js} +2 -2
- package/dist/{agent-UCYQELAQ.js → agent-3ETFZSEZ.js} +2 -2
- package/dist/{board-dashboard-UZF7MQZA.js → board-dashboard-RUO6R5NI.js} +4 -4
- package/dist/{chunk-GDLO7FC7.js → chunk-2FH4TULF.js} +2 -2
- package/dist/{chunk-ZAH74SFX.js → chunk-2K2QDTGP.js} +2 -2
- package/dist/{chunk-VAK4LT62.js → chunk-4FKFEWCE.js} +3 -3
- package/dist/chunk-4FKFEWCE.js.map +1 -0
- package/dist/{chunk-IFOFBI3U.js → chunk-5NTEGDXT.js} +2 -2
- package/dist/{chunk-DZRD6BE4.js → chunk-ABKEGNY4.js} +2 -2
- package/dist/{chunk-2J2OES2S.js → chunk-BMZK232D.js} +2 -2
- package/dist/{chunk-XQ2VU6MM.js → chunk-CJKN4APJ.js} +119 -119
- package/dist/chunk-CJKN4APJ.js.map +1 -0
- package/dist/{chunk-3LU2ZQZJ.js → chunk-F5KWRBTF.js} +2 -2
- package/dist/{chunk-HVNWI63Z.js → chunk-FFPQS2C4.js} +2 -2
- package/dist/{chunk-Z2KGUEB6.js → chunk-GDNKUNT7.js} +2 -2
- package/dist/chunk-GVJMPSE2.js +76 -0
- package/dist/chunk-GVJMPSE2.js.map +1 -0
- package/dist/{chunk-FVRREIVV.js → chunk-HF55LKFC.js} +2 -2
- package/dist/{chunk-ZQONMM3B.js → chunk-HOLJZIVJ.js} +2 -2
- package/dist/{chunk-RUQMUDSX.js → chunk-IRDPIQRR.js} +2 -2
- package/dist/{chunk-UUVJX6WD.js → chunk-IYL4YUXQ.js} +2 -2
- package/dist/{chunk-I45WFYGM.js → chunk-JXY7EEAR.js} +2 -2
- package/dist/{chunk-MM3ABEOW.js → chunk-M5TMFCPA.js} +2 -2
- package/dist/{chunk-MWYPW5XP.js → chunk-MKIJAGES.js} +2 -2
- package/dist/{chunk-5DPN2HIR.js → chunk-NKTBJHIF.js} +5 -5
- package/dist/{chunk-BFONYVOM.js → chunk-NUMWHIFL.js} +2 -2
- package/dist/{chunk-RJCHFDF3.js → chunk-RARXW4KB.js} +2 -2
- package/dist/{chunk-3OPW64OM.js → chunk-RTXFDYFR.js} +2 -2
- package/dist/{chunk-CFPRIE6F.js → chunk-TDMX6HTT.js} +2 -2
- package/dist/{chunk-DPSHY7GN.js → chunk-U3PHNPIJ.js} +3 -3
- package/dist/{chunk-LH3GOBZP.js → chunk-USCFJVVI.js} +2 -2
- package/dist/{chunk-S5FRIHWM.js → chunk-UWUJVING.js} +2 -2
- package/dist/{chunk-JPZBWHNZ.js → chunk-VCAVVCXT.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-PBIUMGDL.js → client-WBAWHYAY.js} +2 -2
- package/dist/{config-VLH5DJTH.js → config-VXXKMXHH.js} +2 -2
- package/dist/{config-mutate-G7HW2R6H.js → config-mutate-MMTHEXWM.js} +2 -2
- package/dist/config-mutator-R75BQXMB.js +2 -0
- package/dist/{contributions-GZVKJXSJ.js → contributions-3ZE2TK24.js} +2 -2
- package/dist/{doctor-QWVUVWTF.js → doctor-TP4GSLZV.js} +2 -2
- package/dist/{follow-up-tool-PTKDMFA7.js → follow-up-tool-L3QXZIU2.js} +2 -2
- package/dist/{hub-BHCBRQZP.js → hub-U65U7SE6.js} +2 -2
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/{program-2YK3YCBX.js → program-7WISM624.js} +24 -24
- package/dist/program-7WISM624.js.map +1 -0
- package/dist/{promote-73ZGTRDV.js → promote-GP2MZX7S.js} +2 -2
- package/dist/{query-KHW4AERR.js → query-WHNB46XD.js} +2 -2
- package/dist/{query-settings-P6RUUEFO.js → query-settings-U5ZMQREP.js} +2 -2
- package/dist/{registry-RQBXAPUZ.js → registry-GXGHPROE.js} +2 -2
- package/dist/{request-planner-EUIMJ7R3.js → request-planner-HALSGCA5.js} +2 -2
- package/dist/{review-candidates-KKGDAZIB.js → review-candidates-WIXZZCF7.js} +2 -2
- package/dist/{routing-FQNGOTMV.js → routing-U543HNNU.js} +2 -2
- package/dist/schedule-tool-FIKDTGXF.js +2 -0
- package/dist/{scheduler-JXZBVPOS.js → scheduler-OEKYXZPJ.js} +2 -2
- package/dist/{seat-DZB3NSZ7.js → seat-FWF2HKWS.js} +2 -2
- package/dist/{select-YD4CA7FP.js → select-QDSG7NQX.js} +2 -2
- package/dist/{set-enabled-UK4SE5MZ.js → set-enabled-W7U5SXYX.js} +2 -2
- package/dist/{tool-2PA2USUG.js → tool-QIFV7Q4M.js} +2 -2
- package/dist/{tool-DIJN4XBY.js → tool-VN7W6QGC.js} +2 -2
- package/dist/{wiki-CQBXLZ2Y.js → wiki-TN5WFJ5P.js} +2 -2
- package/dist/wiki-enrich-GEHA6NJQ.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-5VPU5FHB.js +0 -67
- package/dist/chunk-5VPU5FHB.js.map +0 -1
- package/dist/chunk-VAK4LT62.js.map +0 -1
- package/dist/chunk-XQ2VU6MM.js.map +0 -1
- package/dist/config-mutator-XWWW3PSV.js +0 -2
- package/dist/program-2YK3YCBX.js.map +0 -1
- package/dist/schedule-tool-2OWGAK4H.js +0 -2
- package/dist/wiki-enrich-PA6JS2YN.js +0 -2
- /package/dist/{App-2SWSYFED.js.map → App-OL5GYZBS.js.map} +0 -0
- /package/dist/{ChatApp-NYTNFLIB.js.map → ChatApp-EEHKOZQX.js.map} +0 -0
- /package/dist/{absorb-eval-SYX5QN4H.js.map → absorb-eval-PVCA7UE6.js.map} +0 -0
- /package/dist/{agent-UCYQELAQ.js.map → agent-3ETFZSEZ.js.map} +0 -0
- /package/dist/{board-dashboard-UZF7MQZA.js.map → board-dashboard-RUO6R5NI.js.map} +0 -0
- /package/dist/{chunk-GDLO7FC7.js.map → chunk-2FH4TULF.js.map} +0 -0
- /package/dist/{chunk-ZAH74SFX.js.map → chunk-2K2QDTGP.js.map} +0 -0
- /package/dist/{chunk-IFOFBI3U.js.map → chunk-5NTEGDXT.js.map} +0 -0
- /package/dist/{chunk-DZRD6BE4.js.map → chunk-ABKEGNY4.js.map} +0 -0
- /package/dist/{chunk-2J2OES2S.js.map → chunk-BMZK232D.js.map} +0 -0
- /package/dist/{chunk-3LU2ZQZJ.js.map → chunk-F5KWRBTF.js.map} +0 -0
- /package/dist/{chunk-HVNWI63Z.js.map → chunk-FFPQS2C4.js.map} +0 -0
- /package/dist/{chunk-Z2KGUEB6.js.map → chunk-GDNKUNT7.js.map} +0 -0
- /package/dist/{chunk-FVRREIVV.js.map → chunk-HF55LKFC.js.map} +0 -0
- /package/dist/{chunk-ZQONMM3B.js.map → chunk-HOLJZIVJ.js.map} +0 -0
- /package/dist/{chunk-RUQMUDSX.js.map → chunk-IRDPIQRR.js.map} +0 -0
- /package/dist/{chunk-UUVJX6WD.js.map → chunk-IYL4YUXQ.js.map} +0 -0
- /package/dist/{chunk-I45WFYGM.js.map → chunk-JXY7EEAR.js.map} +0 -0
- /package/dist/{chunk-MM3ABEOW.js.map → chunk-M5TMFCPA.js.map} +0 -0
- /package/dist/{chunk-MWYPW5XP.js.map → chunk-MKIJAGES.js.map} +0 -0
- /package/dist/{chunk-5DPN2HIR.js.map → chunk-NKTBJHIF.js.map} +0 -0
- /package/dist/{chunk-BFONYVOM.js.map → chunk-NUMWHIFL.js.map} +0 -0
- /package/dist/{chunk-RJCHFDF3.js.map → chunk-RARXW4KB.js.map} +0 -0
- /package/dist/{chunk-3OPW64OM.js.map → chunk-RTXFDYFR.js.map} +0 -0
- /package/dist/{chunk-CFPRIE6F.js.map → chunk-TDMX6HTT.js.map} +0 -0
- /package/dist/{chunk-DPSHY7GN.js.map → chunk-U3PHNPIJ.js.map} +0 -0
- /package/dist/{chunk-LH3GOBZP.js.map → chunk-USCFJVVI.js.map} +0 -0
- /package/dist/{chunk-S5FRIHWM.js.map → chunk-UWUJVING.js.map} +0 -0
- /package/dist/{chunk-JPZBWHNZ.js.map → chunk-VCAVVCXT.js.map} +0 -0
- /package/dist/{client-PBIUMGDL.js.map → client-WBAWHYAY.js.map} +0 -0
- /package/dist/{config-VLH5DJTH.js.map → config-VXXKMXHH.js.map} +0 -0
- /package/dist/{config-mutate-G7HW2R6H.js.map → config-mutate-MMTHEXWM.js.map} +0 -0
- /package/dist/{config-mutator-XWWW3PSV.js.map → config-mutator-R75BQXMB.js.map} +0 -0
- /package/dist/{contributions-GZVKJXSJ.js.map → contributions-3ZE2TK24.js.map} +0 -0
- /package/dist/{doctor-QWVUVWTF.js.map → doctor-TP4GSLZV.js.map} +0 -0
- /package/dist/{follow-up-tool-PTKDMFA7.js.map → follow-up-tool-L3QXZIU2.js.map} +0 -0
- /package/dist/{hub-BHCBRQZP.js.map → hub-U65U7SE6.js.map} +0 -0
- /package/dist/{promote-73ZGTRDV.js.map → promote-GP2MZX7S.js.map} +0 -0
- /package/dist/{query-KHW4AERR.js.map → query-WHNB46XD.js.map} +0 -0
- /package/dist/{query-settings-P6RUUEFO.js.map → query-settings-U5ZMQREP.js.map} +0 -0
- /package/dist/{registry-RQBXAPUZ.js.map → registry-GXGHPROE.js.map} +0 -0
- /package/dist/{request-planner-EUIMJ7R3.js.map → request-planner-HALSGCA5.js.map} +0 -0
- /package/dist/{review-candidates-KKGDAZIB.js.map → review-candidates-WIXZZCF7.js.map} +0 -0
- /package/dist/{routing-FQNGOTMV.js.map → routing-U543HNNU.js.map} +0 -0
- /package/dist/{schedule-tool-2OWGAK4H.js.map → schedule-tool-FIKDTGXF.js.map} +0 -0
- /package/dist/{scheduler-JXZBVPOS.js.map → scheduler-OEKYXZPJ.js.map} +0 -0
- /package/dist/{seat-DZB3NSZ7.js.map → seat-FWF2HKWS.js.map} +0 -0
- /package/dist/{select-YD4CA7FP.js.map → select-QDSG7NQX.js.map} +0 -0
- /package/dist/{set-enabled-UK4SE5MZ.js.map → set-enabled-W7U5SXYX.js.map} +0 -0
- /package/dist/{tool-2PA2USUG.js.map → tool-QIFV7Q4M.js.map} +0 -0
- /package/dist/{tool-DIJN4XBY.js.map → tool-VN7W6QGC.js.map} +0 -0
- /package/dist/{wiki-CQBXLZ2Y.js.map → wiki-TN5WFJ5P.js.map} +0 -0
- /package/dist/{wiki-enrich-PA6JS2YN.js.map → wiki-enrich-GEHA6NJQ.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-U3PHNPIJ.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
|
|
2
2
|
`)}).join(`
|
|
3
3
|
|
|
4
4
|
---
|
|
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
|
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
16
|
`}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-HF55LKFC.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as d}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as d}from"./chunk-USCFJVVI.js";import{b as i,c as u,d as l,e as c}from"./chunk-NUMWHIFL.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-HOLJZIVJ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-VCAVVCXT.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-IRDPIQRR.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-HF55LKFC.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-IYL4YUXQ.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-HOLJZIVJ.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-NUMWHIFL.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
2
|
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-JXY7EEAR.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as w}from"./chunk-
|
|
1
|
+
import{c as w}from"./chunk-HF55LKFC.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
|
|
2
2
|
${a.content}`),t.previous??""].join(`
|
|
3
3
|
`),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
|
|
4
4
|
`).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
|
|
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
|
|
|
33
33
|
{"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
|
|
34
34
|
`)+`
|
|
35
35
|
`}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
36
|
+
//# sourceMappingURL=chunk-M5TMFCPA.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-GXGHPROE.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-MKIJAGES.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as Hr,H as Mr,I as Rr,J as Pr,L as _r,M as Er,N as Or,O as Dr,R as Nr,S as Lr,V as Ur,W as Fr,a as pr,b as fr,ba as jr,d as hr,f as Xe,l as At,m as Ar,t as Ct,v as Cr}from"./chunk-
|
|
1
|
+
import{$ as Hr,H as Mr,I as Rr,J as Pr,L as _r,M as Er,N as Or,O as Dr,R as Nr,S as Lr,V as Ur,W as Fr,a as pr,b as fr,ba as jr,d as hr,f as Xe,l as At,m as Ar,t as Ct,v as Cr}from"./chunk-UWUJVING.js";import{b as mr}from"./chunk-MEFPXHQJ.js";import{a as $r}from"./chunk-W4YR2RO2.js";import{a as gr}from"./chunk-5TTHN7DP.js";import{b as wr,c as xn,d as xr,e as $t,h as Sr}from"./chunk-USCFJVVI.js";import{e as ur,f as lr}from"./chunk-36AXN6ZB.js";import{a as wn,b as yr}from"./chunk-J3SOEFRE.js";import{a as bn,b as br}from"./chunk-SIU6STB2.js";import{e as Ir,i as Tr,j as kr,k as vr}from"./chunk-X5C5W3E4.js";import{a as dr}from"./chunk-IRDPIQRR.js";import{g as ar,h as cr}from"./chunk-RARXW4KB.js";import{c as Qs,f as Xs}from"./chunk-GDNKUNT7.js";import{s as Js,v as vt,w as zs,y as we,z as yn}from"./chunk-FFPQS2C4.js";import{a as Qe,b as Oe,f as kt}from"./chunk-72SZI2UW.js";import{a as Ee,b as gn}from"./chunk-FCPTN6NF.js";import{a as Ys,c as Zs}from"./chunk-MYVHVJWZ.js";import{d as De,g as Vs,h as Ce}from"./chunk-6TURWSMN.js";import{a as er,b as tr,c as nr,d as sr,l as rr}from"./chunk-AV7T3SYT.js";import{a as or,b as ir}from"./chunk-U23LVMMZ.js";import{c as Ds,d as Ns}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ua as gc,V as Hs,X as mn,Z as uc,aa as js,ea as lc,ka as Bs,la as hn,ma as Ws,na as ze,oa as qs,pa as Gs,va as Ks}from"./chunk-GVJMPSE2.js";import{g as Je,h as cc}from"./chunk-BRK6M6LA.js";import{f as fn,n as dc}from"./chunk-UIBUZ2N3.js";import{a as Ls,b as ge,c as Us,d as Fs,e as pn}from"./chunk-2QNT5JDS.js";yn();kt();var Mt="tool-set",Br=["answer","code","full"],Wr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},pc=.1;function Gr(n){return{task:qr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:qr(n.agentPrompt,600)}:{}}}var Kr={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function Jr(n,e=pc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Sn(s.answer),o=Sn(s.code),i=Sn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function zr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Wr.answer.includes(t))?"answer":e.every(t=>Wr.code.includes(t))?"code":"full"}function Qr(n,e){return Br.indexOf(n)<Br.indexOf(e)}function Sn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function qr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Xr=!1;function Yr(n,e){let t=vt(Mt);if(t!=="off")return t==="active"&&!Xr&&(Xr=!0,e(`[decisions] seat "${Mt}" is set to active, but only shadow is built: it records and changes nothing`)),we(Mt,Gr(n),Kr,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=Jr(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Zr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=zr(r);zs(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(Qr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function fc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Vr(n,e){let t=fc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function In(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}yn();kt();var eo="session-continuity",to={continues:Qe("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:Qe("Does the new request refer to something stated earlier in the conversation?")};function no(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:Tn(n.message,1200),previousRequest:n.previousMessage?Tn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Tn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function so(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function Tn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ut}from"execa";import{spawn as mc}from"node:child_process";import{createHash as hc}from"node:crypto";import{createInterface as yc}from"node:readline";var be=class extends Error{},wc=n=>mc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),kn=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(),yc({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 s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},vn=class{constructor(e=wc,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}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 s=hc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([x],[$])=>x.localeCompare($))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new be("Conversation already running");r&&(r.fingerprint!==s||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 x=[...this.entries].find(([,$])=>!$.connection.busy);if(!x)throw new be("Codex warm process capacity reached");x[1].connection.close(),this.entries.delete(x[0])}try{r={fingerprint:s,connection:new kn(e,this.launchProcess)}}catch{throw new be("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,d="",c,u,l,p,m=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),y=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 x={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...x,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(y),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let R=new Promise((E,k)=>{i.failTurn=k,i.notify=(L,N)=>{if(N?.threadId!==u)return;let O=N.item,B={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:L.replace("/","."),...O?{item:{...O,type:B[O.type]||O.type}}:{}}),L==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(c=O.text),L==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=N.delta,e.onDelta?.(N.delta,d)),L==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}L==="turn/completed"&&(N.turn.status==="completed"?E():k(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return R.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await R,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(x){if(i.close(),!a&&!e.signal?.aborted)throw new be(x.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:x.message,duration:Date.now()-t}}finally{clearTimeout(y),clearTimeout(b),e.signal?.removeEventListener("abort",h),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())}}},ro=new vn;import{execFile as Fc}from"child_process";import{StringDecoder as tt}from"string_decoder";import{mkdtempSync as To,readFileSync as ko,rmSync as vo}from"fs";import{join as Nt}from"path";import{tmpdir as $o}from"os";function Rt(n){let e=(n||"").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 c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[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]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,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),d=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"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===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"||d===529||d===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"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,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 Pt(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function _t(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var oo=null;function Et(){return oo}function Fg(n){oo=n}function Ye(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function bc(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var Ne=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},io=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 s=Ye(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=bc(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${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 Ne(`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 Ne(`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(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Ye(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ye(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=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<s&&(s=i,t=o)}if(!t)return!1;let r=Ye(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,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.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),s.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(s.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";s.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as xc}from"child_process";import{randomUUID as Sc}from"crypto";import{existsSync as Ic,readFileSync as Tc}from"fs";import{resolve as kc}from"path";function vc(n){let e=kc(n,"CLAUDE.md");if(!Ic(e))return null;try{let t=Tc(e,"utf8");return rr(t)}catch{return null}}var $c=20*60*1e3,Ac=5e3,Ze=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ve=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function Cc(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var ao=class{constructor(e={}){this.opts=e}spawn(e,t){return new $n(e,t,this.opts)}},$n=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=xc(r,o,{cwd:t.workspace,env:Ce(Cc({...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:vc(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 d=this.waiters.splice(0);for(let c of d)c(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;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),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=Sc(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let d=e.deadlineMs??$c,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new Ze(d)),l=!1,p=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let h=await this.nextEvent(m);if(h===null&&this.killReason)throw new Ve(this.killReason);if(h===null&&!this.exited)throw u();if(h===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(h.type==="user"&&h.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(h.type==="system"&&h.subtype==="init")p=h;else if(h.type==="result"){p=null;let b=typeof h.result=="string"?h.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:h.type,raw:h},h.type==="result"){this.onResultEvent(h);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{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 s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Ac);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];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),e.extraArgs&&t.push(...e.extraArgs),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 s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}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 s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=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:s,state:"idle"}}};pn();dc();gn();import{resolve as co,join as uo}from"path";var Mc=4e3;function Ot(n){try{let e=uo(co(n.root),".agentx","db.sqlite"),t=fn({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,Mc):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function jc(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};E.stdout?.on("data",T=>{O+=F.write(T);let S=O.split(`
|
|
32
32
|
`);O=S.pop()||"";for(let U of S)z(U)}),E.stderr?.on("data",T=>{B+=q.write(T)});let A=await E;if(i&&i.removeEventListener("abort",N),O+=F.end(),O.trim()&&z(O),B+=q.end(),k)return{content:"",error:L||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(A.exitCode!==0||h){let T=A,S;return T.timedOut?S=`OpenCode timed out after ${Math.round($/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:h?S=h:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+B)?S=xo():S=B.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(S),duration:Date.now()-d,usage:p,opencodeSessionId:m}}return y=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch($){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let R=/ENOENT|spawn opencode/i.test($?.message||"")?xo():$?.message;return{content:l,...V(R||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:m}}finally{x?.(),b?.release(y)}}async function Zc(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Vc(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let y=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(y))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let h=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);h.unref?.();let b=()=>({content:"",...V(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let y=n.provider||"claude-code",x=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,$=e.context?.sender,R=typeof $=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),E=e.context?.channel==="web-chat"&&R?{userId:$,agentId:e.agentId||"acme-public"}:void 0,k=sr(n),L=Object.keys(k).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:l.signal,mcpServers:L?k:void 0};if(r){let{generateStream:z}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,$=e.context?.sender,R=typeof $=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test($),E=e.context?.channel==="web-chat"&&R?{userId:$,agentId:e.agentId||"acme-public"}:void 0,k=sr(n),L=Object.keys(k).length>0,N={task:x,cwd:n.workspace,provider:y,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:E,providerOpts:o,abortSignal:l.signal,mcpServers:L?k:void 0};if(r){let{generateStream:z}=await import("./agent-3ETFZSEZ.js"),A="",T,S,U,j;for await(let P of z(N)){if(d)try{d(P)}catch{}if(P.type==="text_delta")A+=P.text,r(P.text,A);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}T=P.result.tokensUsed,P.result.inputTokens!=null&&(S=P.result.inputTokens),P.result.outputTokens!=null&&(U=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==A){let Q=P.result.content.slice(A.length);Q?(A=P.result.content,r(Q,A)):A=P.result.content}P.result.tokensUsed!=null&&(T=P.result.tokensUsed)}else P.type==="error"&&(j=P.error)}return j&&!A?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${j}`),duration:Date.now()-c}:((S===void 0||U===void 0)&&T&&(S=Math.round(T*.7),U=T-S),{content:A||"Done.",tokensUsed:T,usage:S!==void 0||U!==void 0?{inputTokens:S||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:O}=await import("./agent-3ETFZSEZ.js"),B=await O(N),F=B.inputTokens,q=B.outputTokens;if((F===void 0||q===void 0)&&B.tokensUsed){let z=B.tokensUsed;F=Math.round(z*.7),q=z-F}return{content:B.content||"Done.",tokensUsed:B.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(y){return p?b():y?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...V(`Orchestrator error: ${y.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",m)}}var Cn=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},ed=1e3;async function td(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),ed),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function nd(n,e,t,s,r,o,i){let a=Et();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Ht(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let A=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>A}catch(A){return A instanceof Ne,null}m&&_n(e.agentId,n,e.model,s,"persistent");let h=Se(n,e,t),b="",y,x,$,R,E,k,L,N="",O="",B=A=>{if(!i||!A)return;let T;if(O&&A.startsWith(O)?T=A.slice(O.length):T=N&&!N.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${A}`:A,O=A,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let z=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(z=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let S=T.raw.message?.content??[];for(let j of S)j.type==="text"&&typeof j.text=="string"?(b=j.text,B(j.text)):j.type==="tool_use"&&(O="");let U=T.raw.message?.usage;if(U){let j=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);j>0&&(R=j)}}if(T.type==="result"){let S=T.raw;if(S.is_error){let U=V(typeof S.result=="string"?S.result:"claude error");y=U.error,x=U.errorKind}else typeof S.result=="string"&&S.result.length>0&&(b=S.result,N||B(S.result));typeof S.session_id=="string"&&(L=S.session_id),S.usage&&($={inputTokens:S.usage.input_tokens||0,outputTokens:S.usage.output_tokens||0,cacheReadTokens:S.usage.cache_read_input_tokens||0,cacheCreateTokens:S.usage.cache_creation_input_tokens||0}),typeof S.num_turns=="number"&&(E=S.num_turns),typeof S.message?.model=="string"?k=S.message.model:typeof S.model=="string"?k=S.model:k=_t(S.modelUsage)||k}}}catch(A){if(F)y="task cancelled by operator",x="cancelled";else if(z)if(A instanceof Ve)y=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,x="interrupted";else if(A instanceof Ze){let T=V(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);y=T.error,x=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);y=T.error,x=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!y&&(y="task cancelled by operator",x="cancelled"),{content:F?"":b,error:y,errorKind:x,duration:Date.now()-d,usage:$,contextTokens:R,numTurns:E,billedModel:k,claudeSessionId:L}}function No(n){let e=ge(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?po(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:wo(t.args,n.taskId,n.agentId)}function sd(n){return ge(n.autonomy)||!!n.personLimits}async function rd(n,e,t,s,r,o,i){let a=ge(e.autonomy)?e.autonomy:void 0,d=a&&fo(a,n.tier)||e.personLimits&&bo(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${Fs(a)}
|
|
@@ -159,7 +159,7 @@ ${Ta(c.number,this.specTestSettings().agent)}`:t.message,settings:o,store:this.c
|
|
|
159
159
|
${e.message}`),e.queuedAt=void 0}let h=ei({message:e.message,home:e.context?.home}),b=Vo(c.runningTasks,h,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});b&&(this.log(`[${e.agentId}] ${b.slice(0,160)}`),e.message=`${b}
|
|
160
160
|
${e.message}`),c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let y={...h.length?{homes:h}:{},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,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};c.runningTasks.push(y),e.runningTaskId=y.id;let x=hn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(y.id,e.context??{}),e.onStart)try{e.onStart(y.id)}catch{}let $=new AbortController;this.taskAborts.set(y.id,{agentId:e.agentId,channel:y.channel,chatId:typeof y.chatId=="string"?y.chatId:"",originalMessage:e.message||"",controller:$,sender:e.context?.sender,rootId:$t()?.rootId,workflowRunId:e.workflowRunId??(typeof y.chatId=="string"&&y.chatId.startsWith("workflow:")&&y.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let R={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(y.id,R);let E=g=>{if(g){R.buffer+=g,R.buffer.length>_a&&(R.buffer=R.buffer.slice(R.buffer.length-_a));for(let f of R.subscribers)try{f(g)}catch{}}},k=Ee();e.taskId=k,y.traceId=k;let L=this.taskAborts.get(y.id);L&&(L.traceId=k);let N=new Map,O=(g,f,C)=>{try{ee().emit("task:step",{taskId:k,agentId:e.agentId,name:"pipeline",action:g,status:C,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},B=0,F=!1,q=()=>{F||(F=!0,B&&O("first-event",B,"ok"))},z;if(t){let g=Tg();z=f=>{q();let C=g(f);if(C&&E(C),Da(k,e.agentId,f),Oa(N,f),Hn(f,void 0,e.model||c.def.model),r)try{r(f)}catch{}}}else z=g=>{if(q(),Da(k,e.agentId,g),Oa(N,g),Hn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let A=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,T=A?setTimeout(()=>$.abort(new Error(`timed out after ${Math.round(A/1e3)}s`)),A):void 0;T?.unref?.();let S=(c.def.preSpawnTimeoutSec??mg)*1e3,U=setTimeout(()=>{$.abort(new Error(`timed out before spawn after ${Math.round(S/1e3)}s in step "${y.step??"start"}"`))},S);U.unref?.();let j=()=>{U&&clearTimeout(U),U=void 0},P=()=>`task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`,Q;$.signal.addEventListener("abort",()=>{let g=_e($.signal).message;/^timed out/.test(g)&&(Q=y.step??"start"),this.log(`[${e.agentId}] task ${y.id} aborted in step "${y.step??"start"}" \u2014 ${g} ${P()}`)},{once:!0});let ne=g=>{y.step=g,this.log(`[${e.agentId}] step ${g} ${P()}`)},X=(g,f,C=0)=>{if($.signal.aborted)return Promise.reject(_e($.signal));ne(g),(g==="agent"||g==="workflow-auto-run")&&(j(),B=Date.now());let v=Date.now(),W=da(f(),ug[g]??0,g);return ca(W,$.signal,C).then(G=>(O(g,v,"ok"),G),G=>{throw O(g,v,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${P()}`),G})},_=async(g,f,C,v=0)=>{try{return await X(g,f,v)}catch(W){if(W instanceof Be)return C();throw W}},se=!1,ie=!1,ns=g=>{if(!(!se||ie)){ie=!0;try{ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-y.startedAt.getTime(),error:g?.error||($.signal.aborted?_e($.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(y.id)?!0:void 0,stopped:!this.interruptedRuns.has(y.id)&&(this.stoppedRuns.has(y.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ss=!1,rs=g=>{if(ss)return;ss=!0,ns(g),this.runReleases.delete(y.id),T&&clearTimeout(T),j(),c.activeTasks--;let f=c.runningTasks.findIndex(v=>v.id===y.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(y.id),this.taskAborts.delete(y.id);let C=this.runEndWaiters.get(y.id);this.runEndWaiters.delete(y.id);for(let v of C??[])try{v()}catch{}R.done=!0,R.endedAt=new Date;for(let v of R.subscribers)try{v(`
|
|
161
161
|
[task finished]
|
|
162
|
-
`)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),pg).unref?.();try{let v=R.endedAt,W={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(W);let G=(W.responseText||W.error||"").trim();if(G){let Z=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Z,at:v,ok:W.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let W=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,at:new Date().toISOString()});for(let Z of v){let $e=Z.originalContext||{channel:Z.channel,sender:Z.sender,chatId:Z.chatId};this.execute({message:Z.text,agentId:e.agentId,context:$e,queuedAt:Z.queuedAt??Z.timestamp}).then(me=>(Xe(me.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw G(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,rs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${P()}`);let w=e.context?.channel||"api",{evaluateRequest:Ua,selectRequestContext:Fa}=await import("./request-planner-EUIMJ7R3.js"),os=_("request-gate",()=>Ua(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),nn=!1;os.then(()=>{nn=!0},()=>{nn=!0});let I=l,sn=e.context?.sender||"User",de=c.def.tier==="codex-cli",qe=Ei(this.config.session,w,c.def.tier),ut=Oi(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await _("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ha=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ia({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ha,taskId:k}),this.sessions.addUserMessage(e.agentId,w,I,sn,e.message);let is=Date.now(),as={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(is).toISOString(),taskId:k,resumeOrigin:zo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:mn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Hs(e.context),operator:js(e.context),dueAt:aa(e.context),taskType:Yt(e.context)};ee().emit("task:started",as),se=!0;let te,rn,cs=this.classifier;if(cs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();rn=cs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(y.intentPath=te.path.slice()),O("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),O("classify",g,"error")})}let ds=async g=>{if(!rn)return;let f;await Promise.race([rn,new Promise(C=>{f=setTimeout(C,g),f.unref?.()})]),f&&clearTimeout(f)};await ds(rg);let Te=this.config.workflows?.matching,fe,us,ls=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ls?.enabled&&(ls.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(us=Cr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Mr(this.config.workflows,e.agentId)&&Rr(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list()),C=Te?.autoRunThreshold??.85;f&&f.confidence>=C&&(fe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?dg():void 0,ja=ae?Pr(ae):void 0,Ba=this.wikiHub.getAgentWiki(e.agentId),gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),ps=this.memoryStore.buildContext(gs),fs=this.memoryStore.contextFacts(gs),Wa=this.patternStore.findRelevant(e.message,e.agentId,5),qa=this.patternStore.buildContext(Wa),ms="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),C=await X("skills",()=>g(c.def.workspace)),v=e.personLimits?.skills??[],W=v.length?C.filter(G=>!v.some(Z=>ze(Z,G.frontmatter.name))):C;ms=f(W,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=Vr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${In(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"cost");let C=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:C,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${In(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await _("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(H=void 0)}try{let g=await X("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",C=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${C} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Ga=process.env.AGENTX_CONTEXT_SURGERY==="1",Ka=de?{maxMessages:8,maxChars:2400}:Ga&&Pa(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ja=!H&&!de?xg(Ba,e.agentId,{notesInbox:bg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Ka):void 0,za=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,hs,ys=[];if(this.config.procedures?.injection?.enabled&&!H&&!de)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){hs=Gn(f),ys=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,C=f[0],v=f[f.length-1],W=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
|
|
162
|
+
`)}catch{}R.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(y.id),pg).unref?.();try{let v=R.endedAt,W={id:y.id,agentId:e.agentId,channel:y.channel,chatId:y.chatId,sender:y.sender,message:e.message||"",startedAt:y.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-y.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(y.id)||g?.errorKind==="stopped"?{status:"stopped"}:Q?{status:"timeout",step:Q}:{},responseText:g?.content||"",transcript:R.buffer};this.persistTaskRecord(W);let G=(W.responseText||W.error||"").trim();if(G){let Z=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Z,at:v,ok:W.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(v=>{if(v.length===0)return;this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${y.id} chat=${u}:${l} at=${new Date().toISOString()}`);let W=Date.now();ee().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,count:v.length,at:new Date().toISOString()});let G=()=>ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:W,at:new Date().toISOString()});for(let Z of v){let $e=Z.originalContext||{channel:Z.channel,sender:Z.sender,chatId:Z.chatId};this.execute({message:Z.text,agentId:e.agentId,context:$e,queuedAt:Z.queuedAt??Z.timestamp}).then(me=>(Xe(me.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,me)),me=>{throw G(),me}).catch(me=>{this.log(`[${e.agentId}] queued message failed: ${me.message}`)})}}).catch(v=>{ee().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(y.id,rs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${P()}`);let w=e.context?.channel||"api",{evaluateRequest:Ua,selectRequestContext:Fa}=await import("./request-planner-HALSGCA5.js"),os=_("request-gate",()=>Ua(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),nn=!1;os.then(()=>{nn=!0},()=>{nn=!0});let I=l,sn=e.context?.sender||"User",de=c.def.tier==="codex-cli",qe=Ei(this.config.session,w,c.def.tier),ut=Oi(this.config.session),ue=e.isolated===!0,Ge=!ue&&qe==="lean"&&ut.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${I}`),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}));let lt=this.sessions.sessionIdleMs(e.agentId,w,I);e.freshSession||await _("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,I,e.seedHistory),()=>{});let Ha=[...this.sessions.getSession(e.agentId,w,I).messages].reverse().find(g=>g.role==="agent")?.content;ia({agent:e.agentId,channel:w,chatId:I,message:e.message,previousReply:Ha,taskId:k}),this.sessions.addUserMessage(e.agentId,w,I,sn,e.message);let is=Date.now(),as={agentId:e.agentId,channel:w,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(is).toISOString(),taskId:k,resumeOrigin:zo(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:mn(e.context),...x?{person:x}:{},humanRoot:Je(e.context),pickup:Hs(e.context),operator:js(e.context),dueAt:aa(e.context),taskType:Yt(e.context)};ee().emit("task:started",as),se=!0;let te,rn,cs=this.classifier;if(cs&&w!=="a2a"&&!de){ne("classify");let g=Date.now();rn=cs.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{te=f||void 0,te?.path?.length&&(y.intentPath=te.path.slice()),O("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),O("classify",g,"error")})}let ds=async g=>{if(!rn)return;let f;await Promise.race([rn,new Promise(C=>{f=setTimeout(C,g),f.unref?.()})]),f&&clearTimeout(f)};await ds(rg);let Te=this.config.workflows?.matching,fe,us,ls=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&ls?.enabled&&(ls.agents[e.agentId]??!0)&&!i&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&(us=Cr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?fe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Mr(this.config.workflows,e.agentId)&&Rr(e)?this.workflowRuns:void 0;if(ke&&!fe&&!i&&this.workflowAutoRunner&&Je(e.context))try{let g=new At({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Ct({agentId:e.agentId,channel:w,message:e.message,intentPath:te?.path},g.list()),C=Te?.autoRunThreshold??.85;f&&f.confidence>=C&&(fe={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?dg():void 0,ja=ae?Pr(ae):void 0,Ba=this.wikiHub.getAgentWiki(e.agentId),gs=this.memoryStore.findRelevant(e.message,e.agentId,de?3:8),ps=this.memoryStore.buildContext(gs),fs=this.memoryStore.contextFacts(gs),Wa=this.patternStore.findRelevant(e.message,e.agentId,5),qa=this.patternStore.buildContext(Wa),ms="";if(!de)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),C=await X("skills",()=>g(c.def.workspace)),v=e.personLimits?.skills??[],W=v.length?C.filter(G=>!v.some(Z=>ze(Z,G.frontmatter.name))):C;ms=f(W,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,I):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,I):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,I):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,I,lt)&&(this.log(`[${e.agentId}] session stale for ${w}:${I}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,I)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,I);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${I} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,I)){let g=this.sessions.getTurnCount(e.agentId,w,I);this.log(`[${e.agentId}] max-turns rotation for ${w}:${I} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=Vr({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,I),idleMs:lt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${I}: ${In(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,I,"cost");let C=this.sessions.getLastTurnInputTokens(e.agentId,w,I);this.sessions.clearClaudeSessionId(e.agentId,w,I),ee().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:I,reason:"cost",lastTurnInputTokens:C,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${I}: would ${In(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await _("rotate",()=>this.maybeRotateForContinuity(e,c,w,I,g),()=>!1)&&(H=void 0)}try{let g=await X("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,I,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",C=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${I} (quality: ${f}%, ${C} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let v=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${v.overallScore} (lexicon=${v.lexiconDecay}, tools=${v.toolShift}, semantic=${v.semanticDrift})`),v.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${v.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let Ga=process.env.AGENTX_CONTEXT_SURGERY==="1",Ka=de?{maxMessages:8,maxChars:2400}:Ga&&Pa(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ja=!H&&!de?xg(Ba,e.agentId,{notesInbox:bg(this.config)}):void 0,gt=!H&&!Ge?this.sessions.buildHistoryContext(e.agentId,w,I,Ka):void 0,za=H?void 0:this.sessions.getRotationMemo(e.agentId,w,I)??void 0,hs,ys=[];if(this.config.procedures?.injection?.enabled&&!H&&!de)try{let g=new it({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=qn(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){hs=Gn(f),ys=f.map(C=>({id:C.procedure.meta.id,title:C.procedure.meta.title}));for(let C of f)this.log(`[${e.agentId}] procedure match ${C.procedure.meta.id} score=${C.score.toFixed(2)} (${C.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,I).messages,C=f[0],v=f[f.length-1],W=gt===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${gt.length}c/${gt.split(`
|
|
163
163
|
`).length}L`,G=`[${e.agentId}] ${w}:${I} ${W} | session.messages=${f.length}`+(f.length>0?` first=${C.timestamp.slice(11,19)}(${C.role}:${(C.content||"").slice(0,40).replace(/\n/g," ")}) last=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let ws;if(c.def.contextReferences&&!H)try{let g=c.def.workspace,f=this.referencesCache.get(g);if(!f){let[v,W]=await X("references",()=>Promise.all([wn(c.def.workspace),bn(c.def.workspace)]));if(v.byId.size===0&&W.recipes.length===0){let[G,Z]=await X("references",()=>Promise.all([wn(process.cwd()),bn(process.cwd())]));f={refs:G,recipes:Z}}else f={refs:v,recipes:W};this.referencesCache.set(g,f)}let C=br({agentId:e.agentId,intentTags:te?.path,message:e.message},f.recipes,f.refs);C.cards.length>0&&(ws=yr(C.cards,500*4)),C.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${C.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let bs=ue||Ge?"":this.sessions.getCrossSessionSummary(e.agentId,w,I,e.message),xs,pt=ue?null:Ho(e.message);if(pt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:I,lookbackDays:pt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${pt.lookbackDays}d on this chat (cue-triggered)]`],C=[...g.turns].sort((v,W)=>v.ts.localeCompare(W.ts));for(let v of C){let W=v.ts.slice(11,16)+" "+v.day,G=v.role==="user"?v.senderName||"User":v.senderName||"Agent";f.push(`${W} ${G}: ${v.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),xs=f.join(`
|
|
164
164
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${pt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Qa=de?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Ss,Is,Ts=!1;nn||ne("request-gate");let ve=await os;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Qa==="planner"&&!ue&&!ve.active&&!Ge&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-DJB6CKY6.js"),f=await X("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Ts=!0,Ss=f.sessionHistory,ps=f.memoryContext,fs=f.memoryFacts,bs=f.crossChatContext,Is=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Ts&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,I),H=void 0)}let on=`${e.agentId}:${w}:${I}`,ft=nr(e.message);ft&&(ft==="default"?(this.activeSouls.delete(on),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(on,ft),this.log(`[${e.agentId}] Soul switched to: ${ft}`)));let Xa=this.activeSouls.get(on),Ya=er(c.def.workspace,Xa),Za=tr(Ya),Va=ue?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),ec=gg(c.def.tier),tc=kg(c.def.richMessages,w),nc=c.def.tier==="claude-code"&&(ue||qe!=="lean"||Di(ut)),ks="";if(c.def.workspace&&!nc){let g=K(c.def.workspace,"CLAUDE.md");if(ce(g))try{let f=ct(g,"utf-8");ks=`[Project CLAUDE.md]
|
|
165
165
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
@@ -173,9 +173,9 @@ ${$e}`),f+=$e.length}catch{}}}let sc=an.length>0?an.join(`
|
|
|
173
173
|
|
|
174
174
|
`)||void 0,ht={channel:w,chatId:I,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:sn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:de||Ge||Pa(w,c.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:de?void 0:qa||void 0,procedureContext:[hs,us].filter(Boolean).join(`
|
|
175
175
|
|
|
176
|
-
`)||void 0,workflowRunContext:ja,references:ws,skillInjection:ms||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ss??gt,memoryContext:ps||void 0,crossChatContext:bs||void 0,longMemoryRecall:xs||void 0,contextOnDemand:Ge&&!H?ji(w,I):void 0,wikiContext:Ja,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(as)}catch{return}})(),rotationMemo:za,eventDigest:H?void 0:wg(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Hr(w,!H,c.def.richMessages);return g?Sg(c.def.workspace,g):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ue&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:Xs({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let vs=Qs(c.def.tier,this.config.decisions.routing),$s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&vs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
176
|
+
`)||void 0,workflowRunContext:ja,references:ws,skillInjection:ms||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ss??gt,memoryContext:ps||void 0,crossChatContext:bs||void 0,longMemoryRecall:xs||void 0,contextOnDemand:Ge&&!H?ji(w,I):void 0,wikiContext:Ja,handoverNote:this.buildHandoverNote(e.agentId,w,I),watcherNote:(()=>{try{return this.runNote?.(as)}catch{return}})(),rotationMemo:za,eventDigest:H?void 0:wg(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Hr(w,!H,c.def.richMessages);return g?Sg(c.def.workspace,g):void 0})(),intent:te?{path:te.path,pathLabel:te.pathLabel,pathId:te.pathId,axes:te.axes,leaf:te.leaf,status:te.status}:void 0,message:e.message};ue&&Object.assign(ht,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let yt=e.model?void 0:Xs({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?lt:null});yt?.downgraded&&this.log(`[${e.agentId}] ${yt.reason}`);let vs=Qs(c.def.tier,this.config.decisions.routing),$s=yt?.downgraded?Promise.resolve(yt.model):!e.model&&vs&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-U543HNNU.js"),f=await X("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?lt:null,cheapModel:vs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),As=!1;$s.then(()=>{As=!0});let wt=ve.active&&ve.preprocess?await _("select-context",()=>Fa(ht),()=>({input:ht,excluded:[]})):{input:ht,excluded:[]};wt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${wt.excluded.join(", ")}`);let bt=Jo(wt.input,de?{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),rc=gr(bt,{memory:fs,procedures:ys,wikiContext:wt.input.wikiContext}),dn=(bt?.length??0)+(cn?.length??0)+(e.message?.length??0),xt={history:bt?.length??0,sysPrompt:cn?.length??0,message:e.message?.length??0},Cs=vi(e.agentId,w,I);$i(Cs,dn,xt);let Ms=Ai(Cs);Ms&&this.log(`[${e.agentId}] ${Ms}`),dn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${I}: ${dn} bytes (history=${xt.history}, sysPrompt=${xt.sysPrompt}, message=${xt.message})`),As||ne("route-model");let Rs=await $s,Ps=c.def.tier!=="claude-code"?void 0:ue?Ui():qe==="lean"?Li(c.def.workspace,ut,void 0,w):Hi(c.def.workspace);qe==="lean"&&!ue&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${Bi(qe,ut,w)}`);let _s=c.def.tier==="claude-code"&&!H?Yr({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:k},g=>this.log(g)):void 0,oc={...e,systemPromptAppend:cn,...Ps?{claudeArgs:Ps}:{},...Rs?{model:Rs}:{}},re,Es=sa({agent:e.agentId,request:e.message,taskId:k,budgetMinutes:c.def.maxExecutionMinutes??20}),ic=z,Os=!1,un=!0;z=g=>{if(Es.observe(g),ae&&un)for(let f of Er(g))_r(f.name,f.input)||(un=!1);ic?.(g)};try{let g=this.workflowAutoRunner;if(fe&&g){let D=fe;try{let J=await X("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:I,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:te?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${fe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:D.follow?`Started the workflow "${J.title??D.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:fe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:fe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&ke)try{let D=Dr(ke,e.resumedFrom);Or(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:I,message:e.message,taskId:k,...D?{continues:D}:{}}),Os=!0,y.workflow={runId:ae,workflowId:Ar}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ne("dispatch-gate");let D=c.def.persistentProcess?Et():null,J=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:I}),ye=!!H||J,le=[ui(ye),Ti(ye,void 0,e.model||c.def.model)].find(Tt=>Tt&&Tt.abort);if(le){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${le.reason}`);let Tt={content:"",error:le.message,duration:0};if(!t){R.buffer=`[error] ${le.message}`;for(let ac of R.subscribers)try{ac(R.buffer)}catch{}}return Tt}mi();let Ke=ki();return Ke&&this.log(`[${e.agentId}] ${Ke}`),null},C=this.planCloudSession(c.def,e);if(C.route==="local"){let D=f();if(D)return c.errors++,re=D,D}let v=c.def.tier==="claude-code",W=v?t:(D,J)=>{D&&E(D),t&&t(D,J)},G=!1,Z=v?s:D=>{D&&(G?E(D):(E(`\u{1F4AD} ${D}`),G=!0)),s&&s(D)},$e=()=>{G&&(E(`
|
|
177
177
|
`),G=!1)},me=v?W:W?(D,J)=>{$e(),W(D,J)}:void 0,M=await X("agent",async()=>{if(C.route!=="local"){let D=await this.runCloudSession(c.def,e,C,k);if(D)return D;let J=f();if(J)return J}return Lo(c.def,oc,this.providers,me,bt,H,z,$.signal,Z)},fg);if(!M.error){let D=Ig(c.def.toolUseRequired,N);if(D){let J=Array.from(N.entries()).map(([ye,It])=>`${ye}=${It}`).join(", ")||"none";M.error=`tool_required_not_called: ${D} (invoked: ${J})`,M.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${J}`)}}_s&&Zr(_s,{toolUses:N,eventsSeen:F,error:M.error,agentId:e.agentId},D=>this.log(D));let St=this.interruptedRuns.get(y.id);St&&(M.content="",M.error=St,M.errorKind="interrupted");let ln=St?void 0:this.stoppedRuns.get(y.id);ln&&(M.content="",M.error=ln,M.errorKind="stopped"),re=M;let he=M.usage?ur(M.usage):void 0;if(ie=!0,ee().emit("task:completed",{taskId:k,agentId:e.agentId,channel:w,chatId:I,durationMs:Date.now()-is,error:M.error||void 0,errorKind:M.error?M.errorKind:void 0,interrupted:St?!0:void 0,stopped:ln?!0:void 0,inputTokens:he?.inputTokens,outputTokens:he?.outputTokens,cacheReadTokens:he?.cacheReadTokens,cacheCreateTokens:he?.cacheCreateTokens,tier2InputTokens:he?.tier2InputTokens,tier2OutputTokens:he?.tier2OutputTokens,tier2CacheReadTokens:he?.tier2CacheReadTokens,tier2CacheCreateTokens:he?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:M.numTurns,injectedContext:rc,finalResponse:M.content||void 0,billedModel:M.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&(M.content||M.error)){let D=M.error?`[error] ${M.error}`:M.content;R.buffer=D;for(let J of R.subscribers)try{J(D)}catch{}}if(M.error)c.errors++,this.log(`[${e.agentId}] error: ${M.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,I,M.content),oa({agent:e.agentId,channel:w,chatId:I,request:e.message,reply:M.content,taskId:k}),M.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,I,M.claudeSessionId),M.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,I,M.codexSessionId),M.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,I,M.opencodeSessionId),(M.claudeSessionId||M.codexSessionId||M.opencodeSessionId)&&M.usage&&this.sessions.recordTurnUsage(e.agentId,w,I,M.usage,M.contextTokens),M.usage){let le=M.contextTokens,Ke=(M.usage.inputTokens||0)+(M.usage.cacheReadTokens||0)+(M.usage.cacheCreateTokens||0);(le??Ke)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${I}: context=${le??"n/a"} tokens (cumulative turn total=${Ke}) \u2014 next turn will rotate`)}if(or({channel:w,content:`User: ${e.message}`,responseLength:M.content.length}).capture){await ds(og);try{let le=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:le,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
178
178
|
|
|
179
179
|
Agent: ${M.content}`,meta:yg(te,e.context)})}catch{}ir(e.agentId,e.message,M.content,{channel:w,chatId:I,sender:sn},this.memoryStore).catch(()=>{}),ri(e.agentId,e.message,M.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=M.billedModel||e.model||c.def.model,ye=e.context?.channel,It=ye&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ye}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,M.duration||0,M.usage,e.message.length,M.content.length,!1,J,ye,It),this.log(`[${e.agentId}] completed in ${M.duration}ms`+(M.tokensUsed?` (${M.tokensUsed} tokens)`:"")+` ${P()}`)}return M}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Rt(g.message);return re={content:"",error:Pt(f),errorKind:f.kind},re}finally{if(Es.stop(),Os&&ae&&ke)try{let g=re?.usage,f=Nr(ke,ae,{error:re?re.error||void 0:$.signal.aborted?_e($.signal).message:"run ended before completion",canceled:Lr(re?.errorKind)||this.stoppedRuns.has(y.id)||this.interruptedRuns.has(y.id)||!re&&$.signal.aborted,durationMs:Date.now()-y.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:un,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}ns(re),rs(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:this.withWorkflowSteps(e.runningTasks),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:Ur(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),We,this.safe(e.agentId),t);ce(s)||ig(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);cg(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),We,this.safe(e));if(!ce(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=K(a,l);if(ce(p))try{for(let m of pe(p)){if(!m.endsWith(".json"))continue;let h=m.split("-")[0],b=parseInt(h,10);if(!Number.isFinite(b)||b<i||b>s)continue;let y=Math.floor((s-b)/36e5),x=t-1-y;x>=0&&x<t&&o[x]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),We);if(!ce(e))return 0;let t=0;for(let s of pe(e)){let r=K(e,s),o;try{o=pe(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),d;try{d=pe(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(ct(K(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hg){let t=K(process.cwd(),We);if(!ce(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of pe(t)){let i=K(t,o),a;try{a=pe(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{ag(K(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return[];let r=pe(s).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=K(s,i),d;try{d=pe(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(ct(K(a,c),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),We,this.safe(e));if(!ce(s))return null;let r=this.safe(t),o=pe(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(ce(a))try{return JSON.parse(ct(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=$r();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Xe(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=Ht(a);return d.channel===t.channel&&d.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,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let r=[...this.taskAborts].filter(([,o])=>o.agentId===e.agentId&&o.channel===e.channel&&o.chatId===e.chatId).map(([o])=>o);t=r.length===1?r[0]:void 0}let s=t?this.taskAborts.get(t):void 0;return!t||!s?null:{taskId:t,traceId:s.traceId,agentId:s.agentId,channel:s.channel,chatId:s.chatId,sender:s.sender,rootId:s.rootId,originalMessage:s.originalMessage,origin:s.origin??null,...s.workflowRunId?{workflowRunId:s.workflowRunId}:{}}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);ee().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:Bs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let h=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:h,edited:l,pending:m}}async continueFinishedTask(e,t,s,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,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Xe(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function kg(n,e){return n===!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(`
|
|
180
180
|
`)}export{ro as a,Fg as b,io as c,vc as d,ao as e,Ot as f,Zg as g,np as h,sp as i,cp as j,Ht as k,Kc as l,Oo as m,Yc as n,Zc as o,Vc as p,Lo as q,Bt as r,Wt as s,Sd as t,Np as u,Lp as v,Gt as w,Hp as x,Ln as y,ee as z,oi as A,Dd as B,Fd as C,ci as D,nf as E,di as F,pi as G,bi as H,yf as I,xi as J,Jt as K,If as L,Tf as M,it as N,qu as O,Gu as P,Ku as Q,Ju as R,zu as S,qn as T,Yt as U,Vf as V,fa as W,at as X,ma as Y,im as Z,am as _,cm as $,dm as aa,um as ba,lm as ca,gm as da,vl as ea,lg as fa,gg as ga,Ph as ha,_h as ia,yg as ja,wg as ka,xg as la,ts as ma,Ea as na,Oa as oa,Ig as pa,Da as qa,Na as ra,kg as sa};
|
|
181
|
-
//# sourceMappingURL=chunk-
|
|
181
|
+
//# sourceMappingURL=chunk-NKTBJHIF.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{Ja as b,Ka as k,Ma as x,Ua as S}from"./chunk-
|
|
1
|
+
import{Ja as b,Ka as k,Ma as x,Ua as S}from"./chunk-GVJMPSE2.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
|
|
4
4
|
${m.map(f=>` ${f}`).join(`
|
|
5
5
|
`)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
|
|
6
6
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{O as a,N as b,A as c,F as d,U as e};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-NUMWHIFL.js.map
|