agentix-cli 0.137.0 → 0.137.1
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-MCYZBCMQ.js → App-TOAWET76.js} +2 -2
- package/dist/{ChatApp-7YXDEW3H.js → ChatApp-4DRCRKFS.js} +2 -2
- package/dist/{absorb-eval-L72I7PKM.js → absorb-eval-OXNL5QGQ.js} +2 -2
- package/dist/{agent-TPREVZGH.js → agent-GALMGMNJ.js} +2 -2
- package/dist/{board-dashboard-3VBZAKYM.js → board-dashboard-VXQYQY22.js} +4 -4
- package/dist/{chunk-QQ67J76O.js → chunk-23LWLYOK.js} +2 -2
- package/dist/{chunk-RX2ISTNT.js → chunk-2JKKGS77.js} +2 -2
- package/dist/{chunk-LGM22AOB.js → chunk-36HFRKIH.js} +2 -2
- package/dist/{chunk-5EIO6S3S.js → chunk-3K3LRLZX.js} +2 -2
- package/dist/{chunk-PYR7GKK7.js → chunk-5ADXRVYT.js} +5 -5
- package/dist/{chunk-QKILE72V.js → chunk-5RHCM3L7.js} +2 -2
- package/dist/{chunk-JXIMGK7Z.js → chunk-635B6SXI.js} +2 -2
- package/dist/{chunk-EFUPLTQ3.js → chunk-7JUISIE7.js} +2 -2
- package/dist/{chunk-64ZACYOF.js → chunk-ADQUFEPJ.js} +163 -163
- package/dist/chunk-ADQUFEPJ.js.map +1 -0
- package/dist/{chunk-AYYEY5UJ.js → chunk-B6PMIUVV.js} +2 -2
- package/dist/{chunk-GRMCAO3Q.js → chunk-BWXRAPTX.js} +2 -2
- package/dist/{chunk-DX6RYYGP.js → chunk-BXXP6DTB.js} +2 -2
- package/dist/{chunk-HSX5LMXD.js → chunk-E3AEOQMK.js} +2 -2
- package/dist/{chunk-OLZL32KG.js → chunk-GIQKQD2B.js} +2 -2
- package/dist/{chunk-APIANBXV.js → chunk-IIFHX625.js} +2 -2
- package/dist/{chunk-5CEBOUBG.js → chunk-JC5KLH2K.js} +2 -2
- package/dist/{chunk-ZX2NJGIU.js → chunk-K6UV4A2T.js} +2 -2
- package/dist/{chunk-6BWVJ7UJ.js → chunk-KHYF6KTY.js} +2 -2
- package/dist/{chunk-6BWVJ7UJ.js.map → chunk-KHYF6KTY.js.map} +1 -1
- package/dist/chunk-KQ7KWFZY.js +4 -0
- package/dist/chunk-KQ7KWFZY.js.map +1 -0
- package/dist/{chunk-P6PTY2NP.js → chunk-LK4YO2FE.js} +2 -2
- package/dist/{chunk-KEJGWFGS.js → chunk-MXDWLBIA.js} +2 -2
- package/dist/{chunk-PLCK4ZAG.js → chunk-PLPDG6GE.js} +2 -2
- package/dist/{chunk-GW4LKNQT.js → chunk-PNYBZPPB.js} +3 -3
- package/dist/{chunk-44N5HXYE.js → chunk-RWMDDMYX.js} +2 -2
- package/dist/{chunk-KOKPK3OL.js → chunk-SQ37I2MD.js} +2 -2
- package/dist/{chunk-I5QKJH7V.js → chunk-XZIKAHFU.js} +2 -2
- package/dist/{chunk-ETOOT5KD.js → chunk-Z2QOQBUS.js} +2 -2
- package/dist/{chunk-XGOBZCYC.js → chunk-Z5OD225A.js} +2 -2
- package/dist/{chunk-264762O7.js → chunk-ZYUVKFX2.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-G2QA4TCG.js → client-PWE4BJH4.js} +2 -2
- package/dist/{config-OD5W6IQE.js → config-E53FBZ47.js} +2 -2
- package/dist/{config-mutate-JEXLMR2L.js → config-mutate-ZEHN6JMZ.js} +2 -2
- package/dist/config-mutator-AK775RTM.js +2 -0
- package/dist/{contributions-UXLHUMF2.js → contributions-CLLCLS3O.js} +2 -2
- package/dist/{doctor-DO2WN4TS.js → doctor-XKT5FWPO.js} +2 -2
- package/dist/{follow-up-tool-QPNJD3HR.js → follow-up-tool-ZFRZUZLI.js} +2 -2
- package/dist/{hub-RFE766AM.js → hub-N5ADP3LO.js} +2 -2
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/ntfy-ZDNBUEIX.js +2 -0
- package/dist/{program-QENG5KI7.js → program-MJ6S6X6T.js} +23 -23
- package/dist/{promote-FJ3EK2J6.js → promote-M4UBD2R6.js} +2 -2
- package/dist/push-HVGOC4VN.js +2 -0
- package/dist/push-bridge-NAQ7WQJX.js +2 -0
- package/dist/{query-KYA6YYUU.js → query-KMQHF5HW.js} +2 -2
- package/dist/{query-settings-P3UOGMAQ.js → query-settings-PENAE4UG.js} +2 -2
- package/dist/{registry-U4S4XXUZ.js → registry-GYKSYSDD.js} +2 -2
- package/dist/{request-planner-SYVDD4PZ.js → request-planner-GBX6DHRQ.js} +2 -2
- package/dist/{review-candidates-QUIX4AK7.js → review-candidates-SYMRJGI2.js} +2 -2
- package/dist/{routing-MDZOHYYH.js → routing-S3L44JLL.js} +2 -2
- package/dist/schedule-tool-FXUFRZHR.js +2 -0
- package/dist/{scheduler-76IIRAP7.js → scheduler-AW4F5ZKS.js} +2 -2
- package/dist/{seat-TV5SK2E7.js → seat-QBBNCOFO.js} +2 -2
- package/dist/{select-HKRDVQNW.js → select-ZCFIMYWS.js} +2 -2
- package/dist/{set-enabled-I2V3PXOA.js → set-enabled-4F27A3U2.js} +2 -2
- package/dist/{tool-J7PYS4NF.js → tool-G6XTO24J.js} +2 -2
- package/dist/{tool-5ZFM6NSO.js → tool-M462KSMF.js} +2 -2
- package/dist/{wiki-3VG33ZZB.js → wiki-JXVHIEZI.js} +2 -2
- package/dist/wiki-enrich-6CSUPULH.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-64ZACYOF.js.map +0 -1
- package/dist/chunk-KZKDVIOE.js +0 -4
- package/dist/chunk-KZKDVIOE.js.map +0 -1
- package/dist/config-mutator-4FKROX3O.js +0 -2
- package/dist/ntfy-52EXHVMD.js +0 -2
- package/dist/push-DID6RZYI.js +0 -2
- package/dist/push-bridge-325SXDGN.js +0 -2
- package/dist/schedule-tool-DKBPBQ3F.js +0 -2
- package/dist/wiki-enrich-2FNORKEQ.js +0 -2
- /package/dist/{App-MCYZBCMQ.js.map → App-TOAWET76.js.map} +0 -0
- /package/dist/{ChatApp-7YXDEW3H.js.map → ChatApp-4DRCRKFS.js.map} +0 -0
- /package/dist/{absorb-eval-L72I7PKM.js.map → absorb-eval-OXNL5QGQ.js.map} +0 -0
- /package/dist/{agent-TPREVZGH.js.map → agent-GALMGMNJ.js.map} +0 -0
- /package/dist/{board-dashboard-3VBZAKYM.js.map → board-dashboard-VXQYQY22.js.map} +0 -0
- /package/dist/{chunk-QQ67J76O.js.map → chunk-23LWLYOK.js.map} +0 -0
- /package/dist/{chunk-RX2ISTNT.js.map → chunk-2JKKGS77.js.map} +0 -0
- /package/dist/{chunk-LGM22AOB.js.map → chunk-36HFRKIH.js.map} +0 -0
- /package/dist/{chunk-5EIO6S3S.js.map → chunk-3K3LRLZX.js.map} +0 -0
- /package/dist/{chunk-PYR7GKK7.js.map → chunk-5ADXRVYT.js.map} +0 -0
- /package/dist/{chunk-QKILE72V.js.map → chunk-5RHCM3L7.js.map} +0 -0
- /package/dist/{chunk-JXIMGK7Z.js.map → chunk-635B6SXI.js.map} +0 -0
- /package/dist/{chunk-EFUPLTQ3.js.map → chunk-7JUISIE7.js.map} +0 -0
- /package/dist/{chunk-AYYEY5UJ.js.map → chunk-B6PMIUVV.js.map} +0 -0
- /package/dist/{chunk-GRMCAO3Q.js.map → chunk-BWXRAPTX.js.map} +0 -0
- /package/dist/{chunk-DX6RYYGP.js.map → chunk-BXXP6DTB.js.map} +0 -0
- /package/dist/{chunk-HSX5LMXD.js.map → chunk-E3AEOQMK.js.map} +0 -0
- /package/dist/{chunk-OLZL32KG.js.map → chunk-GIQKQD2B.js.map} +0 -0
- /package/dist/{chunk-APIANBXV.js.map → chunk-IIFHX625.js.map} +0 -0
- /package/dist/{chunk-5CEBOUBG.js.map → chunk-JC5KLH2K.js.map} +0 -0
- /package/dist/{chunk-ZX2NJGIU.js.map → chunk-K6UV4A2T.js.map} +0 -0
- /package/dist/{chunk-P6PTY2NP.js.map → chunk-LK4YO2FE.js.map} +0 -0
- /package/dist/{chunk-KEJGWFGS.js.map → chunk-MXDWLBIA.js.map} +0 -0
- /package/dist/{chunk-PLCK4ZAG.js.map → chunk-PLPDG6GE.js.map} +0 -0
- /package/dist/{chunk-GW4LKNQT.js.map → chunk-PNYBZPPB.js.map} +0 -0
- /package/dist/{chunk-44N5HXYE.js.map → chunk-RWMDDMYX.js.map} +0 -0
- /package/dist/{chunk-KOKPK3OL.js.map → chunk-SQ37I2MD.js.map} +0 -0
- /package/dist/{chunk-I5QKJH7V.js.map → chunk-XZIKAHFU.js.map} +0 -0
- /package/dist/{chunk-ETOOT5KD.js.map → chunk-Z2QOQBUS.js.map} +0 -0
- /package/dist/{chunk-XGOBZCYC.js.map → chunk-Z5OD225A.js.map} +0 -0
- /package/dist/{chunk-264762O7.js.map → chunk-ZYUVKFX2.js.map} +0 -0
- /package/dist/{client-G2QA4TCG.js.map → client-PWE4BJH4.js.map} +0 -0
- /package/dist/{config-OD5W6IQE.js.map → config-E53FBZ47.js.map} +0 -0
- /package/dist/{config-mutate-JEXLMR2L.js.map → config-mutate-ZEHN6JMZ.js.map} +0 -0
- /package/dist/{config-mutator-4FKROX3O.js.map → config-mutator-AK775RTM.js.map} +0 -0
- /package/dist/{contributions-UXLHUMF2.js.map → contributions-CLLCLS3O.js.map} +0 -0
- /package/dist/{doctor-DO2WN4TS.js.map → doctor-XKT5FWPO.js.map} +0 -0
- /package/dist/{follow-up-tool-QPNJD3HR.js.map → follow-up-tool-ZFRZUZLI.js.map} +0 -0
- /package/dist/{hub-RFE766AM.js.map → hub-N5ADP3LO.js.map} +0 -0
- /package/dist/{ntfy-52EXHVMD.js.map → ntfy-ZDNBUEIX.js.map} +0 -0
- /package/dist/{program-QENG5KI7.js.map → program-MJ6S6X6T.js.map} +0 -0
- /package/dist/{promote-FJ3EK2J6.js.map → promote-M4UBD2R6.js.map} +0 -0
- /package/dist/{push-DID6RZYI.js.map → push-HVGOC4VN.js.map} +0 -0
- /package/dist/{push-bridge-325SXDGN.js.map → push-bridge-NAQ7WQJX.js.map} +0 -0
- /package/dist/{query-KYA6YYUU.js.map → query-KMQHF5HW.js.map} +0 -0
- /package/dist/{query-settings-P3UOGMAQ.js.map → query-settings-PENAE4UG.js.map} +0 -0
- /package/dist/{registry-U4S4XXUZ.js.map → registry-GYKSYSDD.js.map} +0 -0
- /package/dist/{request-planner-SYVDD4PZ.js.map → request-planner-GBX6DHRQ.js.map} +0 -0
- /package/dist/{review-candidates-QUIX4AK7.js.map → review-candidates-SYMRJGI2.js.map} +0 -0
- /package/dist/{routing-MDZOHYYH.js.map → routing-S3L44JLL.js.map} +0 -0
- /package/dist/{schedule-tool-DKBPBQ3F.js.map → schedule-tool-FXUFRZHR.js.map} +0 -0
- /package/dist/{scheduler-76IIRAP7.js.map → scheduler-AW4F5ZKS.js.map} +0 -0
- /package/dist/{seat-TV5SK2E7.js.map → seat-QBBNCOFO.js.map} +0 -0
- /package/dist/{select-HKRDVQNW.js.map → select-ZCFIMYWS.js.map} +0 -0
- /package/dist/{set-enabled-I2V3PXOA.js.map → set-enabled-4F27A3U2.js.map} +0 -0
- /package/dist/{tool-J7PYS4NF.js.map → tool-G6XTO24J.js.map} +0 -0
- /package/dist/{tool-5ZFM6NSO.js.map → tool-M462KSMF.js.map} +0 -0
- /package/dist/{wiki-3VG33ZZB.js.map → wiki-JXVHIEZI.js.map} +0 -0
- /package/dist/{wiki-enrich-2FNORKEQ.js.map → wiki-enrich-6CSUPULH.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as St,c as At}from"./chunk-QSKG754X.js";import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-
|
|
1
|
+
import{b as St,c as At}from"./chunk-QSKG754X.js";import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-23LWLYOK.js";import{b as ft,d as gt,e as mt}from"./chunk-PE5V2LI7.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-SQ37I2MD.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var Ft=200,nr=7,jt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ne(e,".agentx/memory"),this.ledger=new ft(ne(e,".agentx/wiki")),Mt(this.memoryDir)||er(this.memoryDir,{recursive:!0})}filePath(e){return ne(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||$e(t.content))return!1;let r=t.source.trust??dt(t.source.channel),o=t.review??lt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Xn(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Mt(t))return[];try{let{mtimeMs:r,size:o}=tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Et(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Ae);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ne(this.memoryDir,`${t}_bm25_cache.json`),i=it(s,a),d=ot(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),c=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(c.length===0)return o.slice(-r);let f=c.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Ot(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Dt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Pe(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -38,4 +38,4 @@ ${n.text}`}async function me(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
38
38
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Xe(this.file))try{let e=JSON.parse(et(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Sn(xn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Tn(4).toString("hex")}.tmp`;Rn(t,JSON.stringify(e,null,2)+`
|
|
39
39
|
`,{encoding:"utf-8",mode:384}),An(t,this.file)}};import{extname as li}from"path";var Nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Dn=/<agentx-artifact>[\s\S]*$/i;function ld(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Nn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Dn,""):s).trim(),artifacts:r}}function ud(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Nn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Dn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ui={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},cd={bytes:20*1024*1024,perMessage:20,pathChars:512};function pd(n){return ui[li(n).toLowerCase()]??null}var ci=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
40
40
|
`);function fd(n,e,t){return n==="app"&&e&&t!==!1?ci:void 0}import{lstatSync as nt,mkdirSync as pi,readdirSync as fi,realpathSync as tt,unlinkSync as gi}from"fs";import{join as be,resolve as On}from"path";var En=".agentx/outbox",mi=7*24*60*60*1e3;function hi(n,e){try{let t=tt(On(e,n)),r=be(t,En);return tt(r)===r&&nt(r).isDirectory()?r:null}catch{return null}}function wd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=tt(On(t,n));nt(be(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||pi(be(o,En),{recursive:!0})}catch{return 0}let r=hi(n,t);return r?Mn(r,(e.now??Date.now())-(e.maxAgeMs??mi)):0}function Mn(n,e){let t=0;for(let r of fi(n)){let o=be(n,r);try{let s=nt(o);s.isDirectory()?t+=Mn(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(gi(o),t++)}catch{}}return t}export{Tt as a,jt as b,Ct as c,Di as d,ir as e,Oi as f,T as g,z as h,S as i,oe as j,Ir as k,Oe as l,F as m,Fe as n,Ce as o,Ge as p,To as q,Mo as r,Qe as s,_r as t,Go as u,Na as v,Da as w,Oa as x,Ea as y,Ma as z,Vo as A,Qo as B,Fa as C,ja as D,Ca as E,_a as F,Ha as G,Ka as H,Ba as I,qa as J,za as K,Ja as L,Ya as M,Ga as N,Va as O,Qa as P,Za as Q,ri as R,Xa as S,ed as T,td as U,nd as V,Wn as W,ld as X,ud as Y,cd as Z,pd as _,fd as $,En as aa,wd as ba};
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-3K3LRLZX.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-
|
|
1
|
+
import{$ as $r,H as mr,I as hr,J as yr,L as wr,M as br,N as xr,O as Ir,R as Sr,S as Tr,V as kr,W as vr,a as Zs,b as er,ba as Ar,d as nr,f as ze,l as kt,m as pr,t as vt,v as fr}from"./chunk-3K3LRLZX.js";import{a as Vs}from"./chunk-QSKG754X.js";import{b as tr}from"./chunk-MEFPXHQJ.js";import{a as gr}from"./chunk-W4YR2RO2.js";import{b as rr,c as pn,d as ir,e as Tt,h as ar}from"./chunk-23LWLYOK.js";import{e as Xs,f as Ys}from"./chunk-36AXN6ZB.js";import{a as ln,b as sr}from"./chunk-J3SOEFRE.js";import{a as gn,b as or}from"./chunk-SIU6STB2.js";import{e as dr,i as cr,j as ur,k as lr}from"./chunk-X5C5W3E4.js";import{a as zs}from"./chunk-RWMDDMYX.js";import{g as Js,h as Qs}from"./chunk-E3AEOQMK.js";import{c as Ns,f as Ls}from"./chunk-7JUISIE7.js";import{s as Ds,v as St,w as Os,y as ye,z as un}from"./chunk-SQ37I2MD.js";import{a as Qe,b as Ee,f as It}from"./chunk-72SZI2UW.js";import{a as _e,b as rn}from"./chunk-FCPTN6NF.js";import{a as Fs,c as Us}from"./chunk-MYVHVJWZ.js";import{d as De,h as Ae}from"./chunk-6TURWSMN.js";import{a as Hs,b as Bs,c as js,d as Ws,l as qs}from"./chunk-AV7T3SYT.js";import{a as Gs,b as Ks}from"./chunk-Y5MFVVTM.js";import{c as Ss,d as Ts}from"./chunk-QOYAX2FT.js";import{e as $e}from"./chunk-DSYKYZMT.js";import{$ as Rs,Aa as $a,G as As,I as dn,K as ka,N as Cs,R as va,X as Ms,Y as cn,Z as Ps,_ as Je,aa as _s,ga as Es}from"./chunk-KHYF6KTY.js";import{g as Ke,h as Sa}from"./chunk-BRK6M6LA.js";import{f as an,n as Ta}from"./chunk-UIBUZ2N3.js";import{a as ks,b as le,c as vs,d as $s,e as on}from"./chunk-2QNT5JDS.js";un();It();var $t="tool-set",Cr=["answer","code","full"],Mr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},Aa=.1;function Rr(n){return{task:Pr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:Pr(n.agentPrompt,600)}:{}}}var _r={bundle:Ee({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 Er(n,e=Aa){let s=n?.bundle?.probabilities;if(!s)return"full";let r=fn(s.answer),o=fn(s.code),i=fn(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function Dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>Mr.answer.includes(t))?"answer":e.every(t=>Mr.code.includes(t))?"code":"full"}function Or(n,e){return Cr.indexOf(n)<Cr.indexOf(e)}function fn(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var Nr=!1;function Lr(n,e){let t=St($t);if(t!=="off")return t==="active"&&!Nr&&(Nr=!0,e(`[decisions] seat "${$t}" is set to active, but only shadow is built: it records and changes nothing`)),ye($t,Rr(n),_r,{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=Er(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function Fr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=Dr(r);Os(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}`+(Or(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Ca(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function Ur(n,e){let t=Ca(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 mn(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)`}un();It();var Hr="session-continuity",Br={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 jr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:hn(n.message,1200),previousRequest:n.previousMessage?hn(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>hn(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function Wr(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 hn(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as Ot}from"execa";import{spawn as Ma}from"node:child_process";import{createHash as Pa}from"node:crypto";import{createInterface as Ra}from"node:readline";var we=class extends Error{},_a=n=>Ma("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),yn=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(),Ra({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()}},wn=class{constructor(e=_a,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=Pa("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[P])=>w.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new we("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 w=[...this.entries].find(([,P])=>!P.connection.busy);if(!w)throw new we("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:s,connection:new yn(e,this.launchProcess)}}catch{throw new we("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,g,m,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),S=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 w={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",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(S),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let _=new Promise((L,M)=>{i.failTurn=M,i.notify=(D,U)=>{if(U?.threadId!==u)return;let N=U.item,q={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...U,type:D.replace("/","."),...N?{item:{...N,type:q[N.type]||N.type}}:{}}),D==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=U.delta,e.onDelta?.(U.delta,c)),D==="thread/tokenUsage/updated"){let H=U.tokenUsage.last;m=H.inputTokens;let K=H.cachedInputTokens||0;g={inputTokens:(g?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-K),outputTokens:(g?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(g?.cacheReadTokens||0)+K,cacheCreateTokens:(g?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(U.turn.status==="completed"?L():M(new Error(U.turn.error?.message||`Codex turn ${U.turn.status}`)))}});return _.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await _,{content:d??c,codexSessionId:u,billedModel:e.model,usage:g,contextTokens:m,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new we(w.message);return{content:c,codexSessionId:u,usage:g,contextTokens:m,error:w.message,duration:Date.now()-t}}finally{clearTimeout(S),clearTimeout(x),e.signal?.removeEventListener("abort",p),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())}}},qr=new wn;import{execFile as Za}from"child_process";import{StringDecoder as et}from"string_decoder";import{mkdtempSync as co,readFileSync as uo,rmSync as lo}from"fs";import{join as Et}from"path";import{tmpdir as go}from"os";function At(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 d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),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),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ct(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Mt(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,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var Gr=null;function Pt(){return Gr}function fl(n){Gr=n}function Xe(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function Ea(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 Oe=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Kr=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=Xe(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=Ea(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 Oe(`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 Oe(`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=Xe(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=Xe(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Xe(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=Xe(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(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Da}from"child_process";import{randomUUID as Oa}from"crypto";import{existsSync as Na,readFileSync as La}from"fs";import{resolve as Fa}from"path";function Ua(n){let e=Fa(n,"CLAUDE.md");if(!Na(e))return null;try{let t=La(e,"utf8");return qs(t)}catch{return null}}var Ha=20*60*1e3,Ba=5e3,Ye=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 ja(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 Jr=class{constructor(e={}){this.opts=e}spawn(e,t){return new bn(e,t,this.opts)}},bn=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=Da(r,o,{cwd:t.workspace,env:Ae(ja({...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:Ua(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),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=Oa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??Ha,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new Ye(c)),g=!1,m=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ve(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!g){if(p.type==="user"&&p.uuid===i)g=!0,m&&(yield{type:m.type,raw:m});else if(p.type==="system"&&p.subtype==="init")m=p;else if(p.type==="result"){m=null;let x=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${x.length} chars): ${x.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{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)},Ba);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"}}};on();Ta();rn();import{resolve as Qr,join as zr}from"path";var Wa=4e3;function Rt(n){try{let e=zr(Qr(n.root),".agentx","db.sqlite"),t=an({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=_e(),r=n.input.command?n.input.command.slice(0,Wa):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,g)}};L.stdout?.on("data",T=>{N+=H.write(T);let b=N.split(`
|
|
32
32
|
`);N=b.pop()||"";for(let O of b)X(O)}),L.stderr?.on("data",T=>{q+=K.write(T)});let A=await L;if(i&&i.removeEventListener("abort",U),N+=H.end(),N.trim()&&X(N),q+=K.end(),M)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(A.exitCode!==0||p){let T=A,b;return T.timedOut?b=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?b=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+q)?b=oo():b=q.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...V(b),duration:Date.now()-c,usage:m,opencodeSessionId:h}}return S=!1,{content:g.trim(),duration:Date.now()-c,usage:m,billedModel:e.model||n.model,opencodeSessionId:h}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(P?.message||"")?oo():P?.message;return{content:g,...V(_||"OpenCode failed"),duration:Date.now()-c,usage:m,opencodeSessionId:h}}finally{w?.(),x?.release(S)}}async function gd(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=xe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...V(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function pd(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),g=new AbortController,m=!1,h=()=>{let S=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{g.abort(new Error(S))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{m=!0;try{g.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let x=()=>({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()-d});try{let S=n.provider||"claude-code",w=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,P=e.context?.sender,_=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&_?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,P=e.context?.sender,_=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),L=e.context?.channel==="web-chat"&&_?{userId:P,agentId:e.agentId||"acme-public"}:void 0,M=Ws(n),D=Object.keys(M).length>0,U={task:w,cwd:n.workspace,provider:S,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:L,providerOpts:o,abortSignal:g.signal,mcpServers:D?M:void 0};if(r){let{generateStream:X}=await import("./agent-GALMGMNJ.js"),A="",T,b,O,B;for await(let C of X(U)){if(c)try{c(C)}catch{}if(C.type==="text_delta")A+=C.text,r(C.text,A);else if(C.type==="thinking_delta")C.text&&i&&i(C.text);else if(C.type==="generate_result"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}T=C.result.tokensUsed,C.result.inputTokens!=null&&(b=C.result.inputTokens),C.result.outputTokens!=null&&(O=C.result.outputTokens)}else if(C.type==="done"){if(C.result.content&&C.result.content!==A){let W=C.result.content.slice(A.length);W?(A=C.result.content,r(W,A)):A=C.result.content}C.result.tokensUsed!=null&&(T=C.result.tokensUsed)}else C.type==="error"&&(B=C.error)}return B&&!A?m?x():B==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${B}`),duration:Date.now()-d}:((b===void 0||O===void 0)&&T&&(b=Math.round(T*.7),O=T-b),{content:A||"Done.",tokensUsed:T,usage:b!==void 0||O!==void 0?{inputTokens:b||0,outputTokens:O||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:N}=await import("./agent-GALMGMNJ.js"),q=await N(U),H=q.inputTokens,K=q.outputTokens;if((H===void 0||K===void 0)&&q.tokensUsed){let X=q.tokensUsed;H=Math.round(X*.7),K=X-H}return{content:q.content||"Done.",tokensUsed:q.tokensUsed,usage:H!==void 0||K!==void 0?{inputTokens:H||0,outputTokens:K||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(S){return m?x():S?.message==="cancelled"||a?.aborted||g.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...V(`Orchestrator error: ${S.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var In=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}},fd=1e3;async function md(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"}),fd),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 hd(n,e,t,s,r,o,i){let a=Pt();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Lt(e.context),g={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(g,"freshSession=true")}catch{}let m,h=!1;try{let A=a.list().length;m=a.acquire(g,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>A}catch(A){return A instanceof Oe,null}h&&vn(e.agentId,n,e.model,s,"persistent");let p=xe(n,e,t),x="",S,w,P,_,L,M,D,U="",N="",q=A=>{if(!i||!A)return;let T;if(N&&A.startsWith(N)?T=A.slice(N.length):T=U&&!U.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${A}`:A,N=A,!!T){U+=T;try{i(T,U)}catch{}}},H=!1,K=()=>{H=!0,a.kill(g,"operator-cancel").catch(()=>{})};o&&(o.aborted?K():o.addEventListener("abort",K,{once:!0}));let X=!1;try{let A=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of m.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:A})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let b=T.raw.message?.content??[];for(let B of b)B.type==="text"&&typeof B.text=="string"?(x=B.text,q(B.text)):B.type==="tool_use"&&(N="");let O=T.raw.message?.usage;if(O){let B=(O.input_tokens||0)+(O.cache_read_input_tokens||0)+(O.cache_creation_input_tokens||0);B>0&&(_=B)}}if(T.type==="result"){let b=T.raw;if(b.is_error){let O=V(typeof b.result=="string"?b.result:"claude error");S=O.error,w=O.errorKind}else typeof b.result=="string"&&b.result.length>0&&(x=b.result,U||q(b.result));typeof b.session_id=="string"&&(D=b.session_id),b.usage&&(P={inputTokens:b.usage.input_tokens||0,outputTokens:b.usage.output_tokens||0,cacheReadTokens:b.usage.cache_read_input_tokens||0,cacheCreateTokens:b.usage.cache_creation_input_tokens||0}),typeof b.num_turns=="number"&&(L=b.num_turns),typeof b.message?.model=="string"?M=b.message.model:typeof b.model=="string"?M=b.model:M=Mt(b.modelUsage)||M}}}catch(A){if(H)S="task cancelled by operator",w="cancelled";else if(X)if(A instanceof Ve)S=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,w="interrupted";else if(A instanceof Ye){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.`);S=T.error,w=T.errorKind}else{let T=V(`persistent claude process error: ${A?.message||String(A)}`);S=T.error,w=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(g,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",K),null}finally{o&&o.removeEventListener("abort",K)}return H&&!S&&(S="task cancelled by operator",w="cancelled"),{content:H?"":x,error:S,errorKind:w,duration:Date.now()-c,usage:P,contextTokens:_,numTurns:L,billedModel:M,claudeSessionId:D}}function Io(n){let e=le(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?Vr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:so(t.args,n.taskId,n.agentId)}function yd(n){return le(n.autonomy)||!!n.personLimits}async function wd(n,e,t,s,r,o,i){let a=le(e.autonomy)?e.autonomy:void 0,c=a&&Zr(a,n.tier)||e.personLimits&&ro(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${$s(a)}
|
|
@@ -138,7 +138,7 @@ ${Hu}`:n==="codex-cli"?qi:""}function Gi(n,e){return e!=="claude-code"&&e!=="cod
|
|
|
138
138
|
`)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Kt(Q(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Jt,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=qn(t.context?.chatId),a=this.cloudSessionStore();return Hi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Jt,...e.cloudSessions??{}},i=Date.now(),a=Ae(tt(De(e.workspace),t),e.billing),c=await Wi({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>ji({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Z().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}callerGone(e,t){let s=Re(e.callerSignal).message;return this.log(`[${e.agentId}] caller gone during ${t} \u2014 not starting (${s})`),{content:"",error:`Caller gone before agent "${e.agentId}" was free \u2014 not started`}}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(u){i={content:"",error:u?.message??String(u)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"});let c=!a&&e.runningTaskId?this.stoppedRuns.get(e.runningTaskId):void 0;c&&(this.stoppedRuns.delete(e.runningTaskId),i={...i,content:"",error:c,errorKind:"stopped"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&!c&&i.error&&/^timed out before spawn after/.test(i.error);if(d&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(d){let u=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${u}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let u=i.error?ze(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";rr().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:u,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(u){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${u?.message??u}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=le(e.autonomy),a=Rs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:Bo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let l=await c;if(l.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${l.sessionId}`),{content:l.text,viaAttachedSession:l.sessionId};this.log(`[${e.agentId}] attached session did not take it (${l.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let l=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(v=>v.id===e.agentId));if(l){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${l.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(l.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:l.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${l.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:g}=Lt(e.context),m;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let l=Date.now(),f=25*6e4,v=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(e.callerSignal?.aborted)return this.callerGone(e,"slot wait");if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,v))}}else if(u==="voice"){let l=Date.now(),f=25*6e4,v=`${e.agentId}\0${g}`;for(;this.messageQueue.isBusy(e.agentId,u,g)||this.voiceClaims.has(v);){if(Date.now()-l>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(k=>setTimeout(k,500))}m=v,this.voiceClaims.add(v)}else{let l=d.def.queueMode||"collect",f=this.messageQueue.enqueue(e.agentId,u,g,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:g,originalContext:e.context,queuedAt:e.queuedAt});if(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let v=this.messageQueue.pendingCount(e.agentId,u,g);return Z().emit("task:queued",{agentId:e.agentId,channel:u,chatId:g,at:new Date().toISOString(),sender:dn(e.context),humanRoot:Ke(e.context),person:cn(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${v}) behind=${d.runningTasks.map(k=>k.id).join(",")||"-"} chat=${u}:${g} at=${new Date().toISOString()}`),{content:"",error:nr(f,v)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(l,f)=>{this.log(`[${e.agentId}] ${l} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/1e3))}s`)}});if(m&&this.voiceClaims.delete(m),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.callerSignal?.aborted)return this.callerGone(e,"rate-limit wait");if(e.queuedAt!==void 0){let l=_o(e.queuedAt);l&&(e.message=`${l}
|
|
139
139
|
${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={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}}:{}};d.runningTasks.push(p),e.runningTaskId=p.id;let x=cn(this.config.people,e.context);if(e.context&&(x?e.context.person=x.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let S=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:S,sender:e.context?.sender,rootId:Tt()?.rootId,workflowRunId:e.workflowRunId??(typeof p.chatId=="string"&&p.chatId.startsWith("workflow:")&&p.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let w={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,w);let P=l=>{if(l){w.buffer+=l,w.buffer.length>Ki&&(w.buffer=w.buffer.slice(w.buffer.length-Ki));for(let f of w.subscribers)try{f(l)}catch{}}},_=_e();e.taskId=_;let L=this.taskAborts.get(p.id);L&&(L.traceId=_);let M=new Map,D=(l,f,v)=>{try{Z().emit("task:step",{taskId:_,agentId:e.agentId,name:"pipeline",action:l,status:v,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},U=0,N=!1,q=()=>{N||(N=!0,U&&D("first-event",U,"ok"))},H;if(t){let l=Vu();H=f=>{q();let v=l(f);if(v&&P(v),zi(_,e.agentId,f),Qi(M,f),Dn(f,void 0,e.model||d.def.model),r)try{r(f)}catch{}}}else H=l=>{if(q(),zi(_,e.agentId,l),Qi(M,l),Dn(l,void 0,e.model||d.def.model),r)try{r(l)}catch{}};let K=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,X=K?setTimeout(()=>S.abort(new Error(`timed out after ${Math.round(K/1e3)}s`)),K):void 0;X?.unref?.();let A=(d.def.preSpawnTimeoutSec??qu)*1e3,T=setTimeout(()=>{S.abort(new Error(`timed out before spawn after ${Math.round(A/1e3)}s in step "${p.step??"start"}"`))},A);T.unref?.();let b=()=>{T&&clearTimeout(T),T=void 0},O=()=>`task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`,B;S.signal.addEventListener("abort",()=>{let l=Re(S.signal).message;/^timed out/.test(l)&&(B=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${l} ${O()}`)},{once:!0});let C=l=>{p.step=l,this.log(`[${e.agentId}] step ${l} ${O()}`)},W=(l,f,v=0)=>{if(S.signal.aborted)return Promise.reject(Re(S.signal));C(l),(l==="agent"||l==="workflow-auto-run")&&(b(),U=Date.now());let k=Date.now(),j=Ui(f(),Uu[l]??0,l);return Fi(j,S.signal,v).then(G=>(D(l,k,"ok"),G),G=>{throw D(l,k,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${O()}`),G})},te=async(l,f,v,k=0)=>{try{return await W(l,f,k)}catch(j){if(j instanceof Be)return v();throw j}},ne=!1,R=!1,se=l=>{if(!(!ne||R)){R=!0;try{Z().emit("task:completed",{taskId:_,agentId:e.agentId,channel:u,chatId:g,durationMs:Date.now()-p.startedAt.getTime(),error:l?.error||(S.signal.aborted?Re(S.signal).message:"run ended before completion"),errorKind:l?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,stopped:!this.interruptedRuns.has(p.id)&&(this.stoppedRuns.has(p.id)||l?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},ie=!1,Kn=l=>{if(ie)return;ie=!0,se(l),this.runReleases.delete(p.id),X&&clearTimeout(X),b(),d.activeTasks--;let f=d.runningTasks.findIndex(k=>k.id===p.id);f!==-1&&d.runningTasks.splice(f,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id);let v=this.runEndWaiters.get(p.id);this.runEndWaiters.delete(p.id);for(let k of v??[])try{k()}catch{}w.done=!0,w.endedAt=new Date;for(let k of w.subscribers)try{k(`
|
|
140
140
|
[task finished]
|
|
141
|
-
`)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),ju).unref?.();try{let k=w.endedAt,j={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!l?.error,error:l?.error,...this.stoppedRuns.has(p.id)||l?.errorKind==="stopped"?{status:"stopped"}:B?{status:"timeout",step:B}:{},responseText:l?.content||"",transcript:w.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let Y=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:j.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,g).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`);let j=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,count:k.length,at:new Date().toISOString()});let G=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,at:new Date().toISOString()});for(let Y of k){let ve=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:ve,queuedAt:Y.queuedAt??Y.timestamp}).then(fe=>(ze(fe.error)||G(),this.postQueuedResponseToChannel(e.agentId,ve,fe)),fe=>{throw G(),fe}).catch(fe=>{this.log(`[${e.agentId}] queued message failed: ${fe.message}`)})}}).catch(k=>{Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,Kn),this.messageQueue.markRunning(e.agentId,u,g),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let y=e.context?.channel||"api",{evaluateRequest:Vi,selectRequestContext:Zi}=await import("./request-planner-SYVDD4PZ.js"),Jn=te("request-gate",()=>Vi(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Qt=!1;Jn.then(()=>{Qt=!0},()=>{Qt=!0});let I=g,zt=e.context?.sender||"User",ce=d.def.tier==="codex-cli",We=li(this.config.session,y,d.def.tier),dt=gi(this.config.session),qe=We==="lean"&&dt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let ct=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let ea=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(l=>l.role==="agent")?.content;Li({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:ea,taskId:_}),this.sessions.addUserMessage(e.agentId,y,I,zt,e.message);let Qn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Qn).toISOString(),taskId:_,resumeOrigin:Po(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:dn(e.context),...x?{person:x}:{},humanRoot:Ke(e.context),pickup:As(e.context),operator:Cs(e.context)}),ne=!0;let ee,Xt,zn=this.classifier;if(zn&&y!=="a2a"&&!ce){C("classify");let l=Date.now();Xt=zn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ee=f||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),D("classify",l,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",l,"error")})}let Xn=async l=>{if(!Xt)return;let f;await Promise.race([Xt,new Promise(v=>{f=setTimeout(v,l),f.unref?.()})]),f&&clearTimeout(f)};await Xn(Eu);let Se=this.config.workflows?.matching,pe,Yn,Vn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Vn?.enabled&&(Vn.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=(Se?.suggestThreshold??.65)&&(Yn=fr(f.workflow))}catch(l){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${l?.message||l}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Se.mode} reasons=${f.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&f.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?pe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(l){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${l?.message||l}`)}let Te=mr(this.config.workflows,e.agentId)&&hr(e)?this.workflowRuns:void 0;if(Te&&!pe&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list()),v=Se?.autoRunThreshold??.85;f&&f.confidence>=v&&(pe={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(l){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${l?.message||l}`)}let ae=Te?Fu():void 0,ta=ae?yr(ae):void 0,na=this.wikiHub.getAgentWiki(e.agentId),Zn=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),es=this.memoryStore.buildContext(Zn),ts=this.memoryStore.contextFacts(Zn),sa=this.patternStore.findRelevant(e.message,e.agentId,5),ra=this.patternStore.buildContext(sa),ns="";if(!ce)try{let{loadLocalSkills:l,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),v=await W("skills",()=>l(d.def.workspace)),k=e.personLimits?.skills??[],j=k.length?v.filter(G=>!k.some(Y=>Je(Y,G.frontmatter.name))):v;ns=f(j,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,y,I,ct)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let l=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${l} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let l=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let l=this.config.session?.resumeGate;if(l&&l.mode!=="off"){let f=Ur({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:ct??0},l);if(f.rotate&&l.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${mn(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),F=void 0}else l.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${mn(f)}`)}}if(F&&d.def.tier==="claude-code"){let l=F;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,l),()=>!1)&&(F=void 0)}try{let l=await W("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(l.compacted){let f=l.qualityScore??"?",v=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${f}%, ${v} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let k=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let oa=process.env.AGENTX_CONTEXT_SURGERY==="1",ia=ce?{maxMessages:8,maxChars:2400}:oa&&Gi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,aa=!F&&!ce?zu(na,e.agentId,{notesInbox:Qu(this.config)}):void 0,ut=!F&&!qe?this.sessions.buildHistoryContext(e.agentId,y,I,ia):void 0,da=F?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ss,rs=[];if(this.config.procedures?.injection?.enabled&&!F&&!ce)try{let l=new ot({baseDir:Q(process.cwd(),this.config.procedures.dir)}),f=Fn(e.message,l.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){ss=Un(f),rs=f.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of f)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(l){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${l?.message||l}`)}if($e&&$e.cat)try{let f=this.sessions.getSession(e.agentId,y,I).messages,v=f[0],k=f[f.length-1],j=ut===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${ut.length}c/${ut.split(`
|
|
141
|
+
`)}catch{}w.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),ju).unref?.();try{let k=w.endedAt,j={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:k.toISOString(),durationMs:k.getTime()-p.startedAt.getTime(),ok:!l?.error,error:l?.error,...this.stoppedRuns.has(p.id)||l?.errorKind==="stopped"?{status:"stopped"}:B?{status:"timeout",step:B}:{},responseText:l?.content||"",transcript:w.buffer};this.persistTaskRecord(j);let G=(j.responseText||j.error||"").trim();if(G){let Y=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Y,at:k,ok:j.ok})}}catch(k){this.log(`[${e.agentId}] task history persist failed: ${k?.message}`)}this.messageQueue.markDone(e.agentId,u,g).then(k=>{if(k.length===0)return;this.log(`[${e.agentId}] flushing ${k.length} queued message(s) after task=${p.id} chat=${u}:${g} at=${new Date().toISOString()}`);let j=Date.now();Z().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,count:k.length,at:new Date().toISOString()});let G=()=>Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:j,at:new Date().toISOString()});for(let Y of k){let ve=Y.originalContext||{channel:Y.channel,sender:Y.sender,chatId:Y.chatId};this.execute({message:Y.text,agentId:e.agentId,context:ve,queuedAt:Y.queuedAt??Y.timestamp}).then(fe=>(ze(fe.error)||G(),this.postQueuedResponseToChannel(e.agentId,ve,fe)),fe=>{throw G(),fe}).catch(fe=>{this.log(`[${e.agentId}] queued message failed: ${fe.message}`)})}}).catch(k=>{Z().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:g,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${k.message}`)})};this.runReleases.set(p.id,Kn),this.messageQueue.markRunning(e.agentId,u,g),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${O()}`);let y=e.context?.channel||"api",{evaluateRequest:Vi,selectRequestContext:Zi}=await import("./request-planner-GBX6DHRQ.js"),Jn=te("request-gate",()=>Vi(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Qt=!1;Jn.then(()=>{Qt=!0},()=>{Qt=!0});let I=g,zt=e.context?.sender||"User",ce=d.def.tier==="codex-cli",We=li(this.config.session,y,d.def.tier),dt=gi(this.config.session),qe=We==="lean"&&dt.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,I),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${I}`),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}));let ct=this.sessions.sessionIdleMs(e.agentId,y,I);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,I,e.seedHistory),()=>{});let ea=[...this.sessions.getSession(e.agentId,y,I).messages].reverse().find(l=>l.role==="agent")?.content;Li({agent:e.agentId,channel:y,chatId:I,message:e.message,previousReply:ea,taskId:_}),this.sessions.addUserMessage(e.agentId,y,I,zt,e.message);let Qn=Date.now();Z().emit("task:started",{agentId:e.agentId,channel:y,chatId:I,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Qn).toISOString(),taskId:_,resumeOrigin:Po(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:dn(e.context),...x?{person:x}:{},humanRoot:Ke(e.context),pickup:As(e.context),operator:Cs(e.context)}),ne=!0;let ee,Xt,zn=this.classifier;if(zn&&y!=="a2a"&&!ce){C("classify");let l=Date.now();Xt=zn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:I,agentId:e.agentId}).then(f=>{ee=f||void 0,ee?.path?.length&&(p.intentPath=ee.path.slice()),D("classify",l,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),D("classify",l,"error")})}let Xn=async l=>{if(!Xt)return;let f;await Promise.race([Xt,new Promise(v=>{f=setTimeout(v,l),f.unref?.()})]),f&&clearTimeout(f)};await Xn(Eu);let Se=this.config.workflows?.matching,pe,Yn,Vn=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&Vn?.enabled&&(Vn.agents[e.agentId]??!0)&&!i&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=(Se?.suggestThreshold??.65)&&(Yn=fr(f.workflow))}catch(l){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${l?.message||l}`)}if(this.config.workflows?.enabled&&Se?.enabled&&!i)try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list());f&&f.confidence>=Se.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Se.mode} reasons=${f.reasons.join(",")||"n/a"}`),Se.mode==="auto"&&f.confidence>=Se.autoRunThreshold&&(this.workflowAutoRunner?pe={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(l){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${l?.message||l}`)}let Te=mr(this.config.workflows,e.agentId)&&hr(e)?this.workflowRuns:void 0;if(Te&&!pe&&!i&&this.workflowAutoRunner&&Ke(e.context))try{let l=new kt({baseDir:Q(process.cwd(),this.config.workflows.dir)}),f=vt({agentId:e.agentId,channel:y,message:e.message,intentPath:ee?.path},l.list()),v=Se?.autoRunThreshold??.85;f&&f.confidence>=v&&(pe={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(l){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${l?.message||l}`)}let ae=Te?Fu():void 0,ta=ae?yr(ae):void 0,na=this.wikiHub.getAgentWiki(e.agentId),Zn=this.memoryStore.findRelevant(e.message,e.agentId,ce?3:8),es=this.memoryStore.buildContext(Zn),ts=this.memoryStore.contextFacts(Zn),sa=this.patternStore.findRelevant(e.message,e.agentId,5),ra=this.patternStore.buildContext(sa),ns="";if(!ce)try{let{loadLocalSkills:l,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),v=await W("skills",()=>l(d.def.workspace)),k=e.personLimits?.skills??[],j=k.length?v.filter(G=>!k.some(Y=>Je(Y,G.frontmatter.name))):v;ns=f(j,e.message)}catch{}let F=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,I):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,I):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,I):void 0;if(F&&this.sessions.isSessionStale(e.agentId,y,I,ct)&&(this.log(`[${e.agentId}] session stale for ${y}:${I}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"stale",at:new Date().toISOString()}),F=void 0),F&&this.sessions.shouldRotateByTierTwo(e.agentId,y,I)){let l=this.sessions.getLastTurnContextTokens(e.agentId,y,I);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${I} (last turn context: ${l} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"tier-2",lastTurnInputTokens:l,at:new Date().toISOString()}),F=void 0}if(F&&this.sessions.shouldRotateByTurns(e.agentId,y,I)){let l=this.sessions.getTurnCount(e.agentId,y,I);this.log(`[${e.agentId}] max-turns rotation for ${y}:${I} (${l} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"max-turns",at:new Date().toISOString()}),F=void 0}if(F&&d.def.tier==="claude-code"){let l=this.config.session?.resumeGate;if(l&&l.mode!=="off"){let f=Ur({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,y,I),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,y,I),idleMs:ct??0},l);if(f.rotate&&l.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${y}:${I}: ${mn(f)}`),this.captureRotationMemoAsync(e.agentId,d.def,F,y,I,"cost");let v=this.sessions.getLastTurnInputTokens(e.agentId,y,I);this.sessions.clearClaudeSessionId(e.agentId,y,I),Z().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:I,reason:"cost",lastTurnInputTokens:v,at:new Date().toISOString()}),F=void 0}else l.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${y}:${I}: would ${mn(f)}`)}}if(F&&d.def.tier==="claude-code"){let l=F;await te("rotate",()=>this.maybeRotateForContinuity(e,d,y,I,l),()=>!1)&&(F=void 0)}try{let l=await W("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,I,this.memoryStore));if(l.compacted){let f=l.qualityScore??"?",v=l.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${I} (quality: ${f}%, ${v} entities lost)`),l.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${l.lostEntities.slice(0,5).join(", ")}`),l.drift){let k=l.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}}}catch(l){this.log(`[${e.agentId}] compaction failed (non-fatal): ${l.message}`)}let oa=process.env.AGENTX_CONTEXT_SURGERY==="1",ia=ce?{maxMessages:8,maxChars:2400}:oa&&Gi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,aa=!F&&!ce?zu(na,e.agentId,{notesInbox:Qu(this.config)}):void 0,ut=!F&&!qe?this.sessions.buildHistoryContext(e.agentId,y,I,ia):void 0,da=F?void 0:this.sessions.getRotationMemo(e.agentId,y,I)??void 0,ss,rs=[];if(this.config.procedures?.injection?.enabled&&!F&&!ce)try{let l=new ot({baseDir:Q(process.cwd(),this.config.procedures.dir)}),f=Fn(e.message,l.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){ss=Un(f),rs=f.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of f)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(l){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${l?.message||l}`)}if($e&&$e.cat)try{let f=this.sessions.getSession(e.agentId,y,I).messages,v=f[0],k=f[f.length-1],j=ut===void 0?`resume=${F?F.slice(0,8):"?"} (no rebuild)`:`fresh history=${ut.length}c/${ut.split(`
|
|
142
142
|
`).length}L`,G=`[${e.agentId}] ${y}:${I} ${j} | session.messages=${f.length}`+(f.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")})`:"");$e.cat("context",G)}catch(l){$e.cat("context",`[${e.agentId}] context-diag error: ${l?.message??l}`)}let os;if(d.def.contextReferences&&!F)try{let l=d.def.workspace,f=this.referencesCache.get(l);if(!f){let[k,j]=await W("references",()=>Promise.all([ln(d.def.workspace),gn(d.def.workspace)]));if(k.byId.size===0&&j.recipes.length===0){let[G,Y]=await W("references",()=>Promise.all([ln(process.cwd()),gn(process.cwd())]));f={refs:G,recipes:Y}}else f={refs:k,recipes:j};this.referencesCache.set(l,f)}let v=or({agentId:e.agentId,intentTags:ee?.path,message:e.message},f.recipes,f.refs);v.cards.length>0&&(os=sr(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(l){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${l?.message||l}`)}let is=qe?"":this.sessions.getCrossSessionSummary(e.agentId,y,I,e.message),as,lt=vo(e.message);if(lt)try{let l=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:I,lookbackDays:lt.lookbackDays,limit:12});if(l.turns.length>0){let f=[`[Long-memory recall \u2014 last ${lt.lookbackDays}d on this chat (cue-triggered)]`],v=[...l.turns].sort((k,j)=>k.ts.localeCompare(j.ts));for(let k of v){let j=k.ts.slice(11,16)+" "+k.day,G=k.role==="user"?k.senderName||"User":k.senderName||"Agent";f.push(`${j} ${G}: ${k.content}`)}l.hasMore&&f.push(`[\u2026${l.totalScanned-l.turns.length}+ older turns available \u2014 call /recall with before=${l.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),as=f.join(`
|
|
143
143
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${lt.lookbackDays}d, turns=${l.turns.length}, scanned=${l.totalScanned}`)}}catch(l){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${l.message}`)}let ca=ce?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",ds,cs,us=!1;Qt||C("request-gate");let ke=await Jn;if(ke.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),ca==="planner"&&!ke.active&&!qe&&y!=="voice"&&y!=="desktop"){try{let{planContext:l}=await import("./context-planner-3JDA7FNR.js"),f=await W("plan-context",()=>l({agentId:e.agentId,channel:y,chatId:I,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(us=!0,ds=f.sessionHistory,es=f.memoryContext,ts=f.memoryFacts,is=f.crossChatContext,cs=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(l){this.log(`[${e.agentId}] planner failed (non-fatal): ${l.message} \u2014 falling back to layered (keeping --resume for continuity)`)}us&&F&&(this.sessions.clearClaudeSessionId(e.agentId,y,I),F=void 0)}let Yt=`${e.agentId}:${y}:${I}`,gt=js(e.message);gt&&(gt==="default"?(this.activeSouls.delete(Yt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Yt,gt),this.log(`[${e.agentId}] Soul switched to: ${gt}`)));let ua=this.activeSouls.get(Yt),la=Hs(d.def.workspace,ua),ga=Bs(la),pa=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),fa=Bu(d.def.tier),ma=Zu(d.def.richMessages,y),ha=d.def.tier==="claude-code"&&(We!=="lean"||pi(dt)),ls="";if(d.def.workspace&&!ha){let l=Q(d.def.workspace,"CLAUDE.md");if(de(l))try{let f=it(l,"utf-8");ls=`[Project CLAUDE.md]
|
|
144
144
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
@@ -152,9 +152,9 @@ ${ve}`),f+=ve.length}catch{}}}let ya=Vt.length>0?Vt.join(`
|
|
|
152
152
|
|
|
153
153
|
`)||void 0,en={channel:y,chatId:I,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:zt,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ce||qe||Gi(y,d.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:ce?void 0:ra||void 0,procedureContext:[ss,Yn].filter(Boolean).join(`
|
|
154
154
|
|
|
155
|
-
`)||void 0,workflowRunContext:ta,references:os,skillInjection:ns||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ds??ut,memoryContext:es||void 0,crossChatContext:is||void 0,longMemoryRecall:as||void 0,contextOnDemand:qe&&!F?wi(y,I):void 0,wikiContext:aa,handoverNote:this.buildHandoverNote(e.agentId,y,I),rotationMemo:da,eventDigest:F?void 0:Ju(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let l=$r(y,!F,d.def.richMessages);return l?Xu(d.def.workspace,l):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message},ft=e.model?void 0:Ls({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?ct:null});ft?.downgraded&&this.log(`[${e.agentId}] ${ft.reason}`);let gs=Ns(d.def.tier,this.config.decisions.routing),ps=ft?.downgraded?Promise.resolve(ft.model):!e.model&&gs&&(!ke.active||ke.preprocess)?(async()=>{try{let{routeTaskModel:l}=await import("./routing-
|
|
155
|
+
`)||void 0,workflowRunContext:ta,references:os,skillInjection:ns||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:ds??ut,memoryContext:es||void 0,crossChatContext:is||void 0,longMemoryRecall:as||void 0,contextOnDemand:qe&&!F?wi(y,I):void 0,wikiContext:aa,handoverNote:this.buildHandoverNote(e.agentId,y,I),rotationMemo:da,eventDigest:F?void 0:Ju(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let l=$r(y,!F,d.def.richMessages);return l?Xu(d.def.workspace,l):void 0})(),intent:ee?{path:ee.path,pathLabel:ee.pathLabel,pathId:ee.pathId,axes:ee.axes,leaf:ee.leaf,status:ee.status}:void 0,message:e.message},ft=e.model?void 0:Ls({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!F,sessionIdleMs:F?ct:null});ft?.downgraded&&this.log(`[${e.agentId}] ${ft.reason}`);let gs=Ns(d.def.tier,this.config.decisions.routing),ps=ft?.downgraded?Promise.resolve(ft.model):!e.model&&gs&&(!ke.active||ke.preprocess)?(async()=>{try{let{routeTaskModel:l}=await import("./routing-S3L44JLL.js"),f=await W("route-model",()=>l({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!F,sessionIdleMs:F?ct:null,cheapModel:gs}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),fs=!1;ps.then(()=>{fs=!0});let mt=ke.active&&ke.preprocess?await te("select-context",()=>Zi(en),()=>({input:en,excluded:[]})):{input:en,excluded:[]};mt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${mt.excluded.join(", ")}`);let ht=Mo(mt.input,ce?{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),wa=Vs(ht,{memory:ts,procedures:rs,wikiContext:mt.input.wikiContext}),tn=(ht?.length??0)+(Zt?.length??0)+(e.message?.length??0),yt={history:ht?.length??0,sysPrompt:Zt?.length??0,message:e.message?.length??0},ms=si(e.agentId,y,I);ri(ms,tn,yt);let hs=oi(ms);hs&&this.log(`[${e.agentId}] ${hs}`),tn>16e3&&this.log(`[${e.agentId}] large context for ${y}:${I}: ${tn} bytes (history=${yt.history}, sysPrompt=${yt.sysPrompt}, message=${yt.message})`),fs||C("route-model");let ys=await ps,ws=d.def.tier!=="claude-code"?void 0:We==="lean"?mi(d.def.workspace,dt,void 0,y):yi(d.def.workspace);We==="lean"&&!F&&this.log(`[${e.agentId}] session profile for ${y}: ${bi(We,dt,y)}`);let bs=d.def.tier==="claude-code"&&!F?Lr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:_},l=>this.log(l)):void 0,ba={...e,systemPromptAppend:Zt,...ws?{claudeArgs:ws}:{},...ys?{model:ys}:{}},re,xs=Di({agent:e.agentId,request:e.message,taskId:_,budgetMinutes:d.def.maxExecutionMinutes??20}),xa=H,Is=!1,nn=!0;H=l=>{if(xs.observe(l),ae&&nn)for(let f of br(l))wr(f.name,f.input)||(nn=!1);xa?.(l)};try{let l=this.workflowAutoRunner;if(pe&&l){let E=pe;try{let J=await W("workflow-auto-run",()=>l({workflowId:E.workflowId,agentId:e.agentId,channel:y,chatId:I,message:e.message,...E.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:y,chatId:I,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ee?.path,matchedWorkflowId:E.workflowId,matchConfidence:E.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${pe.workflowId} run=${J.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:E.follow?`Started the workflow "${J.title??E.workflowId}" for this${J.runId?` (run ${J.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:pe.workflowId,workflowRunId:J.runId,workflowMatchConfidence:pe.confidence}},re}catch(J){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${J?.message||J}`)}}if(ae&&Te)try{let E=Ir(Te,e.resumedFrom);xr(Te,{runId:ae,agentId:e.agentId,channel:y,chatId:I,message:e.message,taskId:_,...E?{continues:E}:{}}),Is=!0,p.workflow={runId:ae,workflowId:pr}}catch(E){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${E?.message||E}`)}let f=()=>{if(d.def.tier!=="claude-code")return null;C("dispatch-gate");let E=d.def.persistentProcess?Pt():null,J=E!=null&&E.hasLive({agentId:e.agentId,channel:y,chatId:I}),he=!!F||J,ue=[jo(he),ti(he,void 0,e.model||d.def.model)].find(xt=>xt&&xt.abort);if(ue){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ue.reason}`);let xt={content:"",error:ue.message,duration:0};if(!t){w.buffer=`[error] ${ue.message}`;for(let Ia of w.subscribers)try{Ia(w.buffer)}catch{}}return xt}Jo();let Ge=ni();return Ge&&this.log(`[${e.agentId}] ${Ge}`),null},v=this.planCloudSession(d.def,e);if(v.route==="local"){let E=f();if(E)return d.errors++,re=E,E}let k=d.def.tier==="claude-code",j=k?t:(E,J)=>{E&&P(E),t&&t(E,J)},G=!1,Y=k?s:E=>{E&&(G?P(E):(P(`\u{1F4AD} ${E}`),G=!0)),s&&s(E)},ve=()=>{G&&(P(`
|
|
156
156
|
`),G=!1)},fe=k?j:j?(E,J)=>{ve(),j(E,J)}:void 0,$=await W("agent",async()=>{if(v.route!=="local"){let E=await this.runCloudSession(d.def,e,v,_);if(E)return E;let J=f();if(J)return J}return So(d.def,ba,this.providers,fe,ht,F,H,S.signal,Y)},Wu);if(!$.error){let E=Yu(d.def.toolUseRequired,M);if(E){let J=Array.from(M.entries()).map(([he,bt])=>`${he}=${bt}`).join(", ")||"none";$.error=`tool_required_not_called: ${E} (invoked: ${J})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${E}, observed ${J}`)}}bs&&Fr(bs,{toolUses:M,eventsSeen:N,error:$.error,agentId:e.agentId},E=>this.log(E));let wt=this.interruptedRuns.get(p.id);wt&&($.content="",$.error=wt,$.errorKind="interrupted");let sn=wt?void 0:this.stoppedRuns.get(p.id);sn&&($.content="",$.error=sn,$.errorKind="stopped"),re=$;let me=$.usage?Xs($.usage):void 0;if(R=!0,Z().emit("task:completed",{taskId:_,agentId:e.agentId,channel:y,chatId:I,durationMs:Date.now()-Qn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:wt?!0:void 0,stopped:sn?!0:void 0,inputTokens:me?.inputTokens,outputTokens:me?.outputTokens,cacheReadTokens:me?.cacheReadTokens,cacheCreateTokens:me?.cacheCreateTokens,tier2InputTokens:me?.tier2InputTokens,tier2OutputTokens:me?.tier2OutputTokens,tier2CacheReadTokens:me?.tier2CacheReadTokens,tier2CacheCreateTokens:me?.tier2CacheCreateTokens,resumed:!!F,resumeSessionId:F||void 0,jevArm:ke.arm,numTurns:$.numTurns,injectedContext:wa,finalResponse:$.content||void 0,billedModel:$.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let E=$.error?`[error] ${$.error}`:$.content;w.buffer=E;for(let J of w.subscribers)try{J(E)}catch{}}if($.error)d.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,I,$.content),Ni({agent:e.agentId,channel:y,chatId:I,request:e.message,reply:$.content,taskId:_}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,I,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,I,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,I,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,y,I,$.usage,$.contextTokens),$.usage){let ue=$.contextTokens,Ge=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ue??Ge)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${I}: context=${ue??"n/a"} tokens (cumulative turn total=${Ge}) \u2014 next turn will rotate`)}if(Gs({channel:y,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await Xn(Du);try{let ue=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ue,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
157
157
|
|
|
158
158
|
Agent: ${$.content}`,meta:Ku(ee,e.context)})}catch{}Ks(e.agentId,e.message,$.content,{channel:y,chatId:I,sender:zt},this.memoryStore).catch(()=>{}),No(e.agentId,e.message,$.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=$.billedModel||e.model||d.def.model,he=e.context?.channel,bt=he&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${he}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,J,he,bt),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${O()}`)}return $}catch(l){d.errors++,this.log(`[${e.agentId}] unexpected error: ${l.message}`);let f=At(l.message);return re={content:"",error:Ct(f),errorKind:f.kind},re}finally{if(xs.stop(),Is&&ae&&Te)try{let l=re?.usage,f=Sr(Te,ae,{error:re?re.error||void 0:S.signal.aborted?Re(S.signal).message:"run ended before completion",canceled:Tr(re?.errorKind)||this.stoppedRuns.has(p.id)||this.interruptedRuns.has(p.id)||!re&&S.signal.aborted,durationMs:Date.now()-p.startedAt.getTime(),...l?{inputTokens:l.inputTokens,outputTokens:l.outputTokens}:{},readOnly:nn,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(l){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${l?.message||l}`)}se(re),Kn(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:kr(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=Q(process.cwd(),je,this.safe(e.agentId),t);de(s)||Ou(s,{recursive:!0});let r=Q(s,`${this.safe(e.id)}.json`);Lu(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=Q(process.cwd(),je,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let g of[d,c]){let m=Q(a,g);if(de(m))try{for(let h of ge(m)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],x=parseInt(p,10);if(!Number.isFinite(x)||x<i||x>s)continue;let S=Math.floor((s-x)/36e5),w=t-1-S;w>=0&&w<t&&o[w]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=Q(process.cwd(),je);if(!de(e))return 0;let t=0;for(let s of ge(e)){let r=Q(e,s),o;try{o=ge(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=Q(r,i),c;try{c=ge(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(it(Q(a,d),"utf-8")),g=(u.responseText||u.error||"").trim();if(!g)continue;let m=g.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:m,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Gu){let t=Q(process.cwd(),je);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ge(t)){let i=Q(t,o),a;try{a=ge(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{Nu(Q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return[];let r=ge(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=Q(s,i),c;try{c=ge(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(it(Q(a,d),"utf-8")),{transcript:g,responseText:m,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=Q(process.cwd(),je,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=ge(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=Q(s,i,`${r}.json`);if(de(a))try{return JSON.parse(it(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=gr();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||ze(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(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}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}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 c=Lt(a);return c.channel===t.channel&&c.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:c,originalMessage:d}=o,u=o.controller.signal.aborted,g=!1;u&&d&&(g=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let m=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:m,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Z().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(m).toISOString(),sender:{name:s},humanRoot:!1,person:Ms(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:m});let p=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${g?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:g,pending:h}}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,c=i.chatId;return new Promise(d=>{let u=!1,g=m=>{u||(u=!0,d(m))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:m=>g({ok:!0,agentId:e,channel:a,chatId:c,taskId:m,queued:!1})}).then(m=>{ze(m.error)?g({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):m.error?g({ok:!1,status:500,error:m.error||"run did not start"}):g({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:m.viaAttachedSession?"attached":"other"})}).catch(m=>g({ok:!1,status:500,error:m?.message??String(m)}))})}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 Zu(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(`
|
|
159
159
|
`)}export{qr as a,fl as b,Kr as c,Ua as d,Jr as e,Rt as f,Al as g,Rl as h,_l as i,Ll as j,Lt as k,id as l,bo as m,ld as n,gd as o,pd as p,So as q,Ft as r,Ut as s,Dd as t,lg as u,gg as v,Rn as w,Z as x,Lo as y,qd as z,Qd as A,Ho as B,Mg as C,Bo as D,Go as E,Yo as F,Wg as G,Vo as H,jt as I,Qg as J,zg as K,ot as L,Zc as M,eu as N,tu as O,nu as P,su as Q,Fn as R,Hu as S,Bu as T,Ff as U,Uf as V,Ku as W,Ju as X,zu as Y,Gn as Z,Ji as _,Qi as $,Yu as aa,zi as ba,Xi as ca,Zu as da};
|
|
160
|
-
//# sourceMappingURL=chunk-
|
|
160
|
+
//# sourceMappingURL=chunk-5ADXRVYT.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{q as d}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{q as d}from"./chunk-23LWLYOK.js";import{b as i,c as u,d as l,e as c}from"./chunk-BXXP6DTB.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-5RHCM3L7.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-MXDWLBIA.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-635B6SXI.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-SQ37I2MD.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-7JUISIE7.js.map
|