agentix-cli 0.86.0 → 0.88.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-NLEBAGQK.js → App-BSGDYHRD.js} +2 -2
- package/dist/{ChatApp-JN2WJ7ZK.js → ChatApp-K57DBCDT.js} +2 -2
- package/dist/{agent-QORMJHWT.js → agent-6MTUM5DR.js} +2 -2
- package/dist/{board-dashboard-YG3MBOXP.js → board-dashboard-MHMXII6V.js} +414 -220
- package/dist/board-dashboard-MHMXII6V.js.map +1 -0
- package/dist/{chunk-YK6VYYHC.js → chunk-2FLVU2QW.js} +2 -2
- package/dist/{chunk-GO57OXET.js → chunk-54VYZE7A.js} +10 -10
- package/dist/{chunk-GO57OXET.js.map → chunk-54VYZE7A.js.map} +1 -1
- package/dist/{chunk-CZ4CWVDE.js → chunk-7ADEEHZQ.js} +2 -2
- package/dist/{chunk-AXW5U32B.js → chunk-7K5SJJUI.js} +2 -2
- package/dist/{chunk-5PEOSZ44.js → chunk-7OEFPYQJ.js} +2 -2
- package/dist/{chunk-VQVN3VSJ.js → chunk-7QDAGGOD.js} +2 -2
- package/dist/{chunk-CPXZWVKN.js → chunk-BFY4D4RH.js} +2 -2
- package/dist/{chunk-RLSRENAO.js → chunk-BOENB3IK.js} +2 -2
- package/dist/{chunk-NY7ZZGT3.js → chunk-BUELCBBV.js} +27 -27
- package/dist/{chunk-NY7ZZGT3.js.map → chunk-BUELCBBV.js.map} +1 -1
- package/dist/{chunk-KK6HPN3U.js → chunk-C3VCIEZS.js} +6 -6
- package/dist/chunk-C3VCIEZS.js.map +1 -0
- package/dist/{chunk-CL53UVOF.js → chunk-DWZYVYZS.js} +2 -2
- package/dist/chunk-DWZYVYZS.js.map +1 -0
- package/dist/{chunk-WBJLVFBW.js → chunk-ECCPLASB.js} +2 -2
- package/dist/{chunk-WLKQFYUM.js → chunk-EUXF2GJY.js} +2 -2
- package/dist/{chunk-QIJOGYK5.js → chunk-HOXHUFZB.js} +2 -2
- package/dist/{chunk-TICACOQG.js → chunk-HQWMWSSE.js} +2 -2
- package/dist/{chunk-SPSICIEA.js → chunk-I6HCIQCQ.js} +2 -2
- package/dist/{chunk-FRWV3XOV.js → chunk-KIXDJEGA.js} +2 -2
- package/dist/{chunk-FORTAGGM.js → chunk-L6BO76GK.js} +161 -161
- package/dist/chunk-L6BO76GK.js.map +1 -0
- package/dist/{chunk-NNAMMKT7.js → chunk-MZQ5PCLA.js} +2 -2
- package/dist/{chunk-ANJ2BO7D.js → chunk-N4HFUAPN.js} +2 -2
- package/dist/{chunk-O5U5NVLR.js → chunk-OAA7TNB6.js} +2 -2
- package/dist/{chunk-YSV53UFR.js → chunk-TNR7AI4H.js} +5 -5
- package/dist/{chunk-DTXI7LEI.js → chunk-X2F3AVGR.js} +2 -2
- package/dist/{chunk-M457SOS3.js → chunk-XVDASTUX.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-5Z4IVYAH.js → client-UKLOVDZB.js} +2 -2
- package/dist/config-WUDWHRT6.js +2 -0
- package/dist/config-mutator-UPLM7KGO.js +2 -0
- package/dist/{doctor-UKWJO3TG.js → doctor-COAIIKLV.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/processes-TXEWMXXJ.js +2 -0
- package/dist/{program-PUG7P7TC.js → program-VX4XZAE6.js} +14 -14
- package/dist/{promote-3R56RJQD.js → promote-B7FGHUFA.js} +2 -2
- package/dist/{query-6ZTEUTKC.js → query-ZSVAGGSM.js} +2 -2
- package/dist/{registry-KJZDXHKL.js → registry-4DWWYWDR.js} +2 -2
- package/dist/{request-planner-JFES5YW2.js → request-planner-DSXXT75B.js} +2 -2
- package/dist/{review-candidates-OR375PHS.js → review-candidates-34S6R3DJ.js} +2 -2
- package/dist/{routing-W2E52LYP.js → routing-HWGNYIF3.js} +2 -2
- package/dist/schedule-tool-JLIS2GQU.js +2 -0
- package/dist/scheduler-F6NRVZ7W.js +2 -0
- package/dist/{seat-GAS7YKQA.js → seat-OQZY3CW7.js} +2 -2
- package/dist/{select-UYFJH4V5.js → select-BBTWL7FN.js} +2 -2
- package/dist/{set-enabled-PFMELM3V.js → set-enabled-OC3YT4D4.js} +2 -2
- package/dist/{tool-BGEHMLJ3.js → tool-P4AHNZ5O.js} +2 -2
- package/dist/{tool-W4NSPPXO.js → tool-R36FDI6E.js} +2 -2
- package/dist/wiki-5E4AGLKY.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-YG3MBOXP.js.map +0 -1
- package/dist/chunk-CL53UVOF.js.map +0 -1
- package/dist/chunk-FORTAGGM.js.map +0 -1
- package/dist/chunk-KK6HPN3U.js.map +0 -1
- package/dist/config-2SRJEOO7.js +0 -2
- package/dist/config-mutator-RKEMP53O.js +0 -2
- package/dist/processes-5EXCTSD5.js +0 -2
- package/dist/schedule-tool-XZL5AKFB.js +0 -2
- package/dist/scheduler-BOQJMSJE.js +0 -2
- package/dist/wiki-L5FJ5RYE.js +0 -2
- /package/dist/{App-NLEBAGQK.js.map → App-BSGDYHRD.js.map} +0 -0
- /package/dist/{ChatApp-JN2WJ7ZK.js.map → ChatApp-K57DBCDT.js.map} +0 -0
- /package/dist/{agent-QORMJHWT.js.map → agent-6MTUM5DR.js.map} +0 -0
- /package/dist/{chunk-YK6VYYHC.js.map → chunk-2FLVU2QW.js.map} +0 -0
- /package/dist/{chunk-CZ4CWVDE.js.map → chunk-7ADEEHZQ.js.map} +0 -0
- /package/dist/{chunk-AXW5U32B.js.map → chunk-7K5SJJUI.js.map} +0 -0
- /package/dist/{chunk-5PEOSZ44.js.map → chunk-7OEFPYQJ.js.map} +0 -0
- /package/dist/{chunk-VQVN3VSJ.js.map → chunk-7QDAGGOD.js.map} +0 -0
- /package/dist/{chunk-CPXZWVKN.js.map → chunk-BFY4D4RH.js.map} +0 -0
- /package/dist/{chunk-RLSRENAO.js.map → chunk-BOENB3IK.js.map} +0 -0
- /package/dist/{chunk-WBJLVFBW.js.map → chunk-ECCPLASB.js.map} +0 -0
- /package/dist/{chunk-WLKQFYUM.js.map → chunk-EUXF2GJY.js.map} +0 -0
- /package/dist/{chunk-QIJOGYK5.js.map → chunk-HOXHUFZB.js.map} +0 -0
- /package/dist/{chunk-TICACOQG.js.map → chunk-HQWMWSSE.js.map} +0 -0
- /package/dist/{chunk-SPSICIEA.js.map → chunk-I6HCIQCQ.js.map} +0 -0
- /package/dist/{chunk-FRWV3XOV.js.map → chunk-KIXDJEGA.js.map} +0 -0
- /package/dist/{chunk-NNAMMKT7.js.map → chunk-MZQ5PCLA.js.map} +0 -0
- /package/dist/{chunk-ANJ2BO7D.js.map → chunk-N4HFUAPN.js.map} +0 -0
- /package/dist/{chunk-O5U5NVLR.js.map → chunk-OAA7TNB6.js.map} +0 -0
- /package/dist/{chunk-YSV53UFR.js.map → chunk-TNR7AI4H.js.map} +0 -0
- /package/dist/{chunk-DTXI7LEI.js.map → chunk-X2F3AVGR.js.map} +0 -0
- /package/dist/{chunk-M457SOS3.js.map → chunk-XVDASTUX.js.map} +0 -0
- /package/dist/{client-5Z4IVYAH.js.map → client-UKLOVDZB.js.map} +0 -0
- /package/dist/{config-2SRJEOO7.js.map → config-WUDWHRT6.js.map} +0 -0
- /package/dist/{config-mutator-RKEMP53O.js.map → config-mutator-UPLM7KGO.js.map} +0 -0
- /package/dist/{doctor-UKWJO3TG.js.map → doctor-COAIIKLV.js.map} +0 -0
- /package/dist/{processes-5EXCTSD5.js.map → processes-TXEWMXXJ.js.map} +0 -0
- /package/dist/{program-PUG7P7TC.js.map → program-VX4XZAE6.js.map} +0 -0
- /package/dist/{promote-3R56RJQD.js.map → promote-B7FGHUFA.js.map} +0 -0
- /package/dist/{query-6ZTEUTKC.js.map → query-ZSVAGGSM.js.map} +0 -0
- /package/dist/{registry-KJZDXHKL.js.map → registry-4DWWYWDR.js.map} +0 -0
- /package/dist/{request-planner-JFES5YW2.js.map → request-planner-DSXXT75B.js.map} +0 -0
- /package/dist/{review-candidates-OR375PHS.js.map → review-candidates-34S6R3DJ.js.map} +0 -0
- /package/dist/{routing-W2E52LYP.js.map → routing-HWGNYIF3.js.map} +0 -0
- /package/dist/{schedule-tool-XZL5AKFB.js.map → schedule-tool-JLIS2GQU.js.map} +0 -0
- /package/dist/{scheduler-BOQJMSJE.js.map → scheduler-F6NRVZ7W.js.map} +0 -0
- /package/dist/{seat-GAS7YKQA.js.map → seat-OQZY3CW7.js.map} +0 -0
- /package/dist/{select-UYFJH4V5.js.map → select-BBTWL7FN.js.map} +0 -0
- /package/dist/{set-enabled-PFMELM3V.js.map → set-enabled-OC3YT4D4.js.map} +0 -0
- /package/dist/{tool-BGEHMLJ3.js.map → tool-P4AHNZ5O.js.map} +0 -0
- /package/dist/{tool-W4NSPPXO.js.map → tool-R36FDI6E.js.map} +0 -0
- /package/dist/{wiki-L5FJ5RYE.js.map → wiki-5E4AGLKY.js.map} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-BOENB3IK.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-I6HCIQCQ.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
|
|
2
2
|
`)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
|
|
4
4
|
`),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-MZQ5PCLA.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as o}from"./chunk-7OEFPYQJ.js";import{resolve as a}from"path";import{existsSync as d,readdirSync as c,mkdirSync as l}from"fs";var g=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(t=a(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki-hub]"),r="graph"){this.baseDir=t,this.agentsDir=a(t,"agents"),this.mode=r,this.log=e,l(this.agentsDir,{recursive:!0}),this.sharedStore=new o(t,e)}getMode(){return this.mode}getAgentWiki(t){let e=`${t}:${this.mode}`;if(this.agentStores.has(e))return this.agentStores.get(e);let r=a(this.agentsDir,t,this.mode),i=new o(r,this.log);return this.agentStores.set(e,i),i}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}listAgents(){let t=new Set,e=this.sharedStore.listEntries();for(let r of e)t.add(r.agentId);if(d(this.agentsDir))for(let r of c(this.agentsDir))!r.startsWith("_")&&!r.startsWith(".")&&t.add(r);return[...t].sort()}getAgentEntries(t){return this.sharedStore.listEntries({agentId:t})}getUnabsorbedEntries(t){let e=this.getAgentWiki(t),r=this.getAgentEntries(t),i=new Set,n=e.rebuildIndex();for(let s of n.articles)if(s.sources)for(let h of s.sources)i.add(h);return r.filter(s=>!i.has(s.id))}summary(){return this.listAgents().map(e=>{let r=this.getAgentEntries(e),n=this.getAgentWiki(e).rebuildIndex(),s=this.getUnabsorbedEntries(e);return{agentId:e,totalEntries:r.length,totalArticles:n.articles.length,unabsorbed:s.length,articles:n.articles}})}};export{g as a};
|
|
2
|
+
//# sourceMappingURL=chunk-N4HFUAPN.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as t,d as u,e as v,f,g as w}from"./chunk-
|
|
1
|
+
import{a as t,d as u,e as v,f,g as w}from"./chunk-DWZYVYZS.js";var h=`:root {
|
|
2
2
|
/* --- Brand (agentina) --------------------------------------------- */
|
|
3
3
|
--ax-blue: #2979FF;
|
|
4
4
|
--ax-blue-d: #1B5FD9;
|
|
@@ -2021,4 +2021,4 @@ ${a.noAssistant?"":`<script>${$({markdownToHtml:z})}${y}</script>`}
|
|
|
2021
2021
|
const card = btn.closest('.ax-row-card');
|
|
2022
2022
|
if (card) card.classList.toggle('is-open');
|
|
2023
2023
|
};`;export{h as a,$ as b,z as c,T as d,A as e,H as f,O as g,j as h,I as i,L as j,F as k,B as l,P as m,M as n,E as o,N as p};
|
|
2024
|
-
//# sourceMappingURL=chunk-
|
|
2024
|
+
//# sourceMappingURL=chunk-OAA7TNB6.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as Ds,a as hs,b as fs,d as bs,f as Le,l as Ps,s as Rs,u as _s,z as Es}from"./chunk-
|
|
1
|
+
import{B as Ds,a as hs,b as fs,d as bs,f as Le,l as Ps,s as Rs,u as _s,z as Es}from"./chunk-KIXDJEGA.js";import{a as ms}from"./chunk-GLQLCBJS.js";import{b as ys}from"./chunk-DP7RTNDM.js";import{a as Ms}from"./chunk-W4YR2RO2.js";import{b as xs,c as Ut,d as ks,e as Is,h as Ss}from"./chunk-HQWMWSSE.js";import{a as ps}from"./chunk-N4HFUAPN.js";import{a as Ht,b as ws}from"./chunk-J3SOEFRE.js";import{a as jt,b as Ts}from"./chunk-SIU6STB2.js";import{e as vs,i as Cs,j as As,k as $s}from"./chunk-X5C5W3E4.js";import{a as ts}from"./chunk-2FLVU2QW.js";import{a as ns,c as ss}from"./chunk-MYVHVJWZ.js";import{a as rs,b as os,c as is,d as as,f as cs}from"./chunk-DWADWDMU.js";import{a as ds,b as us}from"./chunk-23A5K5UW.js";import{g as ls,h as gs}from"./chunk-HOXHUFZB.js";import{a as it,c as Ne}from"./chunk-2GIDVZ4H.js";import{q as Vn,t as Zn,v as Te,w as es}from"./chunk-ECCPLASB.js";import{a as Oe,b as ot,f as Ft}from"./chunk-72SZI2UW.js";import{a as xe,b as Et}from"./chunk-FCPTN6NF.js";import{c as jn,d as Un}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{A as Lt,C as Xo,E as Gn,I as Yo,O as Jn,P as Qn,Q as De,R as zn,S as Xn,U as Yn,ga as Vo,y as Kn}from"./chunk-54VYZE7A.js";import{a as Nt,i as zo}from"./chunk-PN6XHTG5.js";import{g as Ot,h as Qo}from"./chunk-BRK6M6LA.js";import{a as Bn,b as ie,c as Wn,d as qn,e as Dt}from"./chunk-2QNT5JDS.js";es();Ft();var Os="session-continuity",Ns={continues:Oe("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:Oe("Does the new request refer to something stated earlier in the conversation?")};function Ls(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Bt(s.message,1200),previousRequest:s.previousMessage?Bt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Bt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Fs(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Bt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{execa as mt}from"execa";import{spawn as Zo}from"node:child_process";import{createHash as ei}from"node:crypto";import{createInterface as ti}from"node:readline";var ue=class extends Error{},ni=s=>Zo("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Wt=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(),ti({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},qt=class{constructor(e=ni,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=ei("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([f],[b])=>f.localeCompare(b))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ue("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let f=[...this.entries].find(([,b])=>!b.connection.busy);if(!f)throw new ue("Codex warm process capacity reached");f[1].connection.close(),this.entries.delete(f[0])}try{r={fingerprint:n,connection:new Wt(e,this.launchProcess)}}catch{throw new ue("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,l,u,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let h=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),k=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 f={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...f,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let I=new Promise((E,_)=>{i.failTurn=_,i.notify=(C,O)=>{if(O?.threadId!==l)return;let F=O.item,D={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...O,type:C.replace("/","."),...F?{item:{...F,type:D[F.type]||F.type}}:{}}),C==="item/completed"&&F?.type==="agentMessage"&&F.phase==="final_answer"&&(c=F.text),C==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=O.delta,e.onDelta?.(O.delta,d)),C==="thread/tokenUsage/updated"){let L=O.tokenUsage.last,H=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-H),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+H,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(O.turn.status==="completed"?E():_(new Error(O.turn.error?.message||`Codex turn ${O.turn.status}`)))}});return I.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await I,{content:c??d,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(f){if(i.close(),!a&&!e.signal?.aborted)throw new ue(f.message);return{content:d,codexSessionId:l,usage:u,error:f.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(h),e.signal?.removeEventListener("abort",y),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())}}},Hs=new qt;import{execFile as ki}from"child_process";import{StringDecoder as Be}from"string_decoder";import{mkdtempSync as sr,readFileSync as rr,rmSync as or}from"fs";import{join as gt}from"path";import{tmpdir as ir}from"os";function at(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ct(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var js=null;function dt(){return js}function Kc(s){js=s}function Fe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function si(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var ke=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Us=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Fe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=si(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new ke(`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 ke(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Fe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Fe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Fe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Fe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";n.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as ri}from"child_process";import{existsSync as oi,readFileSync as ii}from"fs";import{resolve as ai}from"path";function ci(s){let e=ai(s,"CLAUDE.md");if(!oi(e))return null;try{let t=ii(e,"utf8");return cs(t)}catch{return null}}var di=20*60*1e3,ui=5e3,He=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},je=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function li(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var Bs=class{constructor(e={}){this.opts=e}spawn(e,t){return new Kt(e,t,this.opts)}},Kt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=ri(r,o,{cwd:t.workspace,env:Ne(li({...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:ci(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??di,d=o+a,c=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new He(a));try{for(;;){let l=d-Date.now();if(l<=0)throw c();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new je(this.killReason);if(u===null&&!this.exited)throw c();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},ui);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};Dt();zo();Et();import{resolve as Ws,join as qs}from"path";var gi=4e3;function ut(s){try{let e=qs(Ws(s.root),".agentx","db.sqlite"),t=Nt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=xe(),r=s.input.command?s.input.command.slice(0,gi):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Si(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};_.stdout?.on("data",v=>{D+=H.write(v);let w=D.split(`
|
|
28
28
|
`);D=w.pop()||"";for(let x of w)K(x)}),_.stderr?.on("data",v=>{L+=j.write(v)});let A=await _;if(i&&i.removeEventListener("abort",F),D+=H.end(),D.trim()&&K(D),L+=j.end(),C)return{content:"",error:O||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:y};if(A.exitCode!==0||h){let v=A,w;return v.timedOut?w=`OpenCode timed out after ${Math.round(I/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:h?w=h:v.code==="ENOENT"||/ENOENT|spawn opencode/i.test((v.shortMessage||"")+" "+L)?w=er():w=L.trim()||`OpenCode exited with code ${v.exitCode??"unknown"}`,{content:"",...Q(w),duration:Date.now()-d,usage:p,opencodeSessionId:y}}return f=!1,{content:u.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(I){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let E=/ENOENT|spawn opencode/i.test(I?.message||"")?er():I?.message;return{content:u,...Q(E||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:y}}finally{b?.(),k?.release(f)}}async function Oi(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ge(s,e,n),d="",c=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of c)l.type==="result"&&l.subtype==="success"&&(d=l.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ni(s,e,t,n,r,o,i,a,d){let c=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let f=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(f))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let h=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);h.unref?.();let k=()=>({content:"",...Q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let f=s.provider||"claude-code",b=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=as(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,I=e.context?.sender,E=typeof I=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(I),_=e.context?.channel==="web-chat"&&E?{userId:I,agentId:e.agentId||"acme-public"}:void 0,C=as(s),O=Object.keys(C).length>0,F={task:b,cwd:s.workspace,provider:f,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:_,providerOpts:o,abortSignal:u.signal,mcpServers:O?C:void 0};if(r){let{generateStream:K}=await import("./agent-6MTUM5DR.js"),A="",v,w,x,N;for await(let M of K(F)){if(d)try{d(M)}catch{}if(M.type==="text_delta")A+=M.text,r(M.text,A);else if(M.type==="thinking_delta")M.text&&i&&i(M.text);else if(M.type==="generate_result"){if(M.result.content&&M.result.content!==A){let Z=M.result.content.slice(A.length);Z?(A=M.result.content,r(Z,A)):A=M.result.content}v=M.result.tokensUsed,M.result.inputTokens!=null&&(w=M.result.inputTokens),M.result.outputTokens!=null&&(x=M.result.outputTokens)}else if(M.type==="done"){if(M.result.content&&M.result.content!==A){let Z=M.result.content.slice(A.length);Z?(A=M.result.content,r(Z,A)):A=M.result.content}M.result.tokensUsed!=null&&(v=M.result.tokensUsed)}else M.type==="error"&&(N=M.error)}return N&&!A?p?k():N==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${N}`),duration:Date.now()-c}:((w===void 0||x===void 0)&&v&&(w=Math.round(v*.7),x=v-w),{content:A||"Done.",tokensUsed:v,usage:w!==void 0||x!==void 0?{inputTokens:w||0,outputTokens:x||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:D}=await import("./agent-6MTUM5DR.js"),L=await D(F),H=L.inputTokens,j=L.outputTokens;if((H===void 0||j===void 0)&&L.tokensUsed){let K=L.tokensUsed;H=Math.round(K*.7),j=K-H}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:H!==void 0||j!==void 0?{inputTokens:H||0,outputTokens:j||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(f){return p?k():f?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Q(`Orchestrator error: ${f.message}`),duration:Date.now()-c}}finally{clearTimeout(h),a&&a.removeEventListener("abort",y)}}var Li=1e3;async function Fi(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),Li),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Hi(s,e,t,n,r,o,i){let a=dt();if(!a)return null;let d=Date.now(),{channel:c,chatId:l}=ft(e.context),u={agentId:e.agentId,channel:c,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let p,y=!1;try{let A=a.list().length;p=a.acquire(u,{agentId:e.agentId,channel:c,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),y=a.list().length>A}catch(A){return A instanceof ke,null}y&&Yt(e.agentId,s,e.model,n,"persistent");let h=ge(s,e,t),k="",f,b,I,E,_,C,O,F="",D="",L=A=>{if(!i||!A)return;let v;if(D&&A.startsWith(D)?v=A.slice(D.length):v=F&&!F.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${A}`:A,D=A,!!v){F+=v;try{i(v,F)}catch{}}},H=!1,j=()=>{H=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?j():o.addEventListener("abort",j,{once:!0}));let K=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let v of p.runTurn({message:h,taskId:e.taskId??"unknown",deadlineMs:A})){if(K=!0,r)try{r(v.raw)}catch{}if(v.type==="assistant"){let w=v.raw.message?.content??[];for(let N of w)N.type==="text"&&typeof N.text=="string"?(k=N.text,L(N.text)):N.type==="tool_use"&&(D="");let x=v.raw.message?.usage;if(x){let N=(x.input_tokens||0)+(x.cache_read_input_tokens||0)+(x.cache_creation_input_tokens||0);N>0&&(E=N)}}if(v.type==="result"){let w=v.raw;if(w.is_error){let x=Q(typeof w.result=="string"?w.result:"claude error");f=x.error,b=x.errorKind}else typeof w.result=="string"&&w.result.length>0&&(k=w.result,F||L(w.result));typeof w.session_id=="string"&&(O=w.session_id),w.usage&&(I={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(_=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(H)f="task cancelled by operator",b="cancelled";else if(K)if(A instanceof je)f=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,b="interrupted";else if(A instanceof He){let v=Q(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);f=v.error,b=v.errorKind}else{let v=Q(`persistent claude process error: ${A?.message||String(A)}`);f=v.error,b=v.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",j),null}finally{o&&o.removeEventListener("abort",j)}return H&&!f&&(f="task cancelled by operator",b="cancelled"),{content:H?"":k,error:f,errorKind:b,duration:Date.now()-d,usage:I,contextTokens:E,numTurns:_,billedModel:C,claudeSessionId:O}}function hr(s){let e=ie(s.autonomy);if(!e&&!s.personLimits)return{args:[]};if(!s.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?Js(s.autonomy,s.agentId,s.taskId):{args:[]};return"error"in t||!s.personLimits?t:Vs(t.args,s.taskId,s.agentId)}function ji(s){return ie(s.autonomy)||!!s.personLimits}async function Ui(s,e,t,n,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,d=a&&Qs(a,s.tier)||e.personLimits&&Zs(s.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:c,message:a?`${qn(a)}
|
|
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:ma,maxTokens:512})).content.trim().match(/\[[
|
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let d=!a&&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,n,r);if(d){let c=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${c}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let c=i.error?Le(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";xs().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=ie(e.autonomy),a=zn(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let d=i||a?null:jr().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(d){let g=await d;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let c=this.agents.get(e.agentId);if(!c){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 g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:l,chatId:u}=ft(e.context),p;if(c.activeTasks>=c.def.maxConcurrent)if(l==="api"||l==="app"||l==="a2a"||l==="mcp"||l==="reminder"||l==="events"||l==="guest"||i){let g=Date.now(),m=25*6e4,S=500;for(;c.activeTasks>=c.def.maxConcurrent;){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(R=>setTimeout(R,S))}}else if(l==="voice"){let g=Date.now(),m=25*6e4,S=`${e.agentId}\0${u}`;for(;this.messageQueue.isBusy(e.agentId,l,u)||this.voiceClaims.has(S);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(R=>setTimeout(R,500))}p=S,this.voiceClaims.add(S)}else{let g=c.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,l,u,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:l,chatId:u,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let S=this.messageQueue.pendingCount(e.agentId,l,u);return Y().emit("task:queued",{agentId:e.agentId,channel:l,chatId:u,at:new Date().toISOString(),sender:Lt(e.context),humanRoot:Ot(e.context)}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${c.runningTasks.map(R=>R.id).join(",")||"-"} chat=${l}:${u} at=${new Date().toISOString()}`),{content:"",error:bs(m,S)}}}let y=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(p&&this.voiceClaims.delete(p),!y.ok)return this.log(`[${e.agentId}] ${y.reason}`),{content:"",error:y.reason};if(e.queuedAt!==void 0){let g=Rr(e.queuedAt);g&&(e.message=`${g}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let h={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};c.runningTasks.push(h),e.runningTaskId=h.id;let k=Jn(this.config.people,e.context);if(e.context&&(k?e.context.person=k.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let f=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:f});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,b);let I=g=>{if(g){b.buffer+=g,b.buffer.length>xo&&(b.buffer=b.buffer.slice(b.buffer.length-xo));for(let m of b.subscribers)try{m(g)}catch{}}},E=xe();e.taskId=E;let _=new Map,C=(g,m,S)=>{try{Y().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},O=0,F=!1,D=()=>{F||(F=!0,O&&C("first-event",O,"ok"))},L;if(t){let g=Nc();L=m=>{D();let S=g(m);if(S&&I(S),Io(E,e.agentId,m),ko(_,m),r)try{r(m)}catch{}}}else L=g=>{if(D(),Io(E,e.agentId,g),ko(_,g),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,j=H?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;j?.unref?.();let K=(c.def.preSpawnTimeoutSec??Mc)*1e3,A=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(K/1e3)}s in step "${h.step??"start"}"`))},K);A.unref?.();let v=()=>{A&&clearTimeout(A),A=void 0},w=()=>`task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`,x;f.signal.addEventListener("abort",()=>{let g=Qe(f.signal).message;/^timed out/.test(g)&&(x=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let N=g=>{h.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},M=(g,m,S=0)=>{if(f.signal.aborted)return Promise.reject(Qe(f.signal));N(g),(g==="agent"||g==="workflow-auto-run")&&(v(),O=Date.now());let R=Date.now(),W=bo(m(),Cc[g]??0,g);return yo(W,f.signal,S).then(B=>(C(g,R,"ok"),B),B=>{throw C(g,R,"error"),B instanceof Me&&this.log(`[${e.agentId}] ${B.message}; continuing without it ${w()}`),B})},Z=async(g,m,S,R=0)=>{try{return await M(g,m,R)}catch(W){if(W instanceof Me)return S();throw W}},yn=!1,bn=g=>{if(yn)return;yn=!0,this.runReleases.delete(h.id),j&&clearTimeout(j),v(),c.activeTasks--;let m=c.runningTasks.findIndex(S=>S.id===h.id);m!==-1&&c.runningTasks.splice(m,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Ac).unref?.();try{let S=b.endedAt,R={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(R);let W=(R.responseText||R.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:R.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let R=Date.now(),W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:R,at:new Date().toISOString()});for(let B of S){let te=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:te,queuedAt:B.queuedAt??B.timestamp}).then($=>(Le($.error)||W(),this.postQueuedResponseToChannel(e.agentId,te,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{Y().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,bn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Co,selectRequestContext:Ao}=await import("./request-planner-
|
|
134
|
+
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),Ac).unref?.();try{let S=b.endedAt,R={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...x?{status:"timeout",step:x}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(R);let W=(R.responseText||R.error||"").trim();if(W){let B=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:B,at:S,ok:R.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,l,u).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${h.id} chat=${l}:${u} at=${new Date().toISOString()}`);let R=Date.now(),W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:R,at:new Date().toISOString()});for(let B of S){let te=B.originalContext||{channel:B.channel,sender:B.sender,chatId:B.chatId};this.execute({message:B.text,agentId:e.agentId,context:te,queuedAt:B.queuedAt??B.timestamp}).then($=>(Le($.error)||W(),this.postQueuedResponseToChannel(e.agentId,te,$)),$=>{throw W(),$}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(S=>{Y().emit("task:queue-ended",{agentId:e.agentId,channel:l,chatId:u,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(h.id,bn),this.messageQueue.markRunning(e.agentId,l,u),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${w()}`);let T=e.context?.channel||"api",{evaluateRequest:Co,selectRequestContext:Ao}=await import("./request-planner-DSXXT75B.js"),me=await Z("request-gate",()=>Co(e.message,e.agentId,T),()=>({active:!1,preprocess:!1}));me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let P=u,St=e.context?.sender||"User",se=c.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,T,P),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${T}:${P}`),Y().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:P,reason:"stale",at:new Date().toISOString()})),e.freshSession||await Z("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,T,P,e.seedHistory),()=>{});let $o=[...this.sessions.getSession(e.agentId,T,P).messages].reverse().find(g=>g.role==="agent")?.content;fo({agent:e.agentId,channel:T,chatId:P,message:e.message,previousReply:$o,taskId:E}),this.sessions.addUserMessage(e.agentId,T,P,St,e.message);let wn=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:T,chatId:P,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(wn).toISOString(),taskId:E,resumeOrigin:Mr(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Lt(e.context),...k?{person:k}:{},humanRoot:Ot(e.context),pickup:Kn(e.context),operator:Gn(e.context)});let V,vt,xn=this.classifier;if(xn&&T!=="a2a"&&!se){N("classify");let g=Date.now();vt=xn.classify({text:e.message,channel:T,sender:e.context?.sender,chatId:P,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(h.intentPath=V.path.slice()),C("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),C("classify",g,"error")})}let Tn=async g=>{if(!vt)return;let m;await Promise.race([vt,new Promise(S=>{m=setTimeout(S,g),m.unref?.()})]),m&&clearTimeout(m)};await Tn(Tc);let Re=this.config.workflows?.matching,we;if(this.config.workflows?.enabled&&Re?.enabled&&!i)try{let g=new Ps({baseDir:G(process.cwd(),this.config.workflows.dir)}),m=Rs({agentId:e.agentId,channel:T,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Re.mode} reasons=${m.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&m.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?we={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Mo=this.wikiHub.getAgentWiki(e.agentId),kn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),In=this.memoryStore.buildContext(kn),Sn=this.memoryStore.contextFacts(kn),Po=this.patternStore.findRelevant(e.message,e.agentId,5),Ro=this.patternStore.buildContext(Po),vn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await M("skills",()=>g(c.def.workspace)),R=e.personLimits?.skills??[],W=R.length?S.filter(B=>!R.some(te=>De(te,B.frontmatter.name))):S;vn=m(W,e.message)}catch{}let U=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,T,P):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,T,P):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,T,P):void 0;if(U&&this.sessions.isSessionStale(e.agentId,T,P)&&(this.log(`[${e.agentId}] session stale for ${T}:${P}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,P,"stale"),this.sessions.clearClaudeSessionId(e.agentId,T,P),Y().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:P,reason:"stale",at:new Date().toISOString()}),U=void 0),U&&this.sessions.shouldRotateByTierTwo(e.agentId,T,P)){let g=this.sessions.getLastTurnContextTokens(e.agentId,T,P);this.log(`[${e.agentId}] tier-2 rotation for ${T}:${P} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,P,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,T,P),Y().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:P,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),U=void 0}if(U&&this.sessions.shouldRotateByTurns(e.agentId,T,P)){let g=this.sessions.getTurnCount(e.agentId,T,P);this.log(`[${e.agentId}] max-turns rotation for ${T}:${P} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,U,T,P,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,T,P),Y().emit("session:rotated",{agentId:e.agentId,channel:T,chatId:P,reason:"max-turns",at:new Date().toISOString()}),U=void 0}if(U&&c.def.tier==="claude-code"){let g=U;await Z("rotate",()=>this.maybeRotateForContinuity(e,c,T,P,g),()=>!1)&&(U=void 0)}try{let g=await M("compact",()=>this.sessions.compactIfNeeded(e.agentId,T,P,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${T}:${P} (quality: ${m}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let R=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${R.overallScore} (lexicon=${R.lexiconDecay}, tools=${R.toolShift}, semantic=${R.semanticDrift})`),R.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${R.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let _o=process.env.AGENTX_CONTEXT_SURGERY==="1",Eo=se?{maxMessages:8,maxChars:2400}:_o&&wo(T,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Do=!U&&!se?Ec(Mo,e.agentId):void 0,Ye=U?void 0:this.sessions.buildHistoryContext(e.agentId,T,P,Eo),Oo=U?void 0:this.sessions.getRotationMemo(e.agentId,T,P)??void 0,Cn,An=[];if(this.config.procedures?.injection?.enabled&&!U&&!se)try{let g=new Je({baseDir:G(process.cwd(),this.config.procedures.dir)}),m=un(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Cn=ln(m),An=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,T,P).messages,S=m[0],R=m[m.length-1],W=Ye===void 0?`resume=${U?U.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ye.length}c/${Ye.split(`
|
|
135
135
|
`).length}L`,B=`[${e.agentId}] ${T}:${P} ${W} | session.messages=${m.length}`+(m.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${R.timestamp.slice(11,19)}(${R.role}:${(R.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",B)}catch(g){he.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let $n;if(c.def.contextReferences&&!U)try{let g=c.def.workspace,m=this.referencesCache.get(g);if(!m){let[R,W]=await M("references",()=>Promise.all([Ht(c.def.workspace),jt(c.def.workspace)]));if(R.byId.size===0&&W.recipes.length===0){let[B,te]=await M("references",()=>Promise.all([Ht(process.cwd()),jt(process.cwd())]));m={refs:B,recipes:te}}else m={refs:R,recipes:W};this.referencesCache.set(g,m)}let S=Ts({agentId:e.agentId,intentTags:V?.path,message:e.message},m.recipes,m.refs);S.cards.length>0&&($n=ws(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Mn=this.sessions.getCrossSessionSummary(e.agentId,T,P,e.message),Pn,Ve=wr(e.message);if(Ve)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:T,chatId:P,lookbackDays:Ve.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Ve.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((R,W)=>R.ts.localeCompare(W.ts));for(let R of S){let W=R.ts.slice(11,16)+" "+R.day,B=R.role==="user"?R.senderName||"User":R.senderName||"Agent";m.push(`${W} ${B}: ${R.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),Pn=m.join(`
|
|
136
136
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Ve.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let No=se?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Rn,_n,En=!1;if(No==="planner"&&!me.active&&T!=="voice"&&T!=="desktop"){try{let{planContext:g}=await import("./context-planner-JU7CNXCB.js"),m=await M("plan-context",()=>g({agentId:e.agentId,channel:T,chatId:P,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(En=!0,Rn=m.sessionHistory,In=m.memoryContext,Sn=m.memoryFacts,Mn=m.crossChatContext,_n=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}En&&U&&(this.sessions.clearClaudeSessionId(e.agentId,T,P),U=void 0)}let Ct=`${e.agentId}:${T}:${P}`,Ze=is(e.message);Ze&&(Ze==="default"?(this.activeSouls.delete(Ct),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Ct,Ze),this.log(`[${e.agentId}] Soul switched to: ${Ze}`)));let Lo=this.activeSouls.get(Ct),Fo=rs(c.def.workspace,Lo),Ho=os(Fo),jo=this.agentMemory.indexMarkdown(e.agentId),Uo=c.def.tier==="claude-code"||c.def.tier==="codex-cli"?`[Operating principle]
|
|
137
137
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",Bo=Lc(c.def.richMessages,T),Dn="";if(c.def.workspace){let g=G(c.def.workspace,"CLAUDE.md");if(ne(g))try{let m=ze(g,"utf-8");Dn=`[Project CLAUDE.md]
|
|
@@ -144,9 +144,9 @@ ${$}`),m+=$.length}catch{}}}let Wo=At.length>0?At.join(`
|
|
|
144
144
|
|
|
145
145
|
`):"",$t=[c.def.systemPrompt||"",Uo,Bo,Dn,Wo,Ho||"",jo||""].filter(g=>g.trim().length>0).join(`
|
|
146
146
|
|
|
147
|
-
`)||void 0,Mt={channel:T,chatId:P,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:St,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||wo(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:se?void 0:Ro||void 0,procedureContext:Cn,references:$n,skillInjection:vn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Rn??Ye,memoryContext:In||void 0,crossChatContext:Mn||void 0,longMemoryRecall:Pn||void 0,wikiContext:Do,handoverNote:this.buildHandoverNote(e.agentId,T,P),rotationMemo:Oo,eventDigest:U?void 0:_c(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Es(T,!U,c.def.richMessages);return g?Dc(c.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},tt=me.active&&me.preprocess?await Z("select-context",()=>Ao(Mt),()=>({input:Mt,excluded:[]})):{input:Mt,excluded:[]};tt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${tt.excluded.join(", ")}`);let nt=$r(tt.input,se?{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),qo=ms(nt,{memory:Sn,procedures:An,wikiContext:tt.input.wikiContext}),Pt=(nt?.length??0)+($t?.length??0)+(e.message?.length??0),st={history:nt?.length??0,sysPrompt:$t?.length??0,message:e.message?.length??0},On=zr(e.agentId,T,P);Xr(On,Pt,st);let Nn=Yr(On);Nn&&this.log(`[${e.agentId}] ${Nn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${P}: ${Pt} bytes (history=${st.history}, sysPrompt=${st.sysPrompt}, message=${st.message})`);let Rt,Ln=ts(c.def.tier,this.config.decisions.routing);if(!e.model&&Ln&&(!me.active||me.preprocess))try{let{routeTaskModel:g}=await import("./routing-
|
|
147
|
+
`)||void 0,Mt={channel:T,chatId:P,channelScope:e.context?.group?"group":T==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,T),systemPrompt:c.def.systemPrompt,sender:St,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||wo(T,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:se?void 0:Ro||void 0,procedureContext:Cn,references:$n,skillInjection:vn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Rn??Ye,memoryContext:In||void 0,crossChatContext:Mn||void 0,longMemoryRecall:Pn||void 0,wikiContext:Do,handoverNote:this.buildHandoverNote(e.agentId,T,P),rotationMemo:Oo,eventDigest:U?void 0:_c(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=Es(T,!U,c.def.richMessages);return g?Dc(c.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},tt=me.active&&me.preprocess?await Z("select-context",()=>Ao(Mt),()=>({input:Mt,excluded:[]})):{input:Mt,excluded:[]};tt.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${tt.excluded.join(", ")}`);let nt=$r(tt.input,se?{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),qo=ms(nt,{memory:Sn,procedures:An,wikiContext:tt.input.wikiContext}),Pt=(nt?.length??0)+($t?.length??0)+(e.message?.length??0),st={history:nt?.length??0,sysPrompt:$t?.length??0,message:e.message?.length??0},On=zr(e.agentId,T,P);Xr(On,Pt,st);let Nn=Yr(On);Nn&&this.log(`[${e.agentId}] ${Nn}`),Pt>16e3&&this.log(`[${e.agentId}] large context for ${T}:${P}: ${Pt} bytes (history=${st.history}, sysPrompt=${st.sysPrompt}, message=${st.message})`);let Rt,Ln=ts(c.def.tier,this.config.decisions.routing);if(!e.model&&Ln&&(!me.active||me.preprocess))try{let{routeTaskModel:g}=await import("./routing-HWGNYIF3.js"),m=await M("route-model",()=>g({message:e.message,agent:e.agentId,channel:T,isFollowUp:!!U,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,T,P),cheapModel:Ln}));m.downgraded&&(Rt=m.model,this.log(`[${e.agentId}] ${m.reason}`))}catch{}let Ko={...e,systemPromptAppend:$t,...Rt?{model:Rt}:{}},re,Fn=!1,Hn=po({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:c.def.maxExecutionMinutes??20}),Go=L;L=g=>{Hn.observe(g),Go?.(g)};try{let g=this.workflowAutoRunner;if(we&&g){let q=we;try{let z=await M("workflow-auto-run",()=>g({workflowId:q.workflowId,agentId:e.agentId,channel:T,chatId:P,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:T,chatId:P,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:q.workflowId,matchConfidence:q.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${we.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:we.workflowId,workflowRunId:z.runId,workflowMatchConfidence:we.confidence}},re}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(c.def.tier==="claude-code"){N("dispatch-gate");let q=c.def.persistentProcess?dt():null,z=q!=null&&q.hasLive({agentId:e.agentId,channel:T,chatId:P}),de=!!U||z,oe=[Ur(de),Jr(de)].find(Ee=>Ee&&Ee.abort);if(oe){c.errors++,this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let Ee={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let Jo of b.subscribers)try{Jo(b.buffer)}catch{}}return re=Ee,Ee}Kr();let _e=Qr();_e&&this.log(`[${e.agentId}] ${_e}`)}let m=c.def.tier==="claude-code",S=m?t:(q,z)=>{q&&I(q),t&&t(q,z)},R=!1,W=m?n:q=>{q&&(R?I(q):(I(`\u{1F4AD} ${q}`),R=!0)),n&&n(q)},B=()=>{R&&(I(`
|
|
148
148
|
`),R=!1)},te=m?S:S?(q,z)=>{B(),S(q,z)}:void 0,$=await M("agent",()=>fr(c.def,Ko,this.providers,te,nt,U,L,f.signal,W),$c);if(!$.error){let q=Oc(c.def.toolUseRequired,_);if(q){let z=Array.from(_.entries()).map(([de,rt])=>`${de}=${rt}`).join(", ")||"none";$.error=`tool_required_not_called: ${q} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${q}, observed ${z}`)}}let _t=this.interruptedRuns.get(h.id);_t&&($.content="",$.error=_t,$.errorKind="interrupted"),re=$;let ce=$.usage?Cr($.usage):void 0;if(Fn=!0,Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:T,chatId:P,durationMs:Date.now()-wn,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:_t?!0:void 0,inputTokens:ce?.inputTokens,outputTokens:ce?.outputTokens,cacheReadTokens:ce?.cacheReadTokens,cacheCreateTokens:ce?.cacheCreateTokens,tier2InputTokens:ce?.tier2InputTokens,tier2OutputTokens:ce?.tier2OutputTokens,tier2CacheReadTokens:ce?.tier2CacheReadTokens,tier2CacheCreateTokens:ce?.tier2CacheCreateTokens,resumed:!!U,resumeSessionId:U||void 0,jevArm:me.arm,numTurns:$.numTurns,injectedContext:qo,finalResponse:$.content||void 0,billedModel:$.billedModel||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let q=$.error?`[error] ${$.error}`:$.content;b.buffer=q;for(let z of b.subscribers)try{z(q)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,T,P,$.content),ho({agent:e.agentId,channel:T,chatId:P,request:e.message,reply:$.content,taskId:E}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,T,P,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,T,P,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,T,P,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,T,P,$.usage,$.contextTokens),$.usage){let oe=$.contextTokens,_e=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(oe??_e)>=this.sessions.getTierTwoThresholdTokens()&&this.log(`[${e.agentId}] TIER-2 HIT on ${T}:${P}: context=${oe??"n/a"} tokens (cumulative turn total=${_e}) \u2014 next turn will rotate`)}if(ds({channel:T,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await Tn(kc);try{let oe=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:oe,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:T,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
149
149
|
|
|
150
150
|
Agent: ${$.content}`,meta:Rc(V,e.context)})}catch{}us(e.agentId,e.message,$.content,{channel:T,chatId:P,sender:St},this.memoryStore).catch(()=>{}),Or(e.agentId,e.message,$.content,{channel:T,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,de=e.context?.channel,rt=de&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${de}:${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,z,de,rt),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${w()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=at(g.message);return re={content:"",error:ct(m),errorKind:m.kind},re}finally{if(Hn.stop(),!Fn)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:l,chatId:u,durationMs:Date.now()-h.startedAt.getTime(),error:re?.error||(f.signal.aborted?Qe(f.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,at:new Date().toISOString()})}catch{}bn(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=G(process.cwd(),Pe,this.safe(e.agentId),t);ne(n)||Ic(n,{recursive:!0});let r=G(n,`${this.safe(e.id)}.json`);vc(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=G(process.cwd(),Pe,this.safe(e));if(!ne(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let d=new Date(n).toISOString().slice(0,10),c=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[c,d]){let p=G(a,u);if(ne(p))try{for(let y of ae(p)){if(!y.endsWith(".json"))continue;let h=y.split("-")[0],k=parseInt(h,10);if(!Number.isFinite(k)||k<i||k>n)continue;let f=Math.floor((n-k)/36e5),b=t-1-f;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=G(process.cwd(),Pe);if(!ne(e))return 0;let t=0;for(let n of ae(e)){let r=G(e,n),o;try{o=ae(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=G(r,i),d;try{d=ae(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let l=JSON.parse(ze(G(a,c),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Pc){let t=G(process.cwd(),Pe);if(!ne(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=G(t,o),a;try{a=ae(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=n))try{Sc(G(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=G(process.cwd(),Pe,this.safe(e));if(!ne(n))return[];let r=ae(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=G(n,i),d;try{d=ae(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let l=JSON.parse(ze(G(a,c),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=G(process.cwd(),Pe,this.safe(e));if(!ne(n))return null;let r=this.safe(t),o=ae(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=G(n,i,`${r}.json`);if(ne(a))try{return JSON.parse(ze(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=Ms();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||Le(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>{let d=ft(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}runningIntentPath(e,t,n){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==n||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,l=o.controller.signal.aborted,u=!1;l&&c&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,d,c)),this.messageQueue.enqueue(i,a,d,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:n}});let p=this.messageQueue.pendingCount(i,a,d),y=!1;if(r.replace){let h=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(h))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${h}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:y,edited:u,pending:p}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let l=!1,u=p=>{l||(l=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>u({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Le(p.error)?u({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Lc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{Hs as a,Kc as b,Us as c,ci as d,Bs as e,ut as f,sd as g,ad as h,cd as i,pd as j,ft as k,Mi as l,pr as m,Di as n,Oi as o,Ni as p,fr as q,yt as r,bt as s,da as t,Wd as u,qd as v,sn as w,Y as x,Nr as y,wa as z,Ia as A,Hr as B,au as C,jr as D,Je as E,ac as F,cc as G,dc as H,uc as I,lc as J,un as K,Gl as L,Jl as M,Rc as N,_c as O,Ec as P,fn as Q,To as R,ko as S,Oc as T,Io as U,So as V,Lc as W};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-TNR7AI4H.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Se}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-
|
|
1
|
+
import{a as Se}from"./chunk-GTJIKXDB.js";import{a as w}from"./chunk-DWZYVYZS.js";import{q as Wt}from"./chunk-S2GAEH2F.js";import{t as jt,u as Vt}from"./chunk-7QDAGGOD.js";import{d as Ot,e as Nt}from"./chunk-AQASR6KR.js";import{c as xe,e as B,f as U,h as Ft}from"./chunk-XIYWXCNU.js";import{A as ke,b as be,v as At,x as Q,y as we}from"./chunk-KIXDJEGA.js";import{a as Pt,b as Lt,d as Mt}from"./chunk-Y4CYQV7G.js";import{a as It,b as Rt}from"./chunk-SHEUCITK.js";import{g as _t,h as Ct,i as Dt,k as Et,l as Tt}from"./chunk-BOENB3IK.js";import{q as $t}from"./chunk-HQWMWSSE.js";import{a as St,b as vt}from"./chunk-I6HCIQCQ.js";import{X as ye,ca as wt,da as kt,ga as xt,m as Z,n as gt,o as mt,p as Tr,u as yt,v as bt,w as Mr}from"./chunk-54VYZE7A.js";import{a as ht,i as Lr}from"./chunk-PN6XHTG5.js";import{a as he,h as Pr}from"./chunk-BRK6M6LA.js";import{existsSync as Or,readdirSync as Nr,readFileSync as jr,statSync as Vr}from"fs";import{resolve as Wr}from"path";function Bt(t,e,n=Date.now(),i=7){let r=i*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(g=>n-g.at<=r),l=a.filter(g=>n-g.at>r&&n-g.at<=r*2),u=c.filter(g=>g.status==="failed").length,d=a.filter(g=>g.status==="paused").length,p=a.length?Math.max(...a.map(g=>g.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ee=new Map;function ra(t,e=1e3){if(!Or(t))return[];let n=Nr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=Wr(t,s);return{path:o,mtime:Vr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),i=new Set(n.map(s=>s.path));for(let s of ee.keys())i.has(s)||ee.delete(s);let r=[];for(let{path:s,mtime:o}of n){let a=ee.get(s);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Fr(s,o);ee.set(s,{mtime:o,summary:c}),c&&r.push(c)}return r}function Fr(t,e){try{let n=jr(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let i=JSON.parse(n[0]),r=i.run?.workflowId;if(!r)return null;let s=i.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:r,status:s,at:e}}catch{return null}}var Br={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Ur=(t,e,n)=>{try{return $t(t,e,n)}catch{return null}},Ut=864e5;function aa(t){let e=t.now??Date.now(),n={...Br,...t.thresholds},i=t.nextFire??Ur,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ve(a.nextRun)??ve(i(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:Xr(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:zt(u),sampledRuns:c.length,flags:[],attention:null};p.flags=Ht(p,u,a.schedule,l,null,e,n,i),r.push(qt(p))}let s=new Map(Bt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(I=>I.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((I,me)=>me.at-I.at),f=p.map(I=>({at:I.at,status:qr(I.status)})),g=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",D=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(y,k.text),timezone:D}:{event:$(typeof l.event=="string"?l.event:"",k.text),filters:Gr(l.filter,a)},agent:Kr(a),enabled:d,state:u,nextRunAt:h&&d&&y?ve(i(y,new Date(e),D)):null,lastRun:g?{at:new Date(g.at).toISOString(),status:g.status}:null,lastSuccessAt:(()=>{let I=f.find(me=>me.status==="success");return I?new Date(I.at).toISOString():null})(),consecutiveFailures:zt(f),sampledRuns:p.length,flags:[],attention:null},Y=Date.parse(a.updated||a.created||"");N.flags=h?Ht(N,f,y,D,Number.isFinite(Y)?Y:null,e,n,i):zr(N,s.get(a.id)?.state==="dormant",Number.isFinite(Y)?Y:null,e,n),r.push(qt(N))}return r.sort(Hr).slice(0,k.routines)}function zt(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Ht(t,e,n,i,r,s,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=Gt(l,r,s,o);return p&&c.push(p),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,i),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function zr(t,e,n,i,r){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Gt(o,n,i,r);return a&&s.push(a),s}return t.consecutiveFailures>=r.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function Gt(t,e,n,i){let r=Math.max(t??0,e??0);return r&&n-r<i.disabledDays*Ut?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/Ut)} days`:"Disabled and never ran"}}function qt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Kt={critical:0,warning:1,info:2};function Hr(t,e){let n=t.attention?Kt[t.attention]:3,i=e.attention?Kt[e.attention]:3;return n-i||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function qr(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Kr(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function Gr(t,e){let n=[],i=e?.project;if(i&&n.push($(`project=${i}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function ve(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Xr(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as re,readdirSync as fi,readFileSync as gi}from"fs";import{resolve as E}from"path";import{randomBytes as Yt}from"crypto";import{existsSync as Yr,mkdirSync as Zr,readdirSync as Qr,readFileSync as ei,renameSync as Zt,unlinkSync as ti,writeFileSync as ni}from"fs";import{resolve as Qt}from"path";function Xt(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Jr=t=>t.trim().split(`
|
|
3
3
|
`).pop()?.slice(0,300)||"no output";async function Jt(t,e,n,i=Se){let r=await i(t.bin,[...Xt(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Jr(r.stderr||r.stdout)}`}}async function ua(t,e,n,i,r=Se){return(await r(t.bin,[...Xt(t),"--read-only","media","download","--chat",e,"--id",n,"--output",i],{timeoutMs:12e4})).code===0}var ri=2e3,ii=t=>Jt(t.wacli,t.to,t.text);function $e(t){return Qt(t,".agentx","whatsapp-triage","drafts")}var si=t=>/^[a-z0-9-]{8,64}$/.test(t),te=(t,e)=>Qt($e(t),`${e}.json`);function en(t,e){Zr($e(t),{recursive:!0});let n=te(t,e.id),i=`${n}.${process.pid}.tmp`;ni(i,JSON.stringify(e,null,2)+`
|
|
4
4
|
`,{mode:384}),Zt(i,n)}function ha(t,e,n=Date.now()){let i=e.text.trim().slice(0,ri);if(!i)throw new Error("empty draft");let r={...e,text:i,id:`${n.toString(36)}-${Yt(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return en(t,r),r}function ne(t,e){if(!si(e))return null;try{return JSON.parse(ei(te(t,e),"utf-8"))}catch{return null}}function tn(t,e){let n=$e(t);return Yr(n)?Qr(n).filter(i=>i.endsWith(".json")).map(i=>ne(t,i.slice(0,-5))).filter(i=>!!i&&(!e||i.status===e)).sort((i,r)=>i.created_at.localeCompare(r.created_at)):[]}async function nn(t,e,n,i={}){let r=ne(t,e);if(!r||r.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${te(t,e)}.${process.pid}.${Yt(3).toString("hex")}.claim`;try{Zt(te(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...r,decided_by:i.by??"operator",decided_at:new Date(i.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(i.send??ii)(r).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}en(t,o);try{ti(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as oi,readFileSync as ai,renameSync as ci,writeFileSync as li}from"fs";import{resolve as ui}from"path";function rn(t){return ui(xe(t),"_state.json")}function R(t){try{let e=JSON.parse(ai(rn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function z(t,e){oi(xe(t),{recursive:!0});let n=rn(t),i=`${n}.${process.pid}.tmp`;li(i,JSON.stringify(e,null,2)+`
|
|
@@ -477,4 +477,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
477
477
|
claude-code ${ft(t)} --arg value
|
|
478
478
|
\`\`\`
|
|
479
479
|
`}xt();var _r={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Cr(t){return{..._r,...t??{},regions:{...t?.regions??{}},buffer:{..._r.buffer,...t?.buffer??{}}}}function hu(t){try{return Cr(kt(t).screen)}catch{return Cr(void 0)}}var ea=/^[a-z][\w-]*$/,Dr=["window","screen","menubar","notifications"];function J(t,e,n,i){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${i}`);return r}var ge=(t,e)=>J(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Er(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function yu(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=ge(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=ge(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=ge(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=J(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=J(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!ea.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete r[s]:r[s]=Er(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,s={...n.buffer??{}};"enabled"in r&&(s.enabled=!!r.enabled),"seconds"in r&&(s.seconds=J(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(s.fps=J(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(s.maxPixels=ge(r.maxPixels,"buffer.maxPixels")),"region"in r&&(s.region=String(r.region).trim()),n.buffer=s}let i=n.buffer?.region;if(i!==void 0&&!Dr.includes(i)&&!n.regions?.[i])try{Er(i)}catch{throw new Error(`buffer.region "${i}" is not a region \u2014 use ${[...Dr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Bt as a,ra as b,Je as c,Cs as d,Ds as e,Nc as f,jc as g,Vc as h,Gn as i,Fc as j,Uc as k,T as l,Xn as m,k as n,aa as o,ua as p,ii as q,ha as r,nn as s,R as t,xa as u,Sa as v,cn as w,_a as x,pn as y,Ba as z,gn as A,cr as B,ml as C,hl as D,Sl as E,yo as F,vl as G,za as H,Ha as I,qa as J,Ka as K,Ga as L,Xa as M,Ya as N,Za as O,ac as P,Te as Q,cc as R,lc as S,H as T,q as U,vo as V,Tl as W,Pl as X,Ll as Y,Ml as Z,tt as _,Ol as $,Me as aa,Oe as ba,le as ca,Xi as da,Yi as ea,gc as fa,je as ga,Ve as ha,Zi as ia,Qi as ja,Ln as ka,jn as la,mc as ma,ns as na,hc as oa,us as pa,fs as qa,We as ra,ms as sa,Vn as ta,P as ua,yr as va,br as wa,wr as xa,Bl as ya,To as za,xr as Aa,Sr as Ba,Ql as Ca,eu as Da,Go as Ea,tu as Fa,$r as Ga,ue as Ha,_c as Ia,Hn as Ja,Fe as Ka,Ge as La,Mc as Ma,su as Na,ou as Oa,au as Pa,cu as Qa,lu as Ra,uu as Sa,du as Ta,pu as Ua,fu as Va,_r as Wa,Cr as Xa,hu as Ya,Dr as Za,yu as _a};
|
|
480
|
-
//# sourceMappingURL=chunk-
|
|
480
|
+
//# sourceMappingURL=chunk-X2F3AVGR.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-4DWWYWDR.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-XVDASTUX.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-VX4XZAE6.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-7K5SJJUI.js";import"./chunk-54VYZE7A.js";import"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-UKLOVDZB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{$ as i,T as a,U as b,V as c,W as d,X as e,Y as f,Z as g,_ as h,aa as j,ba as k,ca as l,da as m,ea as n,ga as o}from"./chunk-54VYZE7A.js";import"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";o();export{a as INTEGRATION_KINDS,j as approvalsConfigSchema,d as callsSchema,c as cameraBotSchema,k as daemonConfigSchema,b as eventSubscriptionSchema,l as expandEnvVars,m as loadDaemonConfig,h as membersConfigSchema,g as peopleConfigSchema,f as personSchema,i as requestStatusConfigSchema,e as requestsConfigSchema,n as validateWorkspaces};
|
|
2
|
+
//# sourceMappingURL=config-WUDWHRT6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-I6HCIQCQ.js";import"./chunk-54VYZE7A.js";import"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-UPLM7KGO.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e}from"./chunk-EUXF2GJY.js";import"./chunk-S2GAEH2F.js";import"./chunk-JXF54PT7.js";import"./chunk-54VYZE7A.js";import"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{e as daemonVoiceCheck,b as doctor,a as runDoctorChecks,c as runNotificationChecks,d as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-COAIIKLV.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as St,b as kt,c as vt,ca as Tt,d as xt,da as Mt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{a as St,b as kt,c as vt,ca as Tt,d as xt,da as Mt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-L6BO76GK.js";import"./chunk-X2F3AVGR.js";import"./chunk-GTJIKXDB.js";import"./chunk-C3VCIEZS.js";import"./chunk-DWZYVYZS.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-7QDAGGOD.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-ACFQBLPX.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-4L244AW4.js";import"./chunk-XIYWXCNU.js";import"./chunk-PPUN7YHA.js";import{V as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-TNR7AI4H.js";import"./chunk-KIXDJEGA.js";import"./chunk-GLQLCBJS.js";import"./chunk-DP7RTNDM.js";import{a as L}from"./chunk-C245D4BZ.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-XVDASTUX.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-BOENB3IK.js";import"./chunk-SZDACK6O.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-HQWMWSSE.js";import"./chunk-I6HCIQCQ.js";import"./chunk-VWTBHLMX.js";import"./chunk-N4HFUAPN.js";import{a as ht}from"./chunk-7OEFPYQJ.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-2FLVU2QW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-DWADWDMU.js";import"./chunk-23A5K5UW.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import"./chunk-7ADEEHZQ.js";import{f as gt,g as ft}from"./chunk-HOXHUFZB.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import{j as it,k as rt,l as at}from"./chunk-ECCPLASB.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-5MUJZODV.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ba as tt,da as st,ea as ot,ga as nt}from"./chunk-54VYZE7A.js";import"./chunk-PN6XHTG5.js";import"./chunk-BRK6M6LA.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|