agentix-cli 0.118.1 → 0.120.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/{agent-E6W5VBYH.js → agent-63RXZRL2.js} +2 -2
- package/dist/{board-dashboard-WDO6Z24C.js → board-dashboard-XQEZBQL5.js} +2 -2
- package/dist/{chunk-PVQPXZHE.js → chunk-247SOQLP.js} +4 -4
- package/dist/chunk-56KNKUFF.js +3 -0
- package/dist/chunk-56KNKUFF.js.map +1 -0
- package/dist/chunk-6FVFD5WU.js +4 -0
- package/dist/chunk-6FVFD5WU.js.map +1 -0
- package/dist/{chunk-IVCFXLAR.js → chunk-6JJJ5MUU.js} +5 -5
- package/dist/chunk-6JJJ5MUU.js.map +1 -0
- package/dist/{chunk-TJ7IUHC7.js → chunk-7ZABMMSW.js} +2 -2
- package/dist/{chunk-GJKYOEDE.js → chunk-AXFE34OV.js} +2 -2
- package/dist/{chunk-ZDWE47LM.js → chunk-KQX3U3H2.js} +2 -2
- package/dist/{chunk-UQ3MWTGF.js → chunk-PCOXSCYT.js} +180 -180
- package/dist/{chunk-UQ3MWTGF.js.map → chunk-PCOXSCYT.js.map} +1 -1
- package/dist/{chunk-5PR6DZYW.js → chunk-S6NQB7VV.js} +2 -2
- package/dist/{chunk-5UFIHT66.js → chunk-UAPWOE2W.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{grants-V2ZNLWSJ.js → grants-ZMHSJMYE.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-GHQQAEVB.js → program-E3NTPNCZ.js} +222 -210
- package/dist/program-E3NTPNCZ.js.map +1 -0
- package/dist/{query-NAU7J34H.js → query-R6YELRQN.js} +2 -2
- package/dist/{registry-I5PXGCO6.js → registry-HIZIFAVH.js} +2 -2
- package/dist/{review-candidates-HAP7P6SH.js → review-candidates-6YIBOEEG.js} +2 -2
- package/dist/{rotation-memo-5MTSJ4FH.js → rotation-memo-6UW6DTBQ.js} +2 -2
- package/dist/{rotation-memo-5MTSJ4FH.js.map → rotation-memo-6UW6DTBQ.js.map} +1 -1
- package/dist/{wiki-PPX3HYXW.js → wiki-R4MNLBXE.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-2GIDVZ4H.js +0 -3
- package/dist/chunk-2GIDVZ4H.js.map +0 -1
- package/dist/chunk-BDJWN3PL.js +0 -4
- package/dist/chunk-BDJWN3PL.js.map +0 -1
- package/dist/chunk-IVCFXLAR.js.map +0 -1
- package/dist/program-GHQQAEVB.js.map +0 -1
- /package/dist/{agent-E6W5VBYH.js.map → agent-63RXZRL2.js.map} +0 -0
- /package/dist/{board-dashboard-WDO6Z24C.js.map → board-dashboard-XQEZBQL5.js.map} +0 -0
- /package/dist/{chunk-PVQPXZHE.js.map → chunk-247SOQLP.js.map} +0 -0
- /package/dist/{chunk-TJ7IUHC7.js.map → chunk-7ZABMMSW.js.map} +0 -0
- /package/dist/{chunk-GJKYOEDE.js.map → chunk-AXFE34OV.js.map} +0 -0
- /package/dist/{chunk-ZDWE47LM.js.map → chunk-KQX3U3H2.js.map} +0 -0
- /package/dist/{chunk-5PR6DZYW.js.map → chunk-S6NQB7VV.js.map} +0 -0
- /package/dist/{chunk-5UFIHT66.js.map → chunk-UAPWOE2W.js.map} +0 -0
- /package/dist/{grants-V2ZNLWSJ.js.map → grants-ZMHSJMYE.js.map} +0 -0
- /package/dist/{query-NAU7J34H.js.map → query-R6YELRQN.js.map} +0 -0
- /package/dist/{registry-I5PXGCO6.js.map → registry-HIZIFAVH.js.map} +0 -0
- /package/dist/{review-candidates-HAP7P6SH.js.map → review-candidates-6YIBOEEG.js.map} +0 -0
- /package/dist/{wiki-PPX3HYXW.js.map → wiki-R4MNLBXE.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as a,B as b,C as c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=agent-
|
|
1
|
+
import{A as a,B as b,C as c}from"./chunk-AXFE34OV.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
|
|
2
|
+
//# sourceMappingURL=agent-63RXZRL2.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Yr,B as Qr,C as Zr,a as C,b as Or,c as Nr,d as Dr,e as Br,f as Ae,g as Hr,h as zr,i as jt,k as qr,q as Fr,r as Ur,s as Wr,t as Gr,u as Xr,y as Kr,z as Jr}from"./chunk-
|
|
1
|
+
import{A as Yr,B as Qr,C as Zr,a as C,b as Or,c as Nr,d as Dr,e as Br,f as Ae,g as Hr,h as zr,i as jt,k as qr,q as Fr,r as Ur,s as Wr,t as Gr,u as Xr,y as Kr,z as Jr}from"./chunk-UAPWOE2W.js";import{a as Vr}from"./chunk-5NTWGUSJ.js";import{a as Lr}from"./chunk-LNY6N73E.js";import{a as jr}from"./chunk-4VDA4UM7.js";import{a as ze,b as q,c as I,h as de,i as Pt,j as oe,k as K,l as $t,m as Rr,n as Pr,o as $r}from"./chunk-SCJ5ZXEN.js";import{A as Tt,B as At,C as cr,D as pr,G as ur,H as mr,Ha as Sr,I as fr,Ja as Te,Oa as Er,P as U,Q as hr,Qa as He,R as gr,Ra as Ct,Sa as It,Ta as Mt,Ua as Lt,Va as Tr,Wa as Ar,Xa as Cr,Ya as Rt,_a as Ir,a as Vn,bb as Mr,c as bt,d as ya,e as Yn,i as vt,l as Qe,n as Qn,va as yr,w as _t,x as lr,xa as wr,y as St,ya as kr,z as Et,za as _r}from"./chunk-S6NQB7VV.js";import"./chunk-GTJIKXDB.js";import{h as Kn,i as Jn}from"./chunk-KQX3U3H2.js";import{p as Zn,t as er}from"./chunk-S2GAEH2F.js";import{a as dr,b as B,c as xr,d as br,h as vr}from"./chunk-BGG3ZSMW.js";import{a as nr,b as yt,d as rr,e as or,f as wt}from"./chunk-WCXXXAHV.js";import{g as kt}from"./chunk-LQE73AZR.js";import{b as sr,c as ir}from"./chunk-2D3RYIDU.js";import"./chunk-6FVFD5WU.js";import"./chunk-FSXWNVGL.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{b as G,c as Ee,d as tr,e as wa}from"./chunk-EMGB23H5.js";import{b as ar}from"./chunk-JWDJMFU6.js";import{a as zn,f as qn,g as ba,h as va,l as Fn,m as Un,n as Wn,u as ht,v as gt,w as xt,x as ce,y as Xn}from"./chunk-RJBRYUKU.js";import"./chunk-GLQLCBJS.js";import"./chunk-6W74CHNW.js";import"./chunk-Y4CYQV7G.js";import"./chunk-SHEUCITK.js";import"./chunk-IOYRRGK7.js";import"./chunk-GV7S5BAX.js";import"./chunk-SZDACK6O.js";import"./chunk-AFRHKA7B.js";import"./chunk-B6OXEIOF.js";import{a as Gn}from"./chunk-4PQREYBU.js";import"./chunk-23SQSUBI.js";import"./chunk-HK7TU5NX.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-GSX4NK2N.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{g as Hn}from"./chunk-FTZCNID3.js";import"./chunk-WPNRDEHW.js";import"./chunk-56KNKUFF.js";import"./chunk-NDPU6AX2.js";import"./chunk-72SZI2UW.js";import"./chunk-FX3D7YON.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import{A as Kc,H as jn,K as ga,N as On,P as mt,Q as Nn,S as Dn,U as Bn,Y as xa,a as Cn,b as In,c as Wc,ja as X,ma as ft,u as dt,v as Gc,w as fa,x as ha}from"./chunk-IMLLHT7U.js";import{a as Mn,b as pt,c as ma,d as Ln,h as Rn}from"./chunk-BRK6M6LA.js";import{d as Pn,e as Xc,f as ut,n as $n}from"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function ka(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function eo(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:ka(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var se={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},Ce=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",Ot=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+Ce(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function to(t={}){return I({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
|
|
2
2
|
|
|
3
3
|
<div class="bf-head">
|
|
4
4
|
<div>
|
|
@@ -20511,4 +20511,4 @@ data: ${f.replace(/\n/g," ")}
|
|
|
20511
20511
|
`)}catch{}}};s.stdout?.on("data",l),s.stderr?.on("data",l);let c=setInterval(()=>{try{e.write(`: hb
|
|
20512
20512
|
|
|
20513
20513
|
`)}catch{}},15e3),d=()=>{clearInterval(c);try{s.kill()}catch{}try{e.end()}catch{}};t.on("close",d),s.on("exit",d),s.on("error",d)}async function jc(t,e,a,n){let r=a.url+n,o=(t.method||"GET").toUpperCase(),i=o!=="GET"&&o!=="HEAD"?await new Promise((p,m)=>{let f=[];t.on("data",_=>f.push(_)),t.on("end",()=>p(Buffer.concat(f))),t.on("error",m)}):void 0,l={},c=t.headers["content-type"];c&&(l["Content-Type"]=Array.isArray(c)?c[0]:c);let d=t.headers["x-requested-with"];d&&(l["X-Requested-With"]=Array.isArray(d)?d[0]:d),a.token&&(l.Authorization=`Bearer ${a.token}`),l["X-Agentx-Peer"]="primary";try{let p=await fetch(r,{method:o,headers:l,body:i&&i.length>0?i:void 0}),m=Buffer.from(await p.arrayBuffer());e.writeHead(p.status,{"Content-Type":p.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),e.end(m)}catch(p){k(e,502,{error:`proxy to peer failed: ${p?.message||p}`,target:r})}}function lt(t,e){let a=t.replace(/\/+$/,""),n=(e.dashboard?.daemons||[]).find(r=>r.url.replace(/\/+$/,"")===a);return n?{url:Hc(n),token:n.dashboardToken||n.token}:null}export{jh as applyAttachSessions,Ch as fetchDaemonAgents,kh as handleBoardRequest,I0 as resetLiveCaches,Se as resolveNodeTargets,C0 as startBoardDashboard,$h as withLastGood};
|
|
20514
|
-
//# sourceMappingURL=board-dashboard-
|
|
20514
|
+
//# sourceMappingURL=board-dashboard-XQEZBQL5.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as tr,a as Ns,b as Ls,d as Hs,f as He,l as Ys,s as Vs,u as Zs,z as er}from"./chunk-RJBRYUKU.js";import{a as Os}from"./chunk-GLQLCBJS.js";import{b as Fs}from"./chunk-6W74CHNW.js";import{a as Xs}from"./chunk-W4YR2RO2.js";import{b as js,c as Vt,d as Ws,e as qs,h as Gs}from"./chunk-B6OXEIOF.js";import{a as Rs}from"./chunk-23SQSUBI.js";import{e as Es,f as Ds}from"./chunk-36AXN6ZB.js";import{a as Xt,b as Bs}from"./chunk-J3SOEFRE.js";import{a as Yt,b as Us}from"./chunk-SIU6STB2.js";import{e as Ks,i as Js,j as Qs,k as zs}from"./chunk-X5C5W3E4.js";import{c as bs,f as xs}from"./chunk-2G227TF3.js";import{a as Ss,c as Is}from"./chunk-MYVHVJWZ.js";import{a as Ts,b as vs,c as ks,d as As,l as $s}from"./chunk-AV7T3SYT.js";import{a as Cs,b as Ms}from"./chunk-Y5MFVVTM.js";import{g as Ps,h as _s}from"./chunk-FTZCNID3.js";import{a as ve,
|
|
1
|
+
import{B as tr,a as Ns,b as Ls,d as Hs,f as He,l as Ys,s as Vs,u as Zs,z as er}from"./chunk-RJBRYUKU.js";import{a as Os}from"./chunk-GLQLCBJS.js";import{b as Fs}from"./chunk-6W74CHNW.js";import{a as Xs}from"./chunk-W4YR2RO2.js";import{b as js,c as Vt,d as Ws,e as qs,h as Gs}from"./chunk-B6OXEIOF.js";import{a as Rs}from"./chunk-23SQSUBI.js";import{e as Es,f as Ds}from"./chunk-36AXN6ZB.js";import{a as Xt,b as Bs}from"./chunk-J3SOEFRE.js";import{a as Yt,b as Us}from"./chunk-SIU6STB2.js";import{e as Ks,i as Js,j as Qs,k as zs}from"./chunk-X5C5W3E4.js";import{c as bs,f as xs}from"./chunk-2G227TF3.js";import{a as Ss,c as Is}from"./chunk-MYVHVJWZ.js";import{a as Ts,b as vs,c as ks,d as As,l as $s}from"./chunk-AV7T3SYT.js";import{a as Cs,b as Ms}from"./chunk-Y5MFVVTM.js";import{g as Ps,h as _s}from"./chunk-FTZCNID3.js";import{a as ve,d as ye}from"./chunk-56KNKUFF.js";import{s as ys,v as lt,w as ws,y as ue,z as zt}from"./chunk-NDPU6AX2.js";import{a as Fe,b as Te,f as ut}from"./chunk-72SZI2UW.js";import{a as Ie,b as Wt}from"./chunk-FCPTN6NF.js";import{c as os,d as is}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{C as us,E as Jt,G as Yi,J as ls,N as Vi,T as gs,U as Qt,V as ps,W as Le,X as fs,Y as ms,_ as hs,ma as Zi}from"./chunk-IMLLHT7U.js";import{g as Gt,h as zi}from"./chunk-BRK6M6LA.js";import{f as Kt,n as Xi}from"./chunk-UIBUZ2N3.js";import{a as as,b as ie,c as ds,d as cs,e as qt}from"./chunk-2QNT5JDS.js";zt();ut();var gt="tool-set",nr=["answer","code","full"],sr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ea=.1;function or(n){return{task:rr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:rr(n.agentPrompt,600)}:{}}}var ir={bundle:Te({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function ar(n,e=ea){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Zt(s.answer),o=Zt(s.code),i=Zt(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>sr.answer.includes(t))?"answer":e.every(t=>sr.code.includes(t))?"code":"full"}function cr(n,e){return nr.indexOf(n)<nr.indexOf(e)}function Zt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function rr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ur=!1;function lr(n,e){let t=lt(gt);if(t!=="off")return t==="active"&&!ur&&(ur=!0,e(`[decisions] seat "${gt}" is set to active, but only shadow is built: it records and changes nothing`)),ue(gt,or(n),ir,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=ar(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function gr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=dr(r);ws(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(cr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}zt();ut();var pr="session-continuity",fr={continues:Fe("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:Fe("Does the new request refer to something stated earlier in the conversation?")};function mr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:en(n.message,1200),previousRequest:n.previousMessage?en(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>en(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function hr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function en(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as St}from"execa";import{spawn as ta}from"node:child_process";import{createHash as na}from"node:crypto";import{createInterface as sa}from"node:readline";var le=class extends Error{},ra=n=>ta("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),tn=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(),sa({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},nn=class{constructor(e=ra,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=na("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[R])=>b.localeCompare(R))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new le("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,R])=>!R.connection.busy);if(!b)throw new le("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:s,connection:new tn(e,this.launchProcess)}}catch{throw new le("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,f,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let I=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 b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let E=new Promise((O,P)=>{i.failTurn=P,i.notify=(D,N)=>{if(N?.threadId!==u)return;let L=N.item,U={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:D.replace("/","."),...L?{item:{...L,type:U[L.type]||L.type}}:{}}),D==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=N.delta,e.onDelta?.(N.delta,c)),D==="thread/tokenUsage/updated"){let H=N.tokenUsage.last;f=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(N.turn.status==="completed"?O():P(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return E.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await E,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:f,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new le(b.message);return{content:c,codexSessionId:u,usage:l,contextTokens:f,error:b.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(I),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},yr=new nn;import{execFile as ka}from"child_process";import{StringDecoder as qe}from"string_decoder";import{mkdtempSync as Or,readFileSync as Nr,rmSync as Lr}from"fs";import{join as bt}from"path";import{tmpdir as Fr}from"os";function pt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ft(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function mt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var wr=null;function ht(){return wr}function Lu(n){wr=n}function Be(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function oa(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var ke=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},br=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Be(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=oa(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new 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(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Be(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Be(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Be(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Be(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as ia}from"child_process";import{randomUUID as aa}from"crypto";import{existsSync as da,readFileSync as ca}from"fs";import{resolve as ua}from"path";function la(n){let e=ua(n,"CLAUDE.md");if(!da(e))return null;try{let t=ca(e,"utf8");return $s(t)}catch{return null}}var ga=20*60*1e3,pa=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function fa(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var xr=class{constructor(e={}){this.opts=e}spawn(e,t){return new sn(e,t,this.opts)}},sn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=ia(r,o,{cwd:t.workspace,env:ye(fa({...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:la(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=aa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??ga,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new je(c)),l=!1,f=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ue(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(p.type==="user"&&p.uuid===i)l=!0,f&&(yield{type:f.type,raw:f});else if(p.type==="system"&&p.subtype==="init")f=p;else if(p.type==="result"){f=null;let I=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${I.length} chars): ${I.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},pa);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};qt();Xi();Wt();import{resolve as Sr,join as Ir}from"path";var ma=4e3;function yt(n){try{let e=Ir(Sr(n.root),".agentx","db.sqlite"),t=Kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ie(),r=n.input.command?n.input.command.slice(0,ma):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${n}`}function $a(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
27
27
|
`,l)}};O.stdout?.on("data",T=>{L+=H.write(T);let w=L.split(`
|
|
28
28
|
`);L=w.pop()||"";for(let _ of w)G(_)}),O.stderr?.on("data",T=>{U+=q.write(T)});let $=await O;if(i&&i.removeEventListener("abort",N),L+=H.end(),L.trim()&&G(L),U+=q.end(),P)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,w;return T.timedOut?w=`OpenCode timed out after ${Math.round(R/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?w=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+U)?w=Rr():w=U.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...X(w),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return k=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(R){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(R?.message||"")?Rr():R?.message;return{content:l,...X(E||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{b?.(),I?.release(k)}}async function Fa(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=pe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...X(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ha(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let k=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(k))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let I=()=>({content:"",...X(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let k=n.provider||"claude-code",b=s?`${s}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=As(n),D=Object.keys(P).length>0,N={task:b,cwd:n.workspace,provider:k,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=As(n),D=Object.keys(P).length>0,N={task:b,cwd:n.workspace,provider:k,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-63RXZRL2.js"),$="",T,w,_,x;for await(let v of G(N)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let K=v.result.content.slice($.length);K?($=v.result.content,r(K,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let K=v.result.content.slice($.length);K?($=v.result.content,r(K,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(x=v.error)}return x&&!$?f?I():x==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${x}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-63RXZRL2.js"),U=await L(N),H=U.inputTokens,q=U.outputTokens;if((H===void 0||q===void 0)&&U.tokensUsed){let G=U.tokensUsed;H=Math.round(G*.7),q=G-H}return{content:U.content||"Done.",tokensUsed:U.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(k){return f?I():k?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${k.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ba=1e3;async function ja(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Ba),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ua(n,e,t,s,r,o,i){let a=ht();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Tt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof ke,null}h&&cn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",k,b,R,E,O,P,D,N="",L="",U=$=>{if(!i||!$)return;let T;if(L&&$.startsWith(L)?T=$.slice(L.length):T=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${$}`:$,L=$,!!T){N+=T;try{i(T,N)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let G=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(G=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let w=T.raw.message?.content??[];for(let x of w)x.type==="text"&&typeof x.text=="string"?(I=x.text,U(x.text)):x.type==="tool_use"&&(L="");let _=T.raw.message?.usage;if(_){let x=(_.input_tokens||0)+(_.cache_read_input_tokens||0)+(_.cache_creation_input_tokens||0);x>0&&(E=x)}}if(T.type==="result"){let w=T.raw;if(w.is_error){let _=X(typeof w.result=="string"?w.result:"claude error");k=_.error,b=_.errorKind}else typeof w.result=="string"&&w.result.length>0&&(I=w.result,N||U(w.result));typeof w.session_id=="string"&&(D=w.session_id),w.usage&&(R={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"&&(O=w.num_turns),typeof w.message?.model=="string"?P=w.message.model:typeof w.model=="string"?P=w.model:P=mt(w.modelUsage)||P}}}catch($){if(H)k="task cancelled by operator",b="cancelled";else if(G)if($ instanceof Ue)k=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,b="interrupted";else if($ instanceof je){let T=X(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);k=T.error,b=T.errorKind}else{let T=X(`persistent claude process error: ${$?.message||String($)}`);k=T.error,b=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return H&&!k&&(k="task cancelled by operator",b="cancelled"),{content:H?"":I,error:k,errorKind:b,duration:Date.now()-c,usage:R,contextTokens:E,numTurns:O,billedModel:P,claudeSessionId:D}}function Jr(n){let e=ie(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?kr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Pr(t.args,n.taskId,n.agentId)}function Wa(n){return ie(n.autonomy)||!!n.personLimits}async function qa(n,e,t,s,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,c=a&&Ar(a,n.tier)||e.personLimits&&_r(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${cs(a)}
|
|
@@ -130,7 +130,7 @@ ${lu}`:n==="codex-cli"?yi:""}function wi(n,e){return e!=="claude-code"&&e!=="cod
|
|
|
130
130
|
\u2192 ${i}(${a})
|
|
131
131
|
`}return r}if(s==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Ve(i,800)}
|
|
132
132
|
`}return r}return s==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
133
|
-
`:""}}var Ti=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Fs;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Ns;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;cloudSessions;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new vt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new Rs(void 0,void 0,"graph"),this.memoryStore=new Ls,this.patternStore=new $t,this.rateLimiter=new kt,this.tokenTracker=new Ds,this.messageQueue=new At,wo({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Ps({baseDir:J(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new _s({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=ps(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Zs(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let f=this.sessions.getSession(e.agentId,s,r);i=Vr(f.messages,e.message??""),c=Zr(f.messages,e.message??"",this.config.session.continuityStateTurns),f.updatedAt&&(a=Math.round((Date.now()-Date.parse(f.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await ue(pr,mr(d),fr,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!hr(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),Y().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-
|
|
133
|
+
`:""}}var Ti=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Fs;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new Ns;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;interruptedRuns=new Map;cloudSessions;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new vt(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens,tierTwoThresholdTokensByChannel:e.session.tierTwoThresholdTokensByChannel}),this.wikiHub=new Rs(void 0,void 0,"graph"),this.memoryStore=new Ls,this.patternStore=new $t,this.rateLimiter=new kt,this.tokenTracker=new Ds,this.messageQueue=new At,wo({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new Ps({baseDir:J(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let s=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new _s({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:s,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[s,r]of Object.entries(e.agents))this.agents.set(s,{id:s,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}setPeople(e){this.config={...this.config,people:e}}refusalFor(e,t){let s=ps(this.config.people,e,t);return s?(this.log(`[${e}] refused: ${s.person.id} may not reach this agent (people[].agents)`),this.memberTrail().log({person:s.person.id,event:"agent-refused",detail:e}),s.note):null}logToolRefusal(e,t,s){this.log(`[${t??"?"}] blocked for ${e}: ${s} (people[].deny)`),this.memberTrail().log({person:e,event:"tool-refused",detail:s})}memberTrail(){let e=this.config.members.logRetentionDays;return(!this.memberLog||this.memberLog.days!==e)&&(this.memberLog={days:e,store:new Zs(process.cwd(),Date.now,e)}),this.memberLog.store}memberLog;buildHandoverNote(e,t,s){let r=this.handoverStore.get(t,s);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,s);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();s.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){s.push(r);break}return s}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,s,r,o){let i=null,a=null,c=[];try{let f=this.sessions.getSession(e.agentId,s,r);i=Vr(f.messages,e.message??""),c=Zr(f.messages,e.message??"",this.config.session.continuityStateTurns),f.updatedAt&&(a=Math.round((Date.now()-Date.parse(f.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,s,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,s,r)||null,agentId:e.agentId,channel:s},u=await ue(pr,mr(d),fr,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${s}:${r}`}],features:{agent:e.agentId,channel:s},timeoutMs:1500});return!u||u.mode!=="active"||!hr(u.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${s}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,s,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,s,r),Y().emit("session:rotated",{agentId:e.agentId,channel:s,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,s,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-6UW6DTBQ.js"),c=await a(t,s);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-A4YW6FSK.js"),u=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});u.error&&this.log(`[${e}] memo claims not proposed: ${u.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${u.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let s=[];for(let[r,o]of this.agents)r!==e&&s.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
134
134
|
`)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Rt(J(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Et,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=Cn(t.context?.chatId),a=this.cloudSessionStore();return pi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Et,...e.cloudSessions??{}},i=Date.now(),a=ye(Ge(ve(e.workspace),t),e.billing),c=await hi({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>mi({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Y().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(d){i={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(c){let d=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=i.error?He(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";js().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=ie(e.autonomy),a=fs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:fo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let g=await c;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 d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let 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:u,chatId:l}=Tt(e.context),f;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let g=Date.now(),m=25*6e4,S=500;for(;d.activeTasks>=d.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(M=>setTimeout(M,S))}}else if(u==="voice"){let g=Date.now(),m=25*6e4,S=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||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(M=>setTimeout(M,500))}f=S,this.voiceClaims.add(S)}else{let g=d.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,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,u,l);return Y().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Jt(e.context),humanRoot:Gt(e.context),person:Qt(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${d.runningTasks.map(M=>M.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Hs(m,S)}}}let h=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(f&&this.voiceClaims.delete(f),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.queuedAt!==void 0){let g=ro(e.queuedAt);g&&(e.message=`${g}
|
|
135
135
|
${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};d.runningTasks.push(p),e.runningTaskId=p.id;let I=Qt(this.config.people,e.context);if(e.context&&(I?e.context.person=I.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let k=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:k});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let R=g=>{if(g){b.buffer+=g,b.buffer.length>bi&&(b.buffer=b.buffer.slice(b.buffer.length-bi));for(let m of b.subscribers)try{m(g)}catch{}}},E=Ie();e.taskId=E;let O=new Map,P=(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{}},D=0,N=!1,L=()=>{N||(N=!0,D&&P("first-event",D,"ok"))},U;if(t){let g=Iu();U=m=>{L();let S=g(m);if(S&&R(S),Ii(E,e.agentId,m),Si(O,m),wn(m,void 0,e.model||d.def.model),r)try{r(m)}catch{}}}else U=g=>{if(L(),Ii(E,e.agentId,g),Si(O,g),wn(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,q=H?setTimeout(()=>k.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;q?.unref?.();let G=(d.def.preSpawnTimeoutSec??mu)*1e3,$=setTimeout(()=>{k.abort(new Error(`timed out before spawn after ${Math.round(G/1e3)}s in step "${p.step??"start"}"`))},G);$.unref?.();let T=()=>{$&&clearTimeout($),$=void 0},w=()=>`task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`,_;k.signal.addEventListener("abort",()=>{let g=Xe(k.signal).message;/^timed out/.test(g)&&(_=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let x=g=>{p.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},v=(g,m,S=0)=>{if(k.signal.aborted)return Promise.reject(Xe(k.signal));x(g),(g==="agent"||g==="workflow-auto-run")&&(T(),D=Date.now());let M=Date.now(),W=gi(m(),uu[g]??0,g);return li(W,k.signal,S).then(j=>(P(g,M,"ok"),j),j=>{throw P(g,M,"error"),j instanceof _e&&this.log(`[${e.agentId}] ${j.message}; continuing without it ${w()}`),j})},K=async(g,m,S,M=0)=>{try{return await v(g,m,M)}catch(W){if(W instanceof _e)return S();throw W}},Pn=!1,_n=g=>{if(Pn)return;Pn=!0,this.runReleases.delete(p.id),q&&clearTimeout(q),T(),d.activeTasks--;let m=d.runningTasks.findIndex(S=>S.id===p.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
136
136
|
[task finished]
|
|
@@ -151,4 +151,4 @@ ${te}`),m+=te.length}catch{}}}let Wi=Ft.length>0?Ft.join(`
|
|
|
151
151
|
|
|
152
152
|
Agent: ${C.content}`,meta:yu(V,e.context)})}catch{}Ms(e.agentId,e.message,C.content,{channel:y,chatId:A,sender:Ot},this.memoryStore).catch(()=>{}),co(e.agentId,e.message,C.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||d.def.model,ce=e.context?.channel,dt=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,Q,ce,dt),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${w()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=pt(g.message);return re={content:"",error:ft(m),errorKind:m.kind},re}finally{if(rs.stop(),!ss)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:re?.error||(k.signal.aborted?Xe(k.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,at:new Date().toISOString()})}catch{}_n(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),s=J(process.cwd(),Re,this.safe(e.agentId),t);ne(s)||au(s,{recursive:!0});let r=J(s,`${this.safe(e.id)}.json`);cu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=J(process.cwd(),Re,this.safe(e));if(!ne(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let f=J(a,l);if(ne(f))try{for(let h of ae(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],I=parseInt(p,10);if(!Number.isFinite(I)||I<i||I>s)continue;let k=Math.floor((s-I)/36e5),b=t-1-k;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=J(process.cwd(),Re);if(!ne(e))return 0;let t=0;for(let s of ae(e)){let r=J(e,s),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=J(r,i),c;try{c=ae(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ye(J(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hu){let t=J(process.cwd(),Re);if(!ne(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=J(t,o),a;try{a=ae(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{du(J(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=J(process.cwd(),Re,this.safe(e));if(!ne(s))return[];let r=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=J(s,i),c;try{c=ae(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Ye(J(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=J(process.cwd(),Re,this.safe(e));if(!ne(s))return null;let r=this.safe(t),o=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=J(s,i,`${r}.json`);if(ne(a))try{return JSON.parse(Ye(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=Xs();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||He(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Tt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Y().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:gs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let I=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(I))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${I}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=f=>{u||(u=!0,d(f))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{He(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Tu(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
153
153
|
`)}export{yr as a,Lu as b,br as c,la as d,xr as e,yt as f,Xu as g,el as h,tl as i,il as j,Tt as k,Ra as l,Gr as m,La as n,Fa as o,Ha as p,Qr as q,vt as r,kt as s,id as t,Dl as u,Ol as v,mn as w,Y as x,uo as y,hd as z,xd as A,po as B,Vl as C,fo as D,wo as E,vo as F,gg as G,ko as H,Ct as I,yg as J,wg as K,ze as L,kc as M,Ac as N,$c as O,Cc as P,Mc as Q,In as R,lu as S,gu as T,tf as U,nf as V,yu as W,wu as X,bu as Y,Mn as Z,xi as _,Si as $,Su as aa,Ii as ba,Ti as ca,Tu as da};
|
|
154
|
-
//# sourceMappingURL=chunk-
|
|
154
|
+
//# sourceMappingURL=chunk-247SOQLP.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{readFileSync as l,existsSync as f}from"fs";import{resolve as u}from"path";function a(e){let n=[];for(let r of e.split(`
|
|
2
|
+
`)){let t=r.trim();if(!t||t.startsWith("#"))continue;let s=t.startsWith("export ")?t.slice(7).trim():t,i=s.indexOf("=");if(i===-1)continue;let c=s.slice(0,i).trim(),o=s.slice(i+1).trim();o.length>=2&&(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),c&&n.push([c,o])}return n}function E(e){let n={};for(let r of[".env",".env.gitlab"]){let t=u(e,r);if(f(t))try{for(let[s,i]of a(l(t,"utf-8")))n[s]=i}catch{}}return n}var p=new Map;function g(e=process.cwd()){let n=p.get(e);if(n)return n;let r=u(e,".env"),t;if(!f(r))t=new Set;else try{t=new Set(a(l(r,"utf-8")).map(([s])=>s))}catch{t=new Set}return p.set(e,t),t}function A(e,n=process.env,r=process.cwd()){let t=E(e),s=g(r),i={...n};for(let c of s)c in t||delete i[c];for(let[c,o]of Object.entries(t))i[c]=o;return i}function d(e){return delete e.ANTHROPIC_API_KEY,delete e.ANTHROPIC_API_KEY_OLD,e}function v(e){let n=e.HOME||process.env.HOME,r=[e.PATH||"",n?`${n}/.local/bin`:"","/opt/homebrew/bin","/usr/local/bin"];return e.PATH=Array.from(new Set(r.flatMap(t=>t.split(":")).filter(Boolean))).join(":"),e}function m(){return v(d({...process.env}))}function S(e,n="subscription"){if(n!=="api")return d(e);if(!e.ANTHROPIC_API_KEY)throw new Error(`billing "api" needs ANTHROPIC_API_KEY in the agent's environment`);return delete e.ANTHROPIC_API_KEY_OLD,delete e.CLAUDE_CODE_OAUTH_TOKEN,e}function y(e){if(f(e))for(let[n,r]of a(l(e,"utf-8")))process.env[n]===void 0&&(process.env[n]=r)}export{A as a,d as b,m as c,S as d,y as e};
|
|
3
|
+
//# sourceMappingURL=chunk-56KNKUFF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/workspace-env.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// Loads per-agent secrets from the agent's workspace and tells the runtime\n// which keys the daemon's own .env injected, so we can strip those before\n// spawning the agent's claude process. Without this, every agent inherits\n// the daemon's GITLAB_TOKEN regardless of whether their workspace has its\n// own .env.gitlab — defeating per-agent identity boundaries (each agent\n// should commit/push as itself, not as the daemon's account).\n\n/**\n * Parse a dotenv-style file. Tolerates the `export KEY=VALUE` form used by\n * shell-sourced files like .env.gitlab on peer-server.\n */\nfunction parseDotEnv(content: string): Array<[string, string]> {\n const out: Array<[string, string]> = []\n for (const raw of content.split(\"\\n\")) {\n const trimmed = raw.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const stripped = trimmed.startsWith(\"export \") ? trimmed.slice(7).trim() : trimmed\n const eq = stripped.indexOf(\"=\")\n if (eq === -1) continue\n const key = stripped.slice(0, eq).trim()\n let value = stripped.slice(eq + 1).trim()\n if (value.length >= 2 && ((value.startsWith('\"') && value.endsWith('\"')) || (value.startsWith(\"'\") && value.endsWith(\"'\")))) {\n value = value.slice(1, -1)\n }\n if (key) out.push([key, value])\n }\n return out\n}\n\n/**\n * Read .env then .env.gitlab from a workspace and return their merged keys.\n * .env.gitlab wins on collision — it's the more specific per-channel file.\n */\nexport function loadWorkspaceEnv(workspace: string): Record<string, string> {\n const merged: Record<string, string> = {}\n for (const fname of [\".env\", \".env.gitlab\"]) {\n const path = resolve(workspace, fname)\n if (!existsSync(path)) continue\n try {\n for (const [k, v] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n merged[k] = v\n }\n } catch { /* best-effort */ }\n }\n return merged\n}\n\n/**\n * Keys defined in the daemon's own .env file, cached per daemonCwd. The\n * runtime uses this to strip those keys from the child env before adding\n * the workspace overrides — so a daemon-level GITLAB_TOKEN never leaks to\n * an agent that hasn't put one in its own workspace.\n */\nconst daemonEnvKeysCache = new Map<string, Set<string>>()\n\nexport function getDaemonEnvKeys(daemonCwd: string = process.cwd()): Set<string> {\n const cached = daemonEnvKeysCache.get(daemonCwd)\n if (cached) return cached\n const path = resolve(daemonCwd, \".env\")\n let keys: Set<string>\n if (!existsSync(path)) {\n keys = new Set()\n } else {\n try {\n keys = new Set(parseDotEnv(readFileSync(path, \"utf-8\")).map(([k]) => k))\n } catch {\n keys = new Set()\n }\n }\n daemonEnvKeysCache.set(daemonCwd, keys)\n return keys\n}\n\n/** Test-only: clear the cache so a different daemonCwd is re-read. */\nexport function _resetDaemonEnvKeysCache(): void {\n daemonEnvKeysCache.clear()\n}\n\n/**\n * Build the env object passed to a spawned agent process. Starts from\n * parentEnv (default process.env), removes any keys that came from the\n * daemon's own .env (so daemon-level secrets don't leak), then layers in\n * workspace .env / .env.gitlab.\n *\n * - System env (PATH, HOME, USER, …) survives untouched.\n * - Daemon-level secrets (e.g. GITLAB_TOKEN in /home/peer/agentx/.env) are\n * stripped UNLESS the workspace provides its own value for that key.\n * - Workspace env (per-agent .env / .env.gitlab) wins on the final merge.\n */\nexport function buildAgentEnv(\n workspace: string,\n parentEnv: NodeJS.ProcessEnv = process.env,\n daemonCwd: string = process.cwd(),\n): NodeJS.ProcessEnv {\n const workspaceEnv = loadWorkspaceEnv(workspace)\n const daemonOwnedKeys = getDaemonEnvKeys(daemonCwd)\n const child: NodeJS.ProcessEnv = { ...parentEnv }\n for (const k of daemonOwnedKeys) {\n if (!(k in workspaceEnv)) delete child[k]\n }\n for (const [k, v] of Object.entries(workspaceEnv)) {\n child[k] = v\n }\n return child\n}\n\n// Force the `claude` CLI to use OAuth/subscription billing. When\n// ANTHROPIC_API_KEY is present (env, systemd EnvironmentFile, daemon .env not\n// stripped because the workspace also defines it), the CLI silently switches\n// to the API-key path and any usage caps on that key surface as\n// \"You have reached your specified API usage limits...\". This caused\n// claude-code-tier agents to bypass the user's subscription. The same\n// stripping pattern lives in src/agent/providers/claude-code.ts for the\n// in-process provider — keep them in sync.\nexport function stripAnthropicApiKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n return env\n}\n\n/** `env` with the folders the fleet's CLIs install to added to PATH. A\n * process started by launchd, or the MCP server Claude Code starts, does\n * not get a login shell's PATH, and `claude` usually lives in\n * ~/.local/bin. */\nexport function withToolPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const home = env.HOME || process.env.HOME\n const parts = [\n env.PATH || \"\",\n home ? `${home}/.local/bin` : \"\",\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n ]\n env.PATH = Array.from(new Set(parts.flatMap((p) => p.split(\":\")).filter(Boolean))).join(\":\")\n return env\n}\n\n/** The env for a one-shot `claude -p` call: subscription billing and a\n * PATH that can find the CLI. */\nexport function claudeCliEnv(): NodeJS.ProcessEnv {\n return withToolPath(stripAnthropicApiKey({ ...process.env }))\n}\n\n/** How an agent's `claude` CLI is billed. \"subscription\" (the default) is\n * the OAuth login shared by the fleet. \"api\" bills ANTHROPIC_API_KEY\n * instead, for agents that must not draw on that shared quota, such as\n * benchmark runs. */\nexport type ClaudeBilling = \"subscription\" | \"api\"\n\n/** Shape a `claude` spawn env for the agent's billing. Each mode removes the\n * other's credential, because the CLI silently uses whichever it finds. An\n * \"api\" agent with no key throws rather than falling back to the\n * subscription. */\nexport function claudeBillingEnv(\n env: NodeJS.ProcessEnv,\n billing: ClaudeBilling = \"subscription\",\n): NodeJS.ProcessEnv {\n if (billing !== \"api\") return stripAnthropicApiKey(env)\n if (!env.ANTHROPIC_API_KEY) {\n throw new Error('billing \"api\" needs ANTHROPIC_API_KEY in the agent\\'s environment')\n }\n delete env.ANTHROPIC_API_KEY_OLD\n delete env.CLAUDE_CODE_OAUTH_TOKEN\n return env\n}\n\n/**\n * Load a dotenv file into process.env for the CURRENT process. Variables\n * already present win, so a systemd/launchd override always beats the file.\n *\n * `agentx daemon start` has always done this; `agentx board serve` did not,\n * so `${MESH_TOKEN}` in agentx.json expanded to \"\" inside the dashboard and\n * every proxied mesh call went out with an empty Bearer (401 from peers).\n */\nexport function loadEnvFileIntoProcess(path: string): void {\n if (!existsSync(path)) return\n for (const [key, value] of parseDotEnv(readFileSync(path, \"utf-8\"))) {\n if (process.env[key] === undefined) process.env[key] = value\n }\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KACzC,OAAS,WAAAC,MAAe,OAaxB,SAASC,EAAYC,EAA0C,CAC7D,IAAMC,EAA+B,CAAC,EACtC,QAAWC,KAAOF,EAAQ,MAAM;AAAA,CAAI,EAAG,CACrC,IAAMG,EAAUD,EAAI,KAAK,EACzB,GAAI,CAACC,GAAWA,EAAQ,WAAW,GAAG,EAAG,SACzC,IAAMC,EAAWD,EAAQ,WAAW,SAAS,EAAIA,EAAQ,MAAM,CAAC,EAAE,KAAK,EAAIA,EACrEE,EAAKD,EAAS,QAAQ,GAAG,EAC/B,GAAIC,IAAO,GAAI,SACf,IAAMC,EAAMF,EAAS,MAAM,EAAGC,CAAE,EAAE,KAAK,EACnCE,EAAQH,EAAS,MAAMC,EAAK,CAAC,EAAE,KAAK,EACpCE,EAAM,QAAU,IAAOA,EAAM,WAAW,GAAG,GAAKA,EAAM,SAAS,GAAG,GAAOA,EAAM,WAAW,GAAG,GAAKA,EAAM,SAAS,GAAG,KACtHA,EAAQA,EAAM,MAAM,EAAG,EAAE,GAEvBD,GAAKL,EAAI,KAAK,CAAC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,CAMO,SAASC,EAAaD,EAA2C,CACtE,IAAME,EAAOF,EAAI,MAAQ,QAAQ,IAAI,KAC/BG,EAAQ,CACZH,EAAI,MAAQ,GACZE,EAAO,GAAGA,eAAoB,GAC9B,oBACA,gBACF,EACA,OAAAF,EAAI,KAAO,MAAM,KAAK,IAAI,IAAIG,EAAM,QAASC,GAAMA,EAAE,MAAM,GAAG,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC,EAAE,KAAK,GAAG,EACpFJ,CACT,CAIO,SAASK,GAAkC,CAChD,OAAOJ,EAAaF,EAAqB,CAAE,GAAG,QAAQ,GAAI,CAAC,CAAC,CAC9D,CAYO,SAASO,EACdN,EACAO,EAAyB,eACN,CACnB,GAAIA,IAAY,MAAO,OAAOR,EAAqBC,CAAG,EACtD,GAAI,CAACA,EAAI,kBACP,MAAM,IAAI,MAAM,kEAAmE,EAErF,cAAOA,EAAI,sBACX,OAAOA,EAAI,wBACJA,CACT,CAUO,SAASQ,EAAuBC,EAAoB,CACzD,GAAKC,EAAWD,CAAI,EACpB,OAAW,CAACE,EAAKC,CAAK,IAAKC,EAAYC,EAAaL,EAAM,OAAO,CAAC,EAC5D,QAAQ,IAAIE,CAAG,IAAM,SAAW,QAAQ,IAAIA,CAAG,EAAIC,EAE3D","names":["readFileSync","existsSync","resolve","parseDotEnv","content","out","raw","trimmed","stripped","eq","key","value","loadWorkspaceEnv","workspace","merged","fname","path","k","v","daemonEnvKeysCache","getDaemonEnvKeys","daemonCwd","cached","keys","buildAgentEnv","workspace","parentEnv","daemonCwd","workspaceEnv","loadWorkspaceEnv","daemonOwnedKeys","getDaemonEnvKeys","child","k","v","stripAnthropicApiKey","env","withToolPath","home","parts","p","claudeCliEnv","claudeBillingEnv","billing","loadEnvFileIntoProcess","path","existsSync","key","value","parseDotEnv","readFileSync"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{c as $,d as I,e as D,f as b}from"./chunk-Y4CYQV7G.js";import{existsSync as F,mkdirSync as j,readdirSync as z,readFileSync as B,renameSync as V,writeFileSync as M}from"fs";import{resolve as N}from"path";function v(e){return e?.kind==="retro"||e?.kind==="retro-check"}var O={keep:"Keep it",loosen:"Loosen it",remove:"Remove it"};function R(e,t,n){let r=`guard rule \`${e.ruleId}\` in \`${e.file}\``,i=[`This was a monthly review of ${r}, added by the retro on run ${e.taskId}. It fires often on runs that went well.`];return!(t.status==="decided"&&t.verdict==="yes")||t.choice===O.keep||!t.choice?(i.push("Change nothing: the rule stays as it is."),i):(i.push(t.choice===O.remove?`The operator chose to remove it. Delete ${r} as a pull request.`:`The operator chose to loosen it. Narrow ${r} (a tighter match, or \`applies_to\`) so it stops firing on good work, keep its \`retro:${e.taskId}\` tag, and open it as a pull request.`),n&&i.push("The operator's note:",n),i.push("Do not change the live policy directly: the operator reviews the pull request first."),i)}function m(e){return e.status==="decided"&&e.verdict==="yes"&&!!e.choice&&e.choice!==y}function T(e,t,n){let r=[`This was a retro card about run ${e.taskId} (\`agentx trace show ${e.taskId}\`).`];if(!m(t))return r.push("Change nothing. Do not propose these fixes again on your own."),r;r.push(`The operator picked this fix: ${t.choice}`);let i=e.specs?.[(t.choices??[]).indexOf(t.choice)];return i&&r.push("Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):",i),n&&r.push("The operator's note on the fix:",n),r.push("Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.","Do not apply it to a live system directly. Tag what you add with `retro:"+e.taskId+"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list."),r}var y="None of these";function E(e,t){let n=e.list?` in the "${e.list}" list`:"",r=[`This card came from the operator's reminder "${e.title}"${n} (id ${e.id}).`];return r.push(t?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),r}var L=["discard","keep","pause"];function x(e){return e==="approve"?"keep":L.includes(e)?e:null}var d={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},Y={defaultExpiryDays:3,maxExpiryDays:30};function w(e){return N(e,".agentx","approvals")}var H=/^[a-z0-9][a-z0-9-]{0,80}$/;function A(e){return H.test(e)}function q(e,t){if(!A(t))throw new Error(`invalid card id: ${t}`);return N(w(e),`${t}.json`)}function J(e,t){let n=new Date(e).toISOString().slice(0,10),r=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${r||"card"}-${Math.random().toString(36).slice(2,6)}`}function f(e,t){j(w(e),{recursive:!0});let n=q(e,t.id),r=`${n}.${process.pid}.tmp`;M(r,JSON.stringify(t,null,2)+`
|
|
2
|
+
`),V(r,n)}function C(e,t){if(!A(t))return null;try{let n=JSON.parse(B(q(e,t),"utf-8")),r=n.if_silent==="approve"||n.outcome==="approve";return{...n,if_silent:x(n.if_silent)??"keep",...n.outcome?{outcome:x(n.outcome)??"keep"}:{},...r?{if_silent_asked:"approve"}:{}}}catch{return null}}function _(e,t){let n=w(e);if(!F(n))return[];let r=[];for(let i of z(n).filter(o=>o.endsWith(".json")&&!o.startsWith("_")).sort()){let o=C(e,i.slice(0,-5));o&&(!t||o.status===t)&&r.push(o)}return r}function c(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function K(e,t,n){let r=t+n.maxExpiryDays*864e5,i,o=c(e);if(!o)i=t+n.defaultExpiryDays*864e5;else{let s=/^(\d+)\s*([hd])$/i.exec(o);if(s)i=t+Number(s[1])*(s[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(o),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${o}")`}}return i<=t?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,r)).toISOString()}}function P(e,t={}){let n=t.now??Date.now(),r=t.settings??Y,i=c(e.title),o=c(e.ask),s=c(e.recommend),a=c(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!o)return{ok:!1,error:"ask is required: the yes/no question"};if(!s)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!a)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>d.title)return{ok:!1,error:`title is longer than ${d.title} characters`};if(o.length>d.ask)return{ok:!1,error:`ask is longer than ${d.ask} characters`};if(s.length>d.recommend)return{ok:!1,error:`recommend is longer than ${d.recommend} characters`};let p=c(e.if_silent).toLowerCase(),S=x(p);if(!S)return{ok:!1,error:`if_silent must be one of ${L.join(", ")}`};let g=K(e.expires,n,r);if(!g.ok)return g;let l=c(e.source);if(l.length>d.source)return{ok:!1,error:`source is longer than ${d.source} characters`};if(l&&/^[a-z][a-z0-9+.-]*:/i.test(l)&&!/^https?:\/\//i.test(l))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let h=$(e);if(!h.ok)return h;let k,u=e.reply;return u&&typeof u=="object"&&c(u.channel)&&c(u.chatId)&&(k={channel:c(u.channel),chatId:c(u.chatId),...c(u.accountId)?{accountId:c(u.accountId)}:{}}),{ok:!0,card:{id:J(n,i),title:i,ask:o,recommend:s,if_silent:S,...p==="approve"?{if_silent_asked:"approve"}:{},expires:g.at,...l?{source:l}:{},raised_by:a,...t.node?{node:t.node}:{},created_at:new Date(n).toISOString(),...k?{reply:k}:{},...h.value,...t.origin?{origin:t.origin}:{},status:"pending"}}}function Z(e,t,n={}){let r=P(t,n);if(!r.ok)return r;let i=a=>v(a.origin),o=i(r.card),s=_(e,"pending").filter(a=>a.raised_by===r.card.raised_by&&i(a)===o).length;if(s>=d.pendingPerAgent){let a=o?"retro cards":"cards";return{ok:!1,error:`${r.card.raised_by} already has ${s} ${a} waiting; wait for decisions before raising more`}}return f(e,r.card),r}function ee(e,t,n,r={}){let i=C(e,t);if(!i)return{ok:!1,error:`no card "${t}"`};if(i.status!=="pending")return{ok:!1,error:`card "${t}" is already ${i.status}`};let o=D(i,n,r);if(!o.ok)return o;let s=c(r.note).slice(0,d.note),a={...i,status:"decided",verdict:n,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString(),...s?{note:s}:{},...o.choice?{choice:o.choice}:{},...o.text?{text:o.text}:{}};return f(e,a),{ok:!0,card:a}}function te(e,t=Date.now()){let n=[];for(let r of _(e,"pending")){if(Date.parse(r.expires)>t)continue;let i={...r,status:"expired",outcome:r.if_silent,decided_by:"expiry",decided_at:new Date(t).toISOString()};f(e,i),n.push(i)}return n}function re(e){return _(e).filter(t=>t.status!=="pending"&&!t.agent_notified_at)}function ne(e,t,n=Date.now()){let r=C(e,t);!r||r.agent_notified_at||f(e,{...r,agent_notified_at:new Date(n).toISOString()})}function ie(e){let t=e.origin?.kind==="retro"?e.origin:void 0,n=e.status==="decided"?e.verdict==="yes"?t&&!m(e)?`The operator picked "${y}", which counts as NO.`:"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,r=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,n],i=e.origin?.kind==="retro-check"?e.origin:void 0;if(e.status==="decided"&&e.verdict==="yes"&&!t&&!i&&r.push(...b(e)),e.note&&r.push(`Operator note: ${e.note}`),e.source&&r.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&r.push(...E(e.origin,e.status==="decided"&&e.verdict==="yes")),t||i){let o=p=>p.replace(/\s+/g," ").trim(),s=I(e.draft,e.choice),a=e.text&&o(e.text)!==o(s)?e.text:void 0;r.push(...t?T(t,e,a):R(i,e,a))}return e.reply&&r.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&r.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),r.push("Act on this result now. Do not raise the same card again."),r.join(`
|
|
3
|
+
`)}export{v as a,O as b,m as c,y as d,L as e,d as f,w as g,A as h,C as i,_ as j,Z as k,ee as l,te as m,re as n,ne as o,ie as p};
|
|
4
|
+
//# sourceMappingURL=chunk-6FVFD5WU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, draftFor, resolveAnswer, type CardChoices } from \"./choices\"\nimport { isRetroOrigin, originLines, RETRO_NONE, retroApproved, retroCheckLines, retroLines, type CardOrigin } from \"./origin\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\n// No card approves itself (#741): only the operator says yes. \"approve\",\n// which older agents and stored cards may still carry, is read as \"keep\".\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\"]\n\nfunction asIfSilent(v: string): IfSilent | null {\n if (v === \"approve\") return \"keep\"\n return IF_SILENT_VALUES.includes(v as IfSilent) ? (v as IfSilent) : null\n}\n\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n /** Set when the agent, or a card stored before #741, asked for\n * \"approve\" on expiry; `if_silent` then holds \"keep\". Kept so the\n * record still shows what was originally asked. */\n if_silent_asked?: \"approve\"\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n const card = JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n // A card that expired as \"approve\" before #741 is read as \"keep\" too, so\n // an agent not yet told never hears \"default applied: approve\".\n const legacy = (card.if_silent as string) === \"approve\" || (card.outcome as string) === \"approve\"\n return {\n ...card,\n if_silent: asIfSilent(card.if_silent) ?? \"keep\",\n ...(card.outcome ? { outcome: asIfSilent(card.outcome) ?? \"keep\" } : {}),\n ...(legacy ? { if_silent_asked: \"approve\" as const } : {}),\n }\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilentRaw = oneLine(input.if_silent).toLowerCase()\n const ifSilent = asIfSilent(ifSilentRaw)\n if (!ifSilent) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent,\n ...(ifSilentRaw === \"approve\" ? { if_silent_asked: \"approve\" as const } : {}),\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n // Retro cards are raised for an agent, not by it: they get their own\n // count, so they never use up the agent's room for its own cards.\n const isRetro = (c: { origin?: CardOrigin }) => isRetroOrigin(c.origin)\n const retro = isRetro(built.card)\n const open = listCards(root, \"pending\").filter((c) => c.raised_by === built.card.raised_by && isRetro(c) === retro).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n const what = retro ? \"retro cards\" : \"cards\"\n return { ok: false, error: `${built.card.raised_by} already has ${open} ${what} waiting; wait for decisions before raising more` }\n }\n saveCard(root, built.card)\n return built\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const retro = card.origin?.kind === \"retro\" ? card.origin : undefined\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\"\n ? (retro && !retroApproved(card) ? `The operator picked \"${RETRO_NONE}\", which counts as NO.` : \"The operator said YES.\")\n : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n // A retro card's pick and spec go through retroLines, labelled as the\n // reviewer's proposal: never \"Approved text (send exactly this)\".\n const check = card.origin?.kind === \"retro-check\" ? card.origin : undefined\n if (card.status === \"decided\" && card.verdict === \"yes\" && !retro && !check) lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (retro || check) {\n // Compare ignoring whitespace so a dashboard that only reflows the draft\n // does not resend the whole draft as the operator's note.\n const squash = (s: string) => s.replace(/\\s+/g, \" \").trim()\n const draft = draftFor(card.draft, card.choice)\n const edited = card.text && squash(card.text) !== squash(draft) ? card.text : undefined\n lines.push(...(retro ? retroLines(retro, card, edited) : retroCheckLines(check!, card, edited)))\n }\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\n/** A retro card (src/retro): fixes to the agents' environment proposed\n * from one run that struggled. The answer goes back to the agent that ran\n * it, which builds the picked fix for a second review. */\nexport interface RetroOrigin {\n kind: \"retro\"\n /** The run the retro read. */\n taskId: string\n /** Failure signature (wiki/failure-candidates.ts), for one card per signature. */\n signature: string\n /** The reviewer's spec for each fix, in the order of the card's choices\n * (without \"None of these\"). Only the picked one reaches the agent. */\n specs?: string[]\n}\n\n/** A monthly review of a check a retro added (src/retro/checks.ts): a\n * guard rule tagged `retro:<taskId>` that fires often on runs that went\n * well. The answer goes back to the agent that built it, which keeps,\n * loosens or removes it for a second review. */\nexport interface RetroCheckOrigin {\n kind: \"retro-check\"\n /** The guard rule's id. */\n ruleId: string\n /** The run whose retro asked for the rule. */\n taskId: string\n /** The policy file that holds the rule, relative to the daemon's folder. */\n file: string\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin | RetroOrigin | RetroCheckOrigin\n\n/** Retro cards of either kind: raised for an agent, not by it. */\nexport function isRetroOrigin(origin: CardOrigin | undefined): origin is RetroOrigin | RetroCheckOrigin {\n return origin?.kind === \"retro\" || origin?.kind === \"retro-check\"\n}\n\n/** The choices on a check review card, in this order. */\nexport const CHECK_CHOICES = { keep: \"Keep it\", loosen: \"Loosen it\", remove: \"Remove it\" } as const\n\n/** Lines for the agent told the result of a check review card. Keep, NO\n * and silence all leave the rule as it is. */\nexport function retroCheckLines(\n origin: RetroCheckOrigin,\n card: { status: string; verdict?: string; choice?: string },\n edited?: string,\n): string[] {\n const rule = `guard rule \\`${origin.ruleId}\\` in \\`${origin.file}\\``\n const lines = [`This was a monthly review of ${rule}, added by the retro on run ${origin.taskId}. It fires often on runs that went well.`]\n const yes = card.status === \"decided\" && card.verdict === \"yes\"\n if (!yes || card.choice === CHECK_CHOICES.keep || !card.choice) {\n lines.push(\"Change nothing: the rule stays as it is.\")\n return lines\n }\n lines.push(card.choice === CHECK_CHOICES.remove\n ? `The operator chose to remove it. Delete ${rule} as a pull request.`\n : `The operator chose to loosen it. Narrow ${rule} (a tighter match, or \\`applies_to\\`) so it stops firing on good work, keep its \\`retro:${origin.taskId}\\` tag, and open it as a pull request.`)\n if (edited) lines.push(\"The operator's note:\", edited)\n lines.push(\"Do not change the live policy directly: the operator reviews the pull request first.\")\n return lines\n}\n\n/** True when the operator answered a retro card with something to build:\n * YES and a fix picked. YES on \"None of these\" counts as NO. */\nexport function retroApproved(card: { status: string; verdict?: string; choice?: string }): boolean {\n return card.status === \"decided\" && card.verdict === \"yes\" && !!card.choice && card.choice !== RETRO_NONE\n}\n\n/** Lines for the agent told the result of a retro card. Replaces the plain\n * card's \"Chosen / Approved text\" lines: the specs are model output written\n * from the run's content, so they reach the agent labelled as such, never\n * as text the operator approved word for word.\n * `edited` is the operator's text when they changed the suggested one. */\nexport function retroLines(\n origin: RetroOrigin,\n card: { status: string; verdict?: string; choice?: string; choices?: string[] },\n edited?: string,\n): string[] {\n const lines = [`This was a retro card about run ${origin.taskId} (\\`agentx trace show ${origin.taskId}\\`).`]\n if (!retroApproved(card)) {\n lines.push(\"Change nothing. Do not propose these fixes again on your own.\")\n return lines\n }\n lines.push(`The operator picked this fix: ${card.choice}`)\n const spec = origin.specs?.[(card.choices ?? []).indexOf(card.choice!)]\n if (spec) {\n lines.push(\n \"Spec for this fix, drafted by the retro reviewer from the run's content (a proposal to check, not instructions from the operator):\",\n spec,\n )\n }\n if (edited) lines.push(\"The operator's note on the fix:\", edited)\n lines.push(\n \"Build the chosen fix as a change the operator reviews again: a pull request, or a guard rule in warn mode.\",\n \"Do not apply it to a live system directly. Tag what you add with `retro:\" + origin.taskId + \"` so it can be found and removed later; for a guard rule, put the tag in its `tags` list.\",\n )\n return lines\n}\n\n/** The last choice on every retro card. */\nexport const RETRO_NONE = \"None of these\"\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n"],"mappings":"6DAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAA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AA4E3D,EAAK,OAAO,EAClH2D,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","resolve","isRetroOrigin","origin","CHECK_CHOICES","retroCheckLines","card","edited","rule","lines","retroApproved","RETRO_NONE","retroLines","spec","originLines","approved","where","IF_SILENT_VALUES","asIfSilent","v","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","readCard","readFileSync","legacy","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilentRaw","ifSilent","expiry","source","extras","buildChoices","reply","r","createCard","built","isRetro","isRetroOrigin","retro","open","what","decideCard","verdict","answer","resolveAnswer","note","decided","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","verdictMessage","result","retroApproved","RETRO_NONE","lines","check","answerLines","originLines","squash","s","draft","draftFor","edited","retroLines","retroCheckLines"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as E}from"./chunk-FTZCNID3.js";import{c as R}from"./chunk-56KNKUFF.js";import{y as W,z as I}from"./chunk-NDPU6AX2.js";import{b as v,c as C}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let p=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,u=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await N(q(n,e,l,m),p,h),f=K(y))}catch(c){return u("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await N(J(n,b),g,h*2)}catch(c){return u("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let Q=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:Q,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,p){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<p;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let u of h.meta.related||[]){let m=g.get(u.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,p,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,p,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),u=await W(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!u||u.mode!=="active")return null;let w=_(u.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let p=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=C(n,v(p)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?E(o,e.graphPath):0,u=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(u),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(u),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let p=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -7,7 +7,7 @@ The request was classified under the intent-graph path "${t.join(" \u203A ")}".
|
|
|
7
7
|
## Question
|
|
8
8
|
|
|
9
9
|
${n}
|
|
10
|
-
${
|
|
10
|
+
${p}
|
|
11
11
|
## Catalog (_index.md \u2014 articles grouped by type, with wikilink previews)
|
|
12
12
|
|
|
13
13
|
${a}
|
|
@@ -26,7 +26,7 @@ Return ONLY valid JSON, no markdown fencing, no prose:
|
|
|
26
26
|
...
|
|
27
27
|
]
|
|
28
28
|
|
|
29
|
-
If none of the articles match, return [].`}function J(n,a){let o=a.map(t=>{let
|
|
29
|
+
If none of the articles match, return [].`}function J(n,a){let o=a.map(t=>{let p=`### ${t.meta.title} \u2014 ${t.meta.type||"untyped"} (${t.path}) [hop ${t.hop}]`,g=t.meta.related?.length?`Related: ${t.meta.related.join(", ")}`:"";return[p,g,"",t.content].filter(Boolean).join(`
|
|
30
30
|
`)}).join(`
|
|
31
31
|
|
|
32
32
|
---
|
|
@@ -45,5 +45,5 @@ ${o}
|
|
|
45
45
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
|
-
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
48
|
+
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function N(n,a,o){let{writeFileSync:t,mkdirSync:p,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);p(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,u=L(h,{env:R(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(u);return String(m.result||m.content||"")}catch{return u}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
+
//# sourceMappingURL=chunk-6JJJ5MUU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/query.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"fs\"\nimport { buildIndex, scoreAll } from \"@/memory/bm25\"\nimport { askSeat } from \"@/decisions/seat\"\nimport { ancestryScore } from \"@/graph\"\nimport {\n DEFAULT_SHORTLIST,\n WIKI_RERANK_SEAT,\n rerankQuestions,\n rerankState,\n toRanking,\n type RerankCandidate,\n} from \"@/decisions/seats/wiki-rerank\"\nimport { claudeCliEnv } from \"@/utils/workspace-env\"\nimport { resolve } from \"path\"\nimport { execSync } from \"child_process\"\nimport type { WikiArticle } from \"./types\"\nimport type { WikiStore } from \"./store\"\n\n/**\n * Agentic wiki query — the \"Farzapedia-faithful\" retrieval path.\n *\n * Two LLM calls + a deterministic graph walk:\n * 1. Selector (cheap): read `_index.md` + question → pick up to `maxCandidates`\n * candidate articles by title + type.\n * 2. Walk (pure code): starting from candidates, follow `related` wikilinks\n * up to `maxHops`, capped at `maxArticles` total.\n * 3. Synthesis (main): answer the question from the walked subgraph.\n *\n * Returns an answer with citations and a trace of which articles were walked,\n * so callers can audit the retrieval path.\n */\n\nexport interface AgenticQueryOptions {\n /** Candidate-selection model (cheap). Defaults to \"haiku\". */\n selectorModel?: string\n /** Synthesis model (main). Defaults to \"sonnet\". */\n synthModel?: string\n /** Number of candidates the selector is asked to return. Default 3. */\n maxCandidates?: number\n /** Wikilink hops from candidates. Default 2. */\n maxHops?: number\n /** Hard cap on total articles walked. Default 8. */\n maxArticles?: number\n /** Timeout per LLM call, ms. Default 60_000. */\n timeoutMs?: number\n /** Logger — defaults to console.error. */\n log?: (...args: unknown[]) => void\n /** Intent-graph path the question's request was classified under.\n * Articles on the same branch rank higher in candidate selection. */\n messagePath?: string[]\n /** Weight of the branch match against the text match, 0–1. Default 0.6\n * (`graph.retrievalWeights.graph`). */\n graphWeight?: number\n}\n\nexport interface AgenticQueryResult {\n answer: string\n citations: Array<{ title: string; path: string; type?: string }>\n /** Titles/paths the selector picked. */\n candidates: Array<{ title: string; path: string }>\n /** Full article subgraph the walk produced. */\n walked: Array<{ title: string; path: string; type?: string; hop: number }>\n /** \"no-catalog\" | \"no-candidates\" | \"ok\" */\n status: \"ok\" | \"no-catalog\" | \"no-candidates\" | \"error\"\n /** For operator debugging only. */\n trace?: {\n selectorMs: number\n synthesisMs: number\n selectorOutput?: string\n }\n error?: string\n}\n\n/**\n * Run an agentic query against a specific agent's WikiStore.\n *\n * `requesterId` is used for permission checks — only articles the requester\n * can read will be included in the synthesis input.\n */\nexport async function agenticQuery(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n opts: AgenticQueryOptions = {},\n): Promise<AgenticQueryResult> {\n const selectorModel = opts.selectorModel ?? \"haiku\"\n const synthModel = opts.synthModel ?? \"sonnet\"\n const maxCandidates = opts.maxCandidates ?? 3\n const maxHops = opts.maxHops ?? 2\n const maxArticles = opts.maxArticles ?? 8\n const timeoutMs = opts.timeoutMs ?? 60_000\n const log = opts.log ?? console.error.bind(console, \"[wiki-query]\")\n const messagePath = opts.messagePath?.length ? opts.messagePath : undefined\n const graphWeight = opts.graphWeight ?? DEFAULT_GRAPH_WEIGHT\n\n // --- Step 1: Load the catalog ---\n const catalogPath = resolve(store.baseDir, \"_index.md\")\n if (!existsSync(catalogPath)) {\n return emptyResult(\"no-catalog\", question, \"No _index.md found — run `agentx wiki status` to rebuild.\")\n }\n const catalog = readFileSync(catalogPath, \"utf-8\")\n\n // --- Step 2: Selector — pick candidates ---\n const selectorStart = Date.now()\n let candidates: Array<{ title: string; path: string }> = []\n let selectorOutput = \"\"\n try {\n const viaSeat = await selectCandidatesViaSeat(question, store, requesterId, maxCandidates, messagePath, graphWeight)\n if (viaSeat) {\n candidates = viaSeat\n selectorOutput = `[wiki-rerank seat] ${viaSeat.map((c) => c.title).join(\" | \")}`\n } else {\n selectorOutput = await runClaude(\n buildSelectorPrompt(question, catalog, maxCandidates, messagePath),\n selectorModel,\n timeoutMs,\n )\n candidates = parseCandidates(selectorOutput)\n }\n } catch (e: any) {\n log(\"selector failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Selector: ${e?.message || \"unknown\"}`), trace: { selectorMs: Date.now() - selectorStart, synthesisMs: 0, selectorOutput } }\n }\n const selectorMs = Date.now() - selectorStart\n\n if (candidates.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Selector returned no candidates.\"), trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 3: Walk the subgraph via `related` wikilinks ---\n const walked = walkSubgraph(candidates, store, requesterId, maxHops, maxArticles)\n\n if (walked.length === 0) {\n return { ...emptyResult(\"no-candidates\", question, \"Candidates did not resolve to readable articles.\"), candidates, trace: { selectorMs, synthesisMs: 0, selectorOutput } }\n }\n\n // --- Step 4: Synthesize the answer ---\n const synthStart = Date.now()\n let answer = \"\"\n try {\n answer = await runClaude(\n buildSynthesisPrompt(question, walked),\n synthModel,\n timeoutMs * 2,\n )\n } catch (e: any) {\n log(\"synthesis failed:\", e?.message)\n return { ...emptyResult(\"error\", question, `Synthesis: ${e?.message || \"unknown\"}`), candidates, walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })), trace: { selectorMs, synthesisMs: Date.now() - synthStart, selectorOutput } }\n }\n const synthesisMs = Date.now() - synthStart\n\n return {\n answer: answer.trim(),\n citations: walked.map(a => ({ title: a.meta.title, path: a.path, type: a.meta.type })),\n candidates,\n walked: walked.map(w => ({ title: w.meta.title, path: w.path, type: w.meta.type, hop: (w as any).hop ?? 0 })),\n status: \"ok\",\n trace: { selectorMs, synthesisMs, selectorOutput },\n }\n}\n\n// --- Helpers ---\n\nfunction emptyResult(\n status: AgenticQueryResult[\"status\"],\n _question: string,\n error?: string,\n): AgenticQueryResult {\n return {\n answer: \"\",\n citations: [],\n candidates: [],\n walked: [],\n status,\n error,\n }\n}\n\nfunction walkSubgraph(\n candidates: Array<{ title: string; path: string }>,\n store: WikiStore,\n requesterId: string | undefined,\n maxHops: number,\n maxArticles: number,\n): Array<WikiArticle & { hop: number }> {\n // Build a title → path index from the store so wikilinks resolve.\n const titleIndex = new Map<string, string>()\n for (const article of store.listArticles(requesterId || \"\")) {\n titleIndex.set(article.meta.title.toLowerCase(), article.path)\n }\n\n const opened = new Map<string, WikiArticle & { hop: number }>()\n let frontier: Array<{ path: string; hop: number }> = []\n\n for (const c of candidates) {\n if (!opened.has(c.path)) frontier.push({ path: c.path, hop: 0 })\n }\n\n while (frontier.length && opened.size < maxArticles) {\n const next = frontier.shift()!\n if (opened.has(next.path)) continue\n if (next.hop > maxHops) continue\n\n const article = requesterId\n ? store.readArticleAs(next.path, requesterId)\n : store.readArticle(next.path)\n if (!article) continue\n\n opened.set(next.path, { ...article, hop: next.hop })\n if (next.hop >= maxHops) continue\n\n for (const target of article.meta.related || []) {\n const path = titleIndex.get(target.toLowerCase())\n if (path && !opened.has(path)) {\n frontier.push({ path, hop: next.hop + 1 })\n }\n }\n }\n\n return Array.from(opened.values())\n}\n\n// --- Prompts ---\n\n/**\n * Pick candidates with the wiki-rerank seat instead of a Claude CLI call.\n *\n * The selector is 56% of a wiki query — 14.1s of a 25s total, measured —\n * and its whole job is \"pick 3 articles from this catalog\", which is a\n * Choice with per-option probabilities. Jev answers that in about a\n * second. Synthesis stays on Sonnet; it writes prose, which Jev cannot.\n *\n * BM25 shortlists first because the shared catalog carries 971 entries,\n * past the 255-option cap. Same two-stage shape as findRelevantReranked,\n * and it reuses that seat rather than introducing a second one.\n *\n * Returns null whenever the seat is off, errors, or has nothing to rank,\n * and the caller falls back to the CLI selector — so this is strictly an\n * accelerator, never a new way to fail.\n */\nasync function selectCandidatesViaSeat(\n question: string,\n store: WikiStore,\n requesterId: string | undefined,\n maxCandidates: number,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): Promise<Array<{ title: string; path: string }> | null> {\n try {\n const index = store.rebuildIndex()\n const pool = (index.articles ?? []).filter((a) => a.path && !a.path.includes(\"/_versions/\"))\n if (pool.length < 2) return null\n\n const shortlist = rankCatalogPool(question, pool, messagePath, graphWeight).slice(0, DEFAULT_SHORTLIST)\n\n const candidates: RerankCandidate[] = shortlist.map((i) => ({\n id: `k${i}`,\n title: pool[i].title || pool[i].path,\n tags: pool[i].tags,\n // The catalog has no body — a title, its type, its wikilinks and its\n // branch of the intent graph are what the selector chooses on.\n excerpt: [\n pool[i].type ? `type: ${pool[i].type}` : \"\",\n (pool[i].related ?? []).length ? `related: ${(pool[i].related ?? []).join(\", \")}` : \"\",\n (pool[i].graphPath ?? []).length ? `graph: ${(pool[i].graphPath ?? []).join(\" › \")}` : \"\",\n ].filter(Boolean).join(\" · \"),\n }))\n\n const result = await askSeat(\n WIKI_RERANK_SEAT,\n rerankState({ query: question, candidates, excerptChars: 300 }),\n rerankQuestions(candidates),\n { features: { agent: requesterId ?? \"unknown\", stage: \"catalog-selector\" } },\n )\n if (!result || result.mode !== \"active\") return null\n\n const ranking = toRanking(result.answers as never, candidates)\n const picked = ranking.ranked\n .slice(0, maxCandidates)\n .map((id) => pool[Number(id.slice(1))])\n .filter(Boolean)\n .map((a) => ({ title: a.title, path: a.path }))\n return picked.length > 0 ? picked : null\n } catch {\n return null\n }\n}\n\n/** Weight of the intent-graph branch match against the text match when\n * shortlisting catalog candidates. Mirrors `graph.retrievalWeights.graph`. */\nexport const DEFAULT_GRAPH_WEIGHT = 0.6\n\n/**\n * Order the catalog pool for a question. Three bands, never mixed:\n *\n * 1. articles the text match scored, ordered by `text * (1 + w * branch)`\n * when the request was classified: the branch reorders text matches\n * but cannot lift an unrelated article above one;\n * 2. articles on the request's branch that the text never matched, by\n * how much of the path they share;\n * 3. the rest, in catalog order.\n *\n * Band 1 comes first in full because the shortlist the reranker sees is\n * finite (DEFAULT_SHORTLIST): a busy category holds more same-branch\n * articles than that, and a blended score let them push the article that\n * actually answers the question out of the list.\n *\n * Exported for tests; the seat and the CLI selector both consume the order.\n */\nexport function rankCatalogPool(\n question: string,\n pool: Array<{ title: string; tags?: string[]; related?: string[]; graphPath?: string[] }>,\n messagePath?: string[],\n graphWeight: number = DEFAULT_GRAPH_WEIGHT,\n): number[] {\n const docs = pool.map((a) =>\n [a.title, (a.tags ?? []).join(\" \"), (a.related ?? []).join(\" \")].join(\" \"),\n )\n const bm25 = scoreAll(question, buildIndex(docs))\n const maxBm25 = bm25.reduce((m, r) => Math.max(m, r.score), 0)\n const text = new Map(bm25.map((r) => [r.docIndex, maxBm25 > 0 ? r.score / maxBm25 : 0]))\n const useGraph = !!messagePath?.length\n const branch = (a: { graphPath?: string[] }) =>\n useGraph && a.graphPath?.length ? ancestryScore(messagePath!, a.graphPath) : 0\n\n const byScore = (x: { i: number; score: number }, y: { i: number; score: number }) => y.score - x.score || x.i - y.i\n const matched = pool\n .map((a, i) => ({ i, score: (text.get(i) ?? 0) * (1 + graphWeight * branch(a)) }))\n .filter((c) => text.has(c.i))\n .sort(byScore)\n const branchOnly = pool\n .map((a, i) => ({ i, score: branch(a) }))\n .filter((c) => !text.has(c.i) && c.score > 0)\n .sort(byScore)\n const ranked = [...matched, ...branchOnly].map((c) => c.i)\n for (let i = 0; i < pool.length; i++) if (!ranked.includes(i)) ranked.push(i)\n return ranked\n}\n\nfunction buildSelectorPrompt(question: string, catalog: string, maxCandidates: number, messagePath?: string[]): string {\n const branch = messagePath?.length\n ? `\\n## Intent\\n\\nThe request was classified under the intent-graph path \"${messagePath.join(\" › \")}\". Prefer articles filed under the same branch when their titles are equally plausible.\\n`\n : \"\"\n return `You are picking candidate articles from a wiki catalog to answer a question. You do NOT answer the question. You pick which articles the answer is likely to come from.\n\n## Question\n\n${question}\n${branch}\n## Catalog (_index.md — articles grouped by type, with wikilink previews)\n\n${catalog}\n\n## Your task\n\nPick up to ${maxCandidates} articles from the catalog that are most likely to answer the question. Prefer:\n- Articles whose title directly names a subject in the question.\n- Articles of the right type (e.g. a \"who owns X\" question → person or project; a \"what happened on DATE\" → event).\n- Articles whose wikilinks suggest they sit at the center of a relevant subgraph.\n\nReturn ONLY valid JSON, no markdown fencing, no prose:\n\n[\n {\"title\": \"Exact Article Title\", \"path\": \"path/from/catalog.md\"},\n ...\n]\n\nIf none of the articles match, return [].`\n}\n\nfunction buildSynthesisPrompt(\n question: string,\n articles: Array<WikiArticle & { hop: number }>,\n): string {\n const articlesBlock = articles\n .map(a => {\n const header = `### ${a.meta.title} — ${a.meta.type || \"untyped\"} (${a.path}) [hop ${a.hop}]`\n const related = a.meta.related?.length ? `Related: ${a.meta.related.join(\", \")}` : \"\"\n return [header, related, \"\", a.content].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n---\\n\\n\")\n\n return `You are answering a question using a small subgraph of wiki articles. The articles were walked from the catalog; trust them over your prior knowledge.\n\n## Question\n\n${question}\n\n## Articles (${articles.length} walked from the catalog)\n\n${articlesBlock}\n\n## Your task\n\nAnswer the question in 2–6 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.\n\nOutput ONLY the answer — no preamble, no \"here is my answer:\", no markdown fencing.`\n}\n\nfunction parseCandidates(raw: string): Array<{ title: string; path: string }> {\n const match = raw.match(/\\[[\\s\\S]*?\\]/)\n if (!match) return []\n try {\n const parsed = JSON.parse(match[0])\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter((x: any) => x && typeof x.title === \"string\" && typeof x.path === \"string\")\n .map((x: any) => ({ title: x.title, path: x.path }))\n } catch {\n return []\n }\n}\n\nasync function runClaude(prompt: string, model: string, timeoutMs: number): Promise<string> {\n // Use stdin via a temp-file pipe to avoid shell-escaping a huge prompt.\n // Prompts can exceed the `-E` arg buffer on macOS, so we always pipe.\n const { writeFileSync, mkdirSync, rmSync } = await import(\"fs\")\n const { tmpdir } = await import(\"os\")\n const dir = resolve(tmpdir(), `agentx-wiki-query-${process.pid}`)\n mkdirSync(dir, { recursive: true })\n const promptPath = resolve(dir, `prompt-${Date.now()}.txt`)\n writeFileSync(promptPath, prompt)\n try {\n const cmd = `cat '${promptPath}' | claude -p - --output-format json --max-turns 1 --model ${model} --disallowedTools \"Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit\"`\n const raw = execSync(cmd, { env: claudeCliEnv(), encoding: \"utf-8\", timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 })\n try {\n const envelope = JSON.parse(raw)\n return String(envelope.result || envelope.content || \"\")\n } catch {\n return raw\n }\n } finally {\n try { rmSync(promptPath, { force: true }) } catch {}\n }\n}\n"],"mappings":"iNAAA,OAAS,gBAAAA,EAAc,cAAAC,MAAkB,KAEzCC,IAWA,OAAS,WAAAC,MAAe,OACxB,OAAS,YAAAC,MAAgB,gBAiEzB,eAAsBC,GACpBC,EACAC,EACAC,EACAC,EAA4B,CAAC,EACA,CAC7B,IAAMC,EAAgBD,EAAK,eAAiB,QACtCE,EAAaF,EAAK,YAAc,SAChCG,EAAgBH,EAAK,eAAiB,EACtCI,EAAUJ,EAAK,SAAW,EAC1BK,EAAcL,EAAK,aAAe,EAClCM,EAAYN,EAAK,WAAa,IAC9BO,EAAMP,EAAK,KAAO,QAAQ,MAAM,KAAK,QAAS,cAAc,EAC5DQ,EAAcR,EAAK,aAAa,OAASA,EAAK,YAAc,OAC5DS,EAAcT,EAAK,aAAeU,EAGlCC,EAAcjB,EAAQI,EAAM,QAAS,WAAW,EACtD,GAAI,CAACc,EAAWD,CAAW,EACzB,OAAOE,EAAY,aA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,EAAa9F,EAAQ6F,EAAK,UAAU,KAAK,IAAI,OAAO,EAC1DJ,EAAcK,EAAYP,CAAM,EAChC,GAAI,CACF,IAAMQ,EAAM,QAAQD,+DAAwEN,6FACtFJ,EAAMnF,EAAS8F,EAAK,CAAE,IAAKC,EAAa,EAAG,SAAU,QAAS,QAASpF,EAAW,UAAW,EAAI,KAAO,IAAK,CAAC,EACpH,GAAI,CACF,IAAMqF,EAAW,KAAK,MAAMb,CAAG,EAC/B,OAAO,OAAOa,EAAS,QAAUA,EAAS,SAAW,EAAE,CACzD,MAAE,CACA,OAAOb,CACT,CACF,QAAE,CACA,GAAI,CAAEO,EAAOG,EAAY,CAAE,MAAO,EAAK,CAAC,CAAE,MAAE,CAAO,CACrD,CACF","names":["readFileSync","existsSync","init_seat","resolve","execSync","agenticQuery","question","store","requesterId","opts","selectorModel","synthModel","maxCandidates","maxHops","maxArticles","timeoutMs","log","messagePath","graphWeight","DEFAULT_GRAPH_WEIGHT","catalogPath","existsSync","emptyResult","catalog","readFileSync","selectorStart","candidates","selectorOutput","viaSeat","selectCandidatesViaSeat","c","runClaude","buildSelectorPrompt","parseCandidates","e","selectorMs","walked","walkSubgraph","synthStart","answer","buildSynthesisPrompt","w","synthesisMs","a","status","_question","error","titleIndex","article","opened","frontier","next","target","path","pool","rankCatalogPool","DEFAULT_SHORTLIST","result","askSeat","WIKI_RERANK_SEAT","rerankState","rerankQuestions","picked","toRanking","id","docs","bm25","scoreAll","buildIndex","maxBm25","m","r","text","useGraph","branch","ancestryScore","byScore","x","y","matched","i","branchOnly","ranked","articles","articlesBlock","header","related","raw","match","parsed","prompt","model","writeFileSync","mkdirSync","rmSync","tmpdir","dir","promptPath","cmd","claudeCliEnv","envelope"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{i as x,k as A}from"./chunk-6FVFD5WU.js";import{a as w,e as D}from"./chunk-2QNT5JDS.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
|
|
2
2
|
`)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-7ZABMMSW.js.map
|