agentix-cli 0.179.0 → 0.181.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-43V7KUZU.js → App-UXX5TGFF.js} +2 -2
- package/dist/{ChatApp-ZG2IXOB5.js → ChatApp-X635NOAE.js} +2 -2
- package/dist/{absorb-eval-4NMMBFH3.js → absorb-eval-4ZPDWNBA.js} +2 -2
- package/dist/{adapter-57X4HJEA.js → adapter-Z23K544D.js} +2 -2
- package/dist/{agent-LP5F5OCL.js → agent-OBRH5BJZ.js} +2 -2
- package/dist/{board-dashboard-J3SNLS2I.js → board-dashboard-KZ43CMZQ.js} +271 -238
- package/dist/board-dashboard-KZ43CMZQ.js.map +1 -0
- package/dist/{chunk-S25OP23O.js → chunk-33DLG4I2.js} +5 -5
- package/dist/{chunk-6FNJ7GQ2.js → chunk-5LPCJZKI.js} +2 -2
- package/dist/{chunk-L7F226TX.js → chunk-5RSTB45Q.js} +2 -2
- package/dist/{chunk-2BI43ZKI.js → chunk-7RVJWLIP.js} +2 -2
- package/dist/{chunk-KPRWATQR.js → chunk-CF7CPE7K.js} +2 -2
- package/dist/{chunk-FZMS4UFL.js → chunk-DUZOHLTF.js} +2 -2
- package/dist/{chunk-XXWSFJFZ.js → chunk-FRVFRWFN.js} +2 -2
- package/dist/{chunk-BCDC7BOQ.js → chunk-HBQRVCLU.js} +2 -2
- package/dist/{chunk-YIR6FABW.js → chunk-HMEFQL5P.js} +2 -2
- package/dist/{chunk-KUZATIJA.js → chunk-IRZYRLXQ.js} +2 -2
- package/dist/{chunk-3VZNOJJK.js → chunk-IYITREE5.js} +2 -2
- package/dist/{chunk-DUWKRQKT.js → chunk-J56YGKUO.js} +2 -2
- package/dist/{chunk-P7FSTC5E.js → chunk-KOY3EOPH.js} +41 -29
- package/dist/chunk-KOY3EOPH.js.map +1 -0
- package/dist/{chunk-T7E33M6T.js → chunk-LZY6YN2J.js} +2 -2
- package/dist/{chunk-FXMUUDSH.js → chunk-NI2XD6P3.js} +2 -2
- package/dist/{chunk-TLSMX7LZ.js → chunk-OYCMFCME.js} +2 -2
- package/dist/{chunk-7NJLRLQN.js → chunk-PCWXHXTM.js} +2 -2
- package/dist/{chunk-CVFQA3TH.js → chunk-SD6UDSXV.js} +2 -2
- package/dist/{chunk-3X2BFCOZ.js → chunk-SDINSYTN.js} +2 -2
- package/dist/{chunk-OHPCZOOM.js → chunk-TZ7GB7FI.js} +2 -2
- package/dist/{chunk-5DJOGAS2.js → chunk-U5S6IP7Z.js} +3 -3
- package/dist/{chunk-RMSB6DKW.js → chunk-UFUQQ5J5.js} +2 -2
- package/dist/{chunk-7WMZJFYD.js → chunk-UHTIZCKU.js} +2 -2
- package/dist/{chunk-QQ3YFYC2.js → chunk-UOIEKYRR.js} +6 -6
- package/dist/{chunk-M4BNVLGJ.js → chunk-VK3M3TVL.js} +2 -2
- package/dist/{chunk-QJKQELHR.js → chunk-WKU7YFDV.js} +2 -2
- package/dist/{chunk-PHT6HTAW.js → chunk-WZUY7VGL.js} +2 -2
- package/dist/{chunk-HYLVA6VA.js → chunk-ZBM24D2Y.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-NJKGG5OP.js → client-ILPJFCTF.js} +2 -2
- package/dist/{config-HILBFLHC.js → config-JVWOL233.js} +2 -2
- package/dist/{config-mutate-SJYPUDP5.js → config-mutate-WYCHP6VK.js} +2 -2
- package/dist/config-mutator-DKNHE6VP.js +2 -0
- package/dist/{contributions-HN3JAPFB.js → contributions-XD66HYWE.js} +2 -2
- package/dist/{doctor-6P5PYFMD.js → doctor-CGZ56DYP.js} +2 -2
- package/dist/{follow-up-tool-MXMT3GED.js → follow-up-tool-HPET6LZW.js} +2 -2
- package/dist/{hub-EBZO3VRY.js → hub-L5FFJPS3.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{program-YXQEKD2W.js → program-XM3X7HIL.js} +23 -23
- package/dist/{promote-M3GWICXS.js → promote-XI6W27JK.js} +2 -2
- package/dist/{query-XBRRKY6I.js → query-MGG5QKNC.js} +2 -2
- package/dist/{query-settings-3UVI3UQF.js → query-settings-CALZYYWD.js} +2 -2
- package/dist/{registry-5YYMCHMF.js → registry-XJWSLJ4O.js} +2 -2
- package/dist/{request-planner-45D32J2H.js → request-planner-JCRGGJUO.js} +2 -2
- package/dist/{review-candidates-VOTQHP2K.js → review-candidates-OEBEEAEZ.js} +2 -2
- package/dist/{routing-SPX5VDTG.js → routing-CGH54RYG.js} +2 -2
- package/dist/schedule-tool-UM3CAPDX.js +2 -0
- package/dist/{scheduler-OVYVZN6N.js → scheduler-2K5YEV2U.js} +2 -2
- package/dist/{seat-4VQ2X5PF.js → seat-DEL5YUOS.js} +2 -2
- package/dist/{select-2QW6SYWW.js → select-MRTWSI7U.js} +2 -2
- package/dist/{set-enabled-API6VRUP.js → set-enabled-XTDCFCZY.js} +2 -2
- package/dist/{sprint-tool-4PLRLWOU.js → sprint-tool-N7WPDX5J.js} +2 -2
- package/dist/{tool-PVFI2DWN.js → tool-BQEJOTF3.js} +2 -2
- package/dist/{tool-CMOZJTA2.js → tool-KZHWJ7BC.js} +2 -2
- package/dist/{tool-XEGKIHUP.js → tool-NZTJZDSB.js} +2 -2
- package/dist/{wiki-3MTKUBPS.js → wiki-YERCKD3E.js} +2 -2
- package/dist/wiki-enrich-K54LGNU3.js +2 -0
- package/package.json +3 -1
- package/dist/board-dashboard-J3SNLS2I.js.map +0 -1
- package/dist/chunk-P7FSTC5E.js.map +0 -1
- package/dist/config-mutator-XGZRKKD4.js +0 -2
- package/dist/schedule-tool-IUUGZFJ3.js +0 -2
- package/dist/wiki-enrich-7KX7YTZ4.js +0 -2
- /package/dist/{App-43V7KUZU.js.map → App-UXX5TGFF.js.map} +0 -0
- /package/dist/{ChatApp-ZG2IXOB5.js.map → ChatApp-X635NOAE.js.map} +0 -0
- /package/dist/{absorb-eval-4NMMBFH3.js.map → absorb-eval-4ZPDWNBA.js.map} +0 -0
- /package/dist/{adapter-57X4HJEA.js.map → adapter-Z23K544D.js.map} +0 -0
- /package/dist/{agent-LP5F5OCL.js.map → agent-OBRH5BJZ.js.map} +0 -0
- /package/dist/{chunk-S25OP23O.js.map → chunk-33DLG4I2.js.map} +0 -0
- /package/dist/{chunk-6FNJ7GQ2.js.map → chunk-5LPCJZKI.js.map} +0 -0
- /package/dist/{chunk-L7F226TX.js.map → chunk-5RSTB45Q.js.map} +0 -0
- /package/dist/{chunk-2BI43ZKI.js.map → chunk-7RVJWLIP.js.map} +0 -0
- /package/dist/{chunk-KPRWATQR.js.map → chunk-CF7CPE7K.js.map} +0 -0
- /package/dist/{chunk-FZMS4UFL.js.map → chunk-DUZOHLTF.js.map} +0 -0
- /package/dist/{chunk-XXWSFJFZ.js.map → chunk-FRVFRWFN.js.map} +0 -0
- /package/dist/{chunk-BCDC7BOQ.js.map → chunk-HBQRVCLU.js.map} +0 -0
- /package/dist/{chunk-YIR6FABW.js.map → chunk-HMEFQL5P.js.map} +0 -0
- /package/dist/{chunk-KUZATIJA.js.map → chunk-IRZYRLXQ.js.map} +0 -0
- /package/dist/{chunk-3VZNOJJK.js.map → chunk-IYITREE5.js.map} +0 -0
- /package/dist/{chunk-DUWKRQKT.js.map → chunk-J56YGKUO.js.map} +0 -0
- /package/dist/{chunk-T7E33M6T.js.map → chunk-LZY6YN2J.js.map} +0 -0
- /package/dist/{chunk-FXMUUDSH.js.map → chunk-NI2XD6P3.js.map} +0 -0
- /package/dist/{chunk-TLSMX7LZ.js.map → chunk-OYCMFCME.js.map} +0 -0
- /package/dist/{chunk-7NJLRLQN.js.map → chunk-PCWXHXTM.js.map} +0 -0
- /package/dist/{chunk-CVFQA3TH.js.map → chunk-SD6UDSXV.js.map} +0 -0
- /package/dist/{chunk-3X2BFCOZ.js.map → chunk-SDINSYTN.js.map} +0 -0
- /package/dist/{chunk-OHPCZOOM.js.map → chunk-TZ7GB7FI.js.map} +0 -0
- /package/dist/{chunk-5DJOGAS2.js.map → chunk-U5S6IP7Z.js.map} +0 -0
- /package/dist/{chunk-RMSB6DKW.js.map → chunk-UFUQQ5J5.js.map} +0 -0
- /package/dist/{chunk-7WMZJFYD.js.map → chunk-UHTIZCKU.js.map} +0 -0
- /package/dist/{chunk-QQ3YFYC2.js.map → chunk-UOIEKYRR.js.map} +0 -0
- /package/dist/{chunk-M4BNVLGJ.js.map → chunk-VK3M3TVL.js.map} +0 -0
- /package/dist/{chunk-QJKQELHR.js.map → chunk-WKU7YFDV.js.map} +0 -0
- /package/dist/{chunk-PHT6HTAW.js.map → chunk-WZUY7VGL.js.map} +0 -0
- /package/dist/{chunk-HYLVA6VA.js.map → chunk-ZBM24D2Y.js.map} +0 -0
- /package/dist/{client-NJKGG5OP.js.map → client-ILPJFCTF.js.map} +0 -0
- /package/dist/{config-HILBFLHC.js.map → config-JVWOL233.js.map} +0 -0
- /package/dist/{config-mutate-SJYPUDP5.js.map → config-mutate-WYCHP6VK.js.map} +0 -0
- /package/dist/{config-mutator-XGZRKKD4.js.map → config-mutator-DKNHE6VP.js.map} +0 -0
- /package/dist/{contributions-HN3JAPFB.js.map → contributions-XD66HYWE.js.map} +0 -0
- /package/dist/{doctor-6P5PYFMD.js.map → doctor-CGZ56DYP.js.map} +0 -0
- /package/dist/{follow-up-tool-MXMT3GED.js.map → follow-up-tool-HPET6LZW.js.map} +0 -0
- /package/dist/{hub-EBZO3VRY.js.map → hub-L5FFJPS3.js.map} +0 -0
- /package/dist/{program-YXQEKD2W.js.map → program-XM3X7HIL.js.map} +0 -0
- /package/dist/{promote-M3GWICXS.js.map → promote-XI6W27JK.js.map} +0 -0
- /package/dist/{query-XBRRKY6I.js.map → query-MGG5QKNC.js.map} +0 -0
- /package/dist/{query-settings-3UVI3UQF.js.map → query-settings-CALZYYWD.js.map} +0 -0
- /package/dist/{registry-5YYMCHMF.js.map → registry-XJWSLJ4O.js.map} +0 -0
- /package/dist/{request-planner-45D32J2H.js.map → request-planner-JCRGGJUO.js.map} +0 -0
- /package/dist/{review-candidates-VOTQHP2K.js.map → review-candidates-OEBEEAEZ.js.map} +0 -0
- /package/dist/{routing-SPX5VDTG.js.map → routing-CGH54RYG.js.map} +0 -0
- /package/dist/{schedule-tool-IUUGZFJ3.js.map → schedule-tool-UM3CAPDX.js.map} +0 -0
- /package/dist/{scheduler-OVYVZN6N.js.map → scheduler-2K5YEV2U.js.map} +0 -0
- /package/dist/{seat-4VQ2X5PF.js.map → seat-DEL5YUOS.js.map} +0 -0
- /package/dist/{select-2QW6SYWW.js.map → select-MRTWSI7U.js.map} +0 -0
- /package/dist/{set-enabled-API6VRUP.js.map → set-enabled-XTDCFCZY.js.map} +0 -0
- /package/dist/{sprint-tool-4PLRLWOU.js.map → sprint-tool-N7WPDX5J.js.map} +0 -0
- /package/dist/{tool-PVFI2DWN.js.map → tool-BQEJOTF3.js.map} +0 -0
- /package/dist/{tool-CMOZJTA2.js.map → tool-KZHWJ7BC.js.map} +0 -0
- /package/dist/{tool-XEGKIHUP.js.map → tool-NZTJZDSB.js.map} +0 -0
- /package/dist/{wiki-3MTKUBPS.js.map → wiki-YERCKD3E.js.map} +0 -0
- /package/dist/{wiki-enrich-7KX7YTZ4.js.map → wiki-enrich-K54LGNU3.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ba as ao,Da as co,G as Jr,N as Ot,O as zr,V as Dt,X as Qr,a as Rr,b as _r,d as $n,f as Ye,ha as Xr,i as Br,ia as Yr,j as Wr,ja as Zr,k as Pt,la as Vr,ma as eo,n as Et,na as to,oa as no,q as qr,r as Gr,ra as so,sa as ro,v as Kr,va as oo,wa as io}from"./chunk-
|
|
1
|
+
import{Ba as ao,Da as co,G as Jr,N as Ot,O as zr,V as Dt,X as Qr,a as Rr,b as _r,d as $n,f as Ye,ha as Xr,i as Br,ia as Yr,j as Wr,ja as Zr,k as Pt,la as Vr,ma as eo,n as Et,na as to,oa as no,q as qr,r as Gr,ra as so,sa as ro,v as Kr,va as oo,wa as io}from"./chunk-VK3M3TVL.js";import{b as Pr}from"./chunk-MEFPXHQJ.js";import{a as Rn}from"./chunk-W4YR2RO2.js";import{a as Mr}from"./chunk-VJVXEVZ7.js";import{b as Or,c as Mn,d as Lr,e as _t,h as Nr}from"./chunk-SD6UDSXV.js";import{h as Ar,i as Cr}from"./chunk-BE64IJWM.js";import{a as An,b as Er}from"./chunk-J3SOEFRE.js";import{a as Cn,b as Dr}from"./chunk-SIU6STB2.js";import{e as Ur,i as Fr,j as Hr,k as jr}from"./chunk-X5C5W3E4.js";import{a as $r}from"./chunk-HBQRVCLU.js";import{g as kr,h as vr}from"./chunk-IYITREE5.js";import{c as lr,f as gr}from"./chunk-J56YGKUO.js";import{s as dr,v as Rt,w as ur,y as be,z as vn}from"./chunk-NI2XD6P3.js";import{a as Xe,b as Oe,f as Mt}from"./chunk-72SZI2UW.js";import{a as Ee,b as xn}from"./chunk-FCPTN6NF.js";import{a as pr,c as fr}from"./chunk-MYVHVJWZ.js";import{e as De,h as mr,i as Ce}from"./chunk-QUFIUXMQ.js";import{a as hr,b as yr,c as wr,d as br,l as xr}from"./chunk-AV7T3SYT.js";import{a as Sr,b as Tr}from"./chunk-LE3BXIUF.js";import{c as Ir}from"./chunk-BERWTVG2.js";import{c as Ys,d as Zs}from"./chunk-QOYAX2FT.js";import{e as Ae}from"./chunk-DSYKYZMT.js";import{Ca as sr,Ha as Kc,Na as rr,Oa as kn,Pa as or,Qa as Qe,Ra as ir,Sa as ar,Ya as cr,ua as nr,xa as Tn,yb as Jc,za as Gc}from"./chunk-KOY3EOPH.js";import{g as ze,h as Wc}from"./chunk-VJ5HC63R.js";import{j as In,r as qc}from"./chunk-UEEB3UTU.js";import{a as Vs,b as pe,c as er,d as tr,e as Sn}from"./chunk-VQRY4IDI.js";vn();Mt();var Lt="tool-set",uo=["answer","code","full"],lo={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},zc=.1;function po(n){return{task:go(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:go(n.agentPrompt,600)}:{}}}var fo={bundle:Oe({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function mo(n,e=zc){let s=n?.bundle?.probabilities;if(!s)return"full";let r=_n(s.answer),o=_n(s.code),i=_n(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function ho(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>lo.answer.includes(t))?"answer":e.every(t=>lo.code.includes(t))?"code":"full"}function yo(n,e){return uo.indexOf(n)<uo.indexOf(e)}function _n(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function go(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var wo=!1;function bo(n,e){let t=Rt(Lt);if(t!=="off")return t==="active"&&!wo&&(wo=!0,e(`[decisions] seat "${Lt}" is set to active, but only shadow is built: it records and changes nothing`)),be(Lt,po(n),fo,{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=mo(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function xo(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=ho(r);ur(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}`+(yo(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}function Qc(n,e){return!n||n<=0||!e||e<=0?10:Math.min(200,Math.max(1,Math.round(e/n)))}function So(n,e){let t=Qc(n.contextTokens,n.turnInputTokens),s=n.idleMs<e.cacheTtlMinutes*6e4,r=.1*(t-1),o=e.freshTokens*(e.cacheWriteFactor+r),i=n.contextTokens;if(!i||i<=0)return{rotate:!1,resumeCost:null,freshCost:o,warm:s,requestsPerTurn:t};let a=i*((s?.1:e.cacheWriteFactor)+r);return{rotate:a>o*e.margin,resumeCost:a,freshCost:o,warm:s,requestsPerTurn:t}}function Pn(n){let e=s=>`${Math.round(s/1e3)}k`,t=n.warm?"warm cache":"cold cache";return n.resumeCost===null?`resume: no context reading (${t})`:`${n.rotate?"start fresh":"resume"}: resume \u2248${e(n.resumeCost)}, fresh \u2248${e(n.freshCost)} input-token equivalents (${t}, ${n.requestsPerTurn} requests/turn)`}vn();Mt();var Io="session-continuity",To={continues:Xe("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:Xe("Does the new request refer to something stated earlier in the conversation?")};function ko(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 vo(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 Gt}from"execa";import{spawn as Xc}from"node:child_process";import{createHash as Yc}from"node:crypto";import{createInterface as Zc}from"node:readline";var xe=class extends Error{},Vc=n=>Xc("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),On=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(),Zc({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()}},Dn=class{constructor(e=Vc,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=Yc("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([h],[P])=>h.localeCompare(P))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new xe("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 h=[...this.entries].find(([,P])=>!P.connection.busy);if(!h)throw new xe("Codex warm process capacity reached");h[1].connection.close(),this.entries.delete(h[0])}try{r={fingerprint:s,connection:new On(e,this.launchProcess)}}catch{throw new xe("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,d="",c,u,l,p,m=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),C=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 h={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",{...h,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(C),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let O=new Promise((A,_)=>{i.failTurn=_,i.notify=(M,N)=>{if(N?.threadId!==u)return;let L=N.item,W={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:M.replace("/","."),...L?{item:{...L,type:W[L.type]||L.type}}:{}}),M==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(c=L.text),M==="item/agentMessage/delta"&&(m||(m=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),d+=N.delta,e.onDelta?.(N.delta,d)),M==="thread/tokenUsage/updated"){let F=N.tokenUsage.last;p=F.inputTokens;let q=F.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(F.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(F.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(F.cacheWriteInputTokens||0)}}M==="turn/completed"&&(N.turn.status==="completed"?A():_(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return O.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await O,{content:c??d,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:p,duration:Date.now()-t}}catch(h){if(i.close(),!a&&!e.signal?.aborted)throw new xe(h.message);return{content:d,codexSessionId:u,usage:l,contextTokens:p,error:h.message,duration:Date.now()-t}}finally{clearTimeout(C),clearTimeout(b),e.signal?.removeEventListener("abort",y),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},$o=new Dn;import{execFile as Sd}from"child_process";import{StringDecoder as nt}from"string_decoder";import{mkdtempSync as qo,readFileSync as Go,rmSync as Ko}from"fs";import{join as Wt}from"path";import{tmpdir as Jo}from"os";function Nt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let c=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${c?` Resets ${c[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),d=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||d===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||d===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||d===529||d===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||d===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:d&&d>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${d}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function Ut(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function Ft(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,d=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&d>s)&&(e=r,t=a,s=d)}return e}var Ao=null;function Ht(){return Ao}function qp(n){Ao=n}function Ze(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function ed(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 Le=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},Co=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=Ze(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=ed(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 Le(`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 Le(`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=Ze(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=Ze(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Ze(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=Ze(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(d){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${d?.message||d}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let d=r.claudeMdHash??"unmarked",c=a??"unmarked";s.kill(`claude-md drifted (${d} \u2192 ${c})`),this.cfg.log(`[process-registry] killed drifted ${t} (${d} \u2192 ${c})`)}}}}}};import{spawn as td}from"child_process";import{randomUUID as nd}from"crypto";import{existsSync as sd,readFileSync as rd}from"fs";import{resolve as od}from"path";function id(n){let e=od(n,"CLAUDE.md");if(!sd(e))return null;try{let t=rd(e,"utf8");return xr(t)}catch{return null}}var ad=20*60*1e3,cd=5e3,Ve=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},et=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function dd(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 Mo=class{constructor(e={}){this.opts=e}spawn(e,t){return new Ln(e,t,this.opts)}},Ln=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=td(r,o,{cwd:t.workspace,env:Ce(dd({...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:id(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let d=this.waiters.splice(0);for(let c of d)c(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(m=>{t=m}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=nd(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let d=e.deadlineMs??ad,c=o+d,u=()=>(this.kill(`turn deadline (${Math.round(d/6e4)}m)`),new Ve(d)),l=!1,p=null;try{for(;;){let m=c-Date.now();if(m<=0)throw u();let y=await this.nextEvent(m);if(y===null&&this.killReason)throw new et(this.killReason);if(y===null&&!this.exited)throw u();if(y===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(y.type==="user"&&y.uuid===i)l=!0,p&&(yield{type:p.type,raw:p});else if(y.type==="system"&&y.subtype==="init")p=y;else if(y.type==="result"){p=null;let b=typeof y.result=="string"?y.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${b.length} chars): ${b.slice(0,120)}`)}continue}if(yield{type:y.type,raw:y},y.type==="result"){this.onResultEvent(y);return}}}finally{let m=this.snap.state==="busy";this.snap={...this.snap,...m?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},cd);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"}}};Sn();qc();xn();import{resolve as Ro,join as _o}from"path";var ud=4e3;function jt(n){try{let e=_o(Ro(n.root),".agentx","db.sqlite"),t=In({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ee(),r=n.input.command?n.input.command.slice(0,ud):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -31,7 +31,7 @@ ${n}`}function Td(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
31
31
|
`,l)}};A.stdout?.on("data",T=>{L+=F.write(T);let x=L.split(`
|
|
32
32
|
`);L=x.pop()||"";for(let U of x)X(U)}),A.stderr?.on("data",T=>{W+=q.write(T)});let v=await A;if(i&&i.removeEventListener("abort",N),L+=F.end(),L.trim()&&X(L),W+=q.end(),_)return{content:"",error:M||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d,opencodeSessionId:m};if(v.exitCode!==0||y){let T=v,x;return T.timedOut?x=`OpenCode timed out after ${Math.round(P/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:y?x=y:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+W)?x=jo():x=W.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...Z(x),duration:Date.now()-d,usage:p,opencodeSessionId:m}}return C=!1,{content:l.trim(),duration:Date.now()-d,usage:p,billedModel:e.model||n.model,opencodeSessionId:m}}catch(P){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d};let O=/ENOENT|spawn opencode/i.test(P?.message||"")?jo():P?.message;return{content:l,...Z(O||"OpenCode failed"),duration:Date.now()-d,usage:p,opencodeSessionId:m}}finally{h?.(),b?.release(C)}}async function Od(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=Se(n,e,s),d="",c=i({prompt:a,options:{model:e.model||n.model,cwd:e.cwd??n.workspace,permissionMode:"bypassPermissions"}});for await(let u of c)u.type==="result"&&u.subtype==="success"&&(d=u.result||"");return{content:d,duration:Date.now()-r}}catch(o){return{content:"",...Z(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Dd(n,e,t,s,r,o,i,a,d){let c=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,p=!1,m=()=>{let C=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(C))}catch{}};a&&(a.aborted?m():a.addEventListener("abort",m,{once:!0}));let y=setTimeout(()=>{p=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);y.unref?.();let b=()=>({content:"",...Z(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-c});try{let C=n.provider||"claude-code",h=s?`${s}
|
|
33
33
|
|
|
34
|
-
${e.message}`:e.message,P=e.context?.sender,O=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&O?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=br(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-
|
|
34
|
+
${e.message}`:e.message,P=e.context?.sender,O=typeof P=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(P),A=e.context?.channel==="web-chat"&&O?{userId:P,agentId:e.agentId||"acme-public"}:void 0,_=br(n),M=Object.keys(_).length>0,N={task:h,cwd:e.cwd??n.workspace,provider:C,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:l.signal,mcpServers:M?_:void 0};if(r){let{generateStream:X}=await import("./agent-OBRH5BJZ.js"),v="",T,x,U,j;for await(let E of X(N)){if(d)try{d(E)}catch{}if(E.type==="text_delta")v+=E.text,r(E.text,v);else if(E.type==="thinking_delta")E.text&&i&&i(E.text);else if(E.type==="generate_result"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}T=E.result.tokensUsed,E.result.inputTokens!=null&&(x=E.result.inputTokens),E.result.outputTokens!=null&&(U=E.result.outputTokens)}else if(E.type==="done"){if(E.result.content&&E.result.content!==v){let J=E.result.content.slice(v.length);J?(v=E.result.content,r(J,v)):v=E.result.content}E.result.tokensUsed!=null&&(T=E.result.tokensUsed)}else E.type==="error"&&(j=E.error)}return j&&!v?p?b():j==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${j}`),duration:Date.now()-c}:((x===void 0||U===void 0)&&T&&(x=Math.round(T*.7),U=T-x),{content:v||"Done.",tokensUsed:T,usage:x!==void 0||U!==void 0?{inputTokens:x||0,outputTokens:U||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c})}let{generate:L}=await import("./agent-OBRH5BJZ.js"),W=await L(N),F=W.inputTokens,q=W.outputTokens;if((F===void 0||q===void 0)&&W.tokensUsed){let X=W.tokensUsed;F=Math.round(X*.7),q=X-F}return{content:W.content||"Done.",tokensUsed:W.tokensUsed,usage:F!==void 0||q!==void 0?{inputTokens:F||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-c}}catch(C){return p?b():C?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c}:{content:"",...Z(`Orchestrator error: ${C.message}`),duration:Date.now()-c}}finally{clearTimeout(y),a&&a.removeEventListener("abort",m)}}var Un=class{open=new Set;observe(e){e?.type!=="system"||typeof e.task_id!="string"||(e.subtype==="task_started"&&e.is_backgrounded!==!1?this.open.add(e.task_id):e.subtype==="task_notification"&&this.open.delete(e.task_id))}get pending(){return this.open.size}},Ld=1e3;async function Nd(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"}),Ld),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 Ud(n,e,t,s,r,o,i){let a=Ht();if(!a)return null;let d=Date.now(),{channel:c,chatId:u}=Jt(e.context),l={agentId:e.agentId,channel:c,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let p,m=!1;try{let v=a.list().length;p=a.acquire(l,{agentId:e.agentId,channel:c,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),m=a.list().length>v}catch(v){return v instanceof Le,null}m&&Bn(e.agentId,n,e.model,s,"persistent");let y=Se(n,e,t),b="",C,h,P,O,A,_,M,N="",L="",W=v=>{if(!i||!v)return;let T;if(L&&v.startsWith(L)?T=v.slice(L.length):T=N&&!N.endsWith(`
|
|
35
35
|
`)?`
|
|
36
36
|
|
|
37
37
|
${v}`:v,L=v,!!T){N+=T;try{i(T,N)}catch{}}},F=!1,q=()=>{F=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let X=!1;try{let v=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of p.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:v})){if(X=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let x=T.raw.message?.content??[];for(let j of x)j.type==="text"&&typeof j.text=="string"?(b=j.text,W(j.text)):j.type==="tool_use"&&(L="");let U=T.raw.message?.usage;if(U){let j=(U.input_tokens||0)+(U.cache_read_input_tokens||0)+(U.cache_creation_input_tokens||0);j>0&&(O=j)}}if(T.type==="result"){let x=T.raw;if(x.is_error){let U=Z(typeof x.result=="string"?x.result:"claude error");C=U.error,h=U.errorKind}else typeof x.result=="string"&&x.result.length>0&&(b=x.result,N||W(x.result));typeof x.session_id=="string"&&(M=x.session_id),x.usage&&(P={inputTokens:x.usage.input_tokens||0,outputTokens:x.usage.output_tokens||0,cacheReadTokens:x.usage.cache_read_input_tokens||0,cacheCreateTokens:x.usage.cache_creation_input_tokens||0}),typeof x.num_turns=="number"&&(A=x.num_turns),typeof x.message?.model=="string"?_=x.message.model:typeof x.model=="string"?_=x.model:_=Ft(x.modelUsage)||_}}}catch(v){if(F)C="task cancelled by operator",h="cancelled";else if(X)if(v instanceof et)C=`Claude Code was stopped mid-turn (${v.reason}), before its time limit`,h="interrupted";else if(v instanceof Ve){let T=Z(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);C=T.error,h=T.errorKind}else{let T=Z(`persistent claude process error: ${v?.message||String(v)}`);C=T.error,h=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return F&&!C&&(C="task cancelled by operator",h="cancelled"),{content:F?"":b,error:C,errorKind:h,duration:Date.now()-d,usage:P,contextTokens:O,numTurns:A,billedModel:_,claudeSessionId:M}}function si(n){let e=pe(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?Oo(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Fo(t.args,n.taskId,n.agentId)}function Fd(n){return pe(n.autonomy)||!!n.personLimits}async function Hd(n,e,t,s,r,o,i){let a=pe(e.autonomy)?e.autonomy:void 0,d=a&&Do(a,n.tier)||e.personLimits&&Ho(n.tier);if(d)return{content:"",error:d,...a?{autonomy:a}:{}};let c=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:c,message:a?`${tr(a)}
|
|
@@ -164,7 +164,7 @@ ${b}`,timeLimitRequest:b,timeLimitContinuation:u.continuation,timeLimitStartedAt
|
|
|
164
164
|
${e.message}`),e.queuedAt=void 0}let b=ki({message:e.message,home:e.context?.home}),C=Ti(c.runningTasks,b,{channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group});C&&(this.log(`[${e.agentId}] ${C.slice(0,160)}`),e.message=`${C}
|
|
165
165
|
${e.message}`),c.activeTasks++,c.totalTasks++,c.lastActive=new Date;let h={...b.length?{homes:b}:{},id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date,...e.autonomy?{autonomy:e.autonomy}:{},...e.workflowRunId?{workflow:{runId:e.workflowRunId}}:{}};c.runningTasks.push(h),e.runningTaskId=h.id;let P=kn(this.config.people,e.context);if(e.context&&(P?e.context.person=P.id:delete e.context.person),this.runningContexts.set(h.id,e.context??{}),e.onStart)try{e.onStart(h.id)}catch{}let O=new AbortController;this.taskAborts.set(h.id,{agentId:e.agentId,channel:h.channel,chatId:typeof h.chatId=="string"?h.chatId:"",originalMessage:e.message||"",controller:O,sender:e.context?.sender,rootId:_t()?.rootId,workflowRunId:e.workflowRunId??(typeof h.chatId=="string"&&h.chatId.startsWith("workflow:")&&h.chatId.slice(9)||void 0),origin:e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}});let A={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(h.id,A);let _=g=>{if(g){A.buffer+=g,A.buffer.length>lc&&(A.buffer=A.buffer.slice(A.buffer.length-lc));for(let f of A.subscribers)try{f(g)}catch{}}},M=Ee();e.taskId=M,h.traceId=M;let N=this.taskAborts.get(h.id);N&&(N.traceId=M);let L=new Map,W=(g,f,k)=>{try{V().emit("task:step",{taskId:M,agentId:e.agentId,name:"pipeline",action:g,status:k,ms:Date.now()-f,at:new Date().toISOString()})}catch{}},F=0,q=!1,X=()=>{q||(q=!0,F&&W("first-event",F,"ok"))},v;if(t){let g=Cp();v=f=>{X();let k=g(f);if(k&&_(k),fc(M,e.agentId,f),pc(L,f),Zn(f,void 0,e.model||c.def.model),r)try{r(f)}catch{}}}else v=g=>{if(X(),fc(M,e.agentId,g),pc(L,g),Zn(g,void 0,e.model||c.def.model),r)try{r(g)}catch{}};let T=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,x=T?setTimeout(()=>O.abort(new Error(`timed out after ${Math.round(T/1e3)}s`)),T):void 0;x?.unref?.();let U=(c.def.preSpawnTimeoutSec??bp)*1e3,j=setTimeout(()=>{O.abort(new Error(`timed out before spawn after ${Math.round(U/1e3)}s in step "${h.step??"start"}"`))},U);j.unref?.();let E=()=>{j&&clearTimeout(j),j=void 0},J=()=>`task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`,re;O.signal.addEventListener("abort",()=>{let g=Pe(O.signal).message;/^timed out/.test(g)&&(re=h.step??"start"),this.log(`[${e.agentId}] task ${h.id} aborted in step "${h.step??"start"}" \u2014 ${g} ${J()}`)},{once:!0});let ee=g=>{h.step=g,this.log(`[${e.agentId}] step ${g} ${J()}`)},R=(g,f,k=0)=>{if(O.signal.aborted)return Promise.reject(Pe(O.signal));ee(g),(g==="agent"||g==="workflow-auto-run")&&(E(),F=Date.now());let I=Date.now(),B=Ea(f(),gp[g]??0,g);return Pa(B,O.signal,k).then(G=>(W(g,I,"ok"),G),G=>{throw W(g,I,"error"),G instanceof Be&&this.log(`[${e.agentId}] ${G.message}; continuing without it ${J()}`),G})},te=async(g,f,k,I=0)=>{try{return await R(g,f,I)}catch(B){if(B instanceof Be)return k();throw B}},ie=!1,un=!1,ws=g=>{if(!(!ie||un)){un=!0;try{V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-h.startedAt.getTime(),error:g?.error||(O.signal.aborted?Pe(O.signal).message:"run ended before completion"),errorKind:g?.errorKind,interrupted:this.interruptedRuns.has(h.id)?!0:void 0,stopped:!this.interruptedRuns.has(h.id)&&(this.stoppedRuns.has(h.id)||g?.errorKind==="stopped")?!0:void 0,at:new Date().toISOString()})}catch{}}},bs=!1,xs=g=>{if(bs)return;bs=!0,ws(g),this.runReleases.delete(h.id),x&&clearTimeout(x),E(),c.activeTasks--;let f=c.runningTasks.findIndex(I=>I.id===h.id);f!==-1&&c.runningTasks.splice(f,1),this.runningContexts.delete(h.id),this.taskAborts.delete(h.id);let k=this.runEndWaiters.get(h.id);this.runEndWaiters.delete(h.id);for(let I of k??[])try{I()}catch{}A.done=!0,A.endedAt=new Date;for(let I of A.subscribers)try{I(`
|
|
166
166
|
[task finished]
|
|
167
|
-
`)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),yp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(h.id)||g?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:g?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,xs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:yc,selectRequestContext:wc}=await import("./request-planner-45D32J2H.js"),Ss=te("request-gate",()=>yc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),ln=!1;Ss.then(()=>{ln=!0},()=>{ln=!0});let S=l,gn=e.context?.sender||"User",ue=c.def.tier==="codex-cli",Ge=sa(this.config.session,w,c.def.tier),ft=ra(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&ft.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let mt=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let bc=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(g=>g.role==="agent")?.content;Ra({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:bc,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,gn,e.message);let Is=Date.now(),Ts={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Is).toISOString(),taskId:M,resumeOrigin:mi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Tn(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:nr(e.context),operator:sr(e.context),dueAt:_a(e.context),taskType:on(e.context)};V().emit("task:started",Ts),ie=!0;let ne,pn,ks=this.classifier;if(ks&&w!=="a2a"&&!ue){ee("classify");let g=Date.now();pn=ks.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",g,"error")})}let vs=async g=>{if(!pn)return;let f;await Promise.race([pn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await vs(ip);let Te=this.config.workflows?.matching,he,$s,As=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&As?.enabled&&(As.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&($s=Qr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Xr(this.config.workflows,e.agentId)&&Yr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?lp():void 0,xc=ae?Zr(ae):void 0,Sc=this.wikiHub.getAgentWiki(e.agentId),Cs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Ms=this.memoryStore.buildContext(Cs),Rs=this.memoryStore.contextFacts(Cs),Ic=this.patternStore.findRelevant(e.message,e.agentId,5),Tc=this.patternStore.buildContext(Ic),_s="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>g(c.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;_s=f(B,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,mt)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let g=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=So({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:mt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${Pn(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${Pn(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,c,w,S,g),()=>!1)&&(H=void 0)}try{let g=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let I=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let kc=process.env.AGENTX_CONTEXT_SURGERY==="1",vc=ue?{maxMessages:8,maxChars:2400}:kc&&uc(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,$c=!H&&!ue?vp(Sc,e.agentId,{notesInbox:kp(this.config)}):void 0,ht=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,vc):void 0,Ac=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,Ps,Es=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ps=rs(f),Es=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=ht===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${ht.length}c/${ht.split(`
|
|
167
|
+
`)}catch{}A.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(h.id),yp).unref?.();try{let I=A.endedAt,B={id:h.id,agentId:e.agentId,channel:h.channel,chatId:h.chatId,sender:h.sender,message:e.message||"",startedAt:h.startedAt.toISOString(),endedAt:I.toISOString(),durationMs:I.getTime()-h.startedAt.getTime(),ok:!g?.error,error:g?.error,...this.stoppedRuns.has(h.id)||g?.errorKind==="stopped"?{status:"stopped"}:re?{status:"timeout",step:re}:{},responseText:g?.content||"",transcript:A.buffer};this.persistTaskRecord(B);let G=(B.responseText||B.error||"").trim();if(G){let Q=G.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:I,ok:B.ok})}}catch(I){this.log(`[${e.agentId}] task history persist failed: ${I?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(I=>{if(I.length===0)return;this.log(`[${e.agentId}] flushing ${I.length} queued message(s) after task=${h.id} chat=${u}:${l} at=${new Date().toISOString()}`);let B=Date.now();V().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,count:I.length,at:new Date().toISOString()});let G=()=>V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:B,at:new Date().toISOString()});for(let Q of I){let $e=Q.originalContext||{channel:Q.channel,sender:Q.sender,chatId:Q.chatId};this.execute({message:Q.text,agentId:e.agentId,context:$e,queuedAt:Q.queuedAt??Q.timestamp}).then(ye=>(Ye(ye.error)||G(),this.postQueuedResponseToChannel(e.agentId,$e,ye)),ye=>{throw G(),ye}).catch(ye=>{this.log(`[${e.agentId}] queued message failed: ${ye.message}`)})}}).catch(I=>{V().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${I.message}`)})};this.runReleases.set(h.id,xs),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${c.activeTasks}/${c.def.maxConcurrent}) ${J()}`);let w=e.context?.channel||"api",{evaluateRequest:yc,selectRequestContext:wc}=await import("./request-planner-JCRGGJUO.js"),Ss=te("request-gate",()=>yc(e.message,e.agentId,w),()=>({active:!1,preprocess:!1})),ln=!1;Ss.then(()=>{ln=!0},()=>{ln=!0});let S=l,gn=e.context?.sender||"User",ue=c.def.tier==="codex-cli",Ge=sa(this.config.session,w,c.def.tier),ft=ra(this.config.session),le=e.isolated===!0,Ke=!le&&Ge==="lean"&&ft.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,w,S),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${w}:${S}`),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}));let mt=this.sessions.sessionIdleMs(e.agentId,w,S);e.freshSession||await te("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,w,S,e.seedHistory),()=>{});let bc=[...this.sessions.getSession(e.agentId,w,S).messages].reverse().find(g=>g.role==="agent")?.content;Ra({agent:e.agentId,channel:w,chatId:S,message:e.message,previousReply:bc,taskId:M}),this.sessions.addUserMessage(e.agentId,w,S,gn,e.message);let Is=Date.now(),Ts={agentId:e.agentId,channel:w,chatId:S,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(Is).toISOString(),taskId:M,resumeOrigin:mi(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Tn(e.context),...P?{person:P}:{},humanRoot:ze(e.context),pickup:nr(e.context),operator:sr(e.context),dueAt:_a(e.context),taskType:on(e.context)};V().emit("task:started",Ts),ie=!0;let ne,pn,ks=this.classifier;if(ks&&w!=="a2a"&&!ue){ee("classify");let g=Date.now();pn=ks.classify({text:e.message,channel:w,sender:e.context?.sender,chatId:S,agentId:e.agentId}).then(f=>{ne=f||void 0,ne?.path?.length&&(h.intentPath=ne.path.slice()),W("classify",g,"ok")},f=>{this.log(`[classifier] classify failed for ${e.agentId}: ${f?.message||f}`),W("classify",g,"error")})}let vs=async g=>{if(!pn)return;let f;await Promise.race([pn,new Promise(k=>{f=setTimeout(k,g),f.unref?.()})]),f&&clearTimeout(f)};await vs(ip);let Te=this.config.workflows?.matching,he,$s,As=this.config.workflows?.followUp;if(this.config.workflows?.enabled&&As?.enabled&&(As.agents[e.agentId]??!0)&&!i&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=(Te?.suggestThreshold??.65)&&($s=Qr(f.workflow))}catch(g){this.log(`[${e.agentId}] workflow hint failed (non-fatal): ${g?.message||g}`)}if(this.config.workflows?.enabled&&Te?.enabled&&!i)try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list());f&&f.confidence>=Te.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${f.workflow.id} confidence=${f.confidence.toFixed(2)} mode=${Te.mode} reasons=${f.reasons.join(",")||"n/a"}`),Te.mode==="auto"&&f.confidence>=Te.autoRunThreshold&&(this.workflowAutoRunner?he={workflowId:f.workflow.id,confidence:f.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let ke=Xr(this.config.workflows,e.agentId)&&Yr(e)?this.workflowRuns:void 0;if(ke&&!he&&!i&&this.workflowAutoRunner&&ze(e.context))try{let g=new Ot({baseDir:K(process.cwd(),this.config.workflows.dir)}),f=Dt({agentId:e.agentId,channel:w,message:e.message,intentPath:ne?.path},g.list()),k=Te?.autoRunThreshold??.85;f&&f.confidence>=k&&(he={workflowId:f.workflow.id,confidence:f.confidence,follow:!0},this.log(`[${e.agentId}] workflows.required: saved workflow ${f.workflow.id} fits (confidence=${f.confidence.toFixed(2)})`))}catch(g){this.log(`[${e.agentId}] workflows.required matcher failed (non-fatal): ${g?.message||g}`)}let ae=ke?lp():void 0,xc=ae?Zr(ae):void 0,Sc=this.wikiHub.getAgentWiki(e.agentId),Cs=this.memoryStore.findRelevant(e.message,e.agentId,ue?3:8),Ms=this.memoryStore.buildContext(Cs),Rs=this.memoryStore.contextFacts(Cs),Ic=this.patternStore.findRelevant(e.message,e.agentId,5),Tc=this.patternStore.buildContext(Ic),_s="";if(!ue)try{let{loadLocalSkills:g,getAutoInjectSkills:f}=await import("./loader-YFVSSYSL.js"),k=await R("skills",()=>g(c.def.workspace)),I=e.personLimits?.skills??[],B=I.length?k.filter(G=>!I.some(Q=>Qe(Q,G.frontmatter.name))):k;_s=f(B,e.message)}catch{}let H=c.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,w,S):c.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,w,S):c.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,w,S):void 0;if(H&&this.sessions.isSessionStale(e.agentId,w,S,mt)&&(this.log(`[${e.agentId}] session stale for ${w}:${S}, starting fresh`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"stale"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"stale",at:new Date().toISOString()}),H=void 0),H&&this.sessions.shouldRotateByTierTwo(e.agentId,w,S)){let g=this.sessions.getLastTurnContextTokens(e.agentId,w,S);this.log(`[${e.agentId}] tier-2 rotation for ${w}:${S} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(w)})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),H=void 0}if(H&&this.sessions.shouldRotateByTurns(e.agentId,w,S)){let g=this.sessions.getTurnCount(e.agentId,w,S);this.log(`[${e.agentId}] max-turns rotation for ${w}:${S} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),c.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"max-turns",at:new Date().toISOString()}),H=void 0}if(H&&c.def.tier==="claude-code"){let g=this.config.session?.resumeGate;if(g&&g.mode!=="off"){let f=So({contextTokens:this.sessions.getRawLastTurnContextTokens(e.agentId,w,S),turnInputTokens:this.sessions.getLastTurnInputTokens(e.agentId,w,S),idleMs:mt??0},g);if(f.rotate&&g.mode==="active"){this.log(`[${e.agentId}] cost rotation for ${w}:${S}: ${Pn(f)}`),this.captureRotationMemoAsync(e.agentId,c.def,H,w,S,"cost");let k=this.sessions.getLastTurnInputTokens(e.agentId,w,S);this.sessions.clearClaudeSessionId(e.agentId,w,S),V().emit("session:rotated",{agentId:e.agentId,channel:w,chatId:S,reason:"cost",lastTurnInputTokens:k,at:new Date().toISOString()}),H=void 0}else g.mode==="shadow"&&this.log(`[${e.agentId}] resume gate (shadow) for ${w}:${S}: would ${Pn(f)}`)}}if(H&&c.def.tier==="claude-code"){let g=H;await te("rotate",()=>this.maybeRotateForContinuity(e,c,w,S,g),()=>!1)&&(H=void 0)}try{let g=await R("compact",()=>this.sessions.compactIfNeeded(e.agentId,w,S,this.memoryStore));if(g.compacted){let f=g.qualityScore??"?",k=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${w}:${S} (quality: ${f}%, ${k} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let I=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let kc=process.env.AGENTX_CONTEXT_SURGERY==="1",vc=ue?{maxMessages:8,maxChars:2400}:kc&&uc(w,c.def.tier)?{maxMessages:6,maxChars:1800}:void 0,$c=!H&&!ue?vp(Sc,e.agentId,{notesInbox:kp(this.config)}):void 0,ht=!H&&!Ke?this.sessions.buildHistoryContext(e.agentId,w,S,vc):void 0,Ac=H?void 0:this.sessions.getRotationMemo(e.agentId,w,S)??void 0,Ps,Es=[];if(this.config.procedures?.injection?.enabled&&!H&&!ue)try{let g=new at({baseDir:K(process.cwd(),this.config.procedures.dir)}),f=ss(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(f.length>0){Ps=rs(f),Es=f.map(k=>({id:k.procedure.meta.id,title:k.procedure.meta.title}));for(let k of f)this.log(`[${e.agentId}] procedure match ${k.procedure.meta.id} score=${k.score.toFixed(2)} (${k.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(Ae&&Ae.cat)try{let f=this.sessions.getSession(e.agentId,w,S).messages,k=f[0],I=f[f.length-1],B=ht===void 0?`resume=${H?H.slice(0,8):"?"} (no rebuild)`:`fresh history=${ht.length}c/${ht.split(`
|
|
168
168
|
`).length}L`,G=`[${e.agentId}] ${w}:${S} ${B} | session.messages=${f.length}`+(f.length>0?` first=${k.timestamp.slice(11,19)}(${k.role}:${(k.content||"").slice(0,40).replace(/\n/g," ")}) last=${I.timestamp.slice(11,19)}(${I.role}:${(I.content||"").slice(0,40).replace(/\n/g," ")})`:"");Ae.cat("context",G)}catch(g){Ae.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Os;if(c.def.contextReferences&&!H)try{let g=c.def.workspace,f=this.referencesCache.get(g);if(!f){let[I,B]=await R("references",()=>Promise.all([An(c.def.workspace),Cn(c.def.workspace)]));if(I.byId.size===0&&B.recipes.length===0){let[G,Q]=await R("references",()=>Promise.all([An(process.cwd()),Cn(process.cwd())]));f={refs:G,recipes:Q}}else f={refs:I,recipes:B};this.referencesCache.set(g,f)}let k=Dr({agentId:e.agentId,intentTags:ne?.path,message:e.message},f.recipes,f.refs);k.cards.length>0&&(Os=Er(k.cards,500*4)),k.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${k.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Ds=le||Ke?"":this.sessions.getCrossSessionSummary(e.agentId,w,S,e.message),Ls,yt=le?null:ai(e.message);if(yt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:w,chatId:S,lookbackDays:yt.lookbackDays,limit:12});if(g.turns.length>0){let f=[`[Long-memory recall \u2014 last ${yt.lookbackDays}d on this chat (cue-triggered)]`],k=[...g.turns].sort((I,B)=>I.ts.localeCompare(B.ts));for(let I of k){let B=I.ts.slice(11,16)+" "+I.day,G=I.role==="user"?I.senderName||"User":I.senderName||"Agent";f.push(`${B} ${G}: ${I.content}`)}g.hasMore&&f.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),f.push("[End of long-memory recall \u2014 respond to the latest message above]"),Ls=f.join(`
|
|
169
169
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${yt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Cc=ue?"layered":e.contextStrategy??c.def.contextStrategy??this.config.session.contextStrategy??"layered",Ns,Us,Fs=!1;ln||ee("request-gate");let ve=await Ss;if(ve.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Cc==="planner"&&!le&&!ve.active&&!Ke&&w!=="voice"&&w!=="desktop"){try{let{planContext:g}=await import("./context-planner-CVCRW5TV.js"),f=await R("plan-context",()=>g({agentId:e.agentId,channel:w,chatId:S,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));f?(Fs=!0,Ns=f.sessionHistory,Ms=f.memoryContext,Rs=f.memoryFacts,Ds=f.crossChatContext,Us=f.debug,this.log(`[${e.agentId}] planner: turns=${f.debug.recentTurns}, mem=${f.debug.memoryIncluded?"yes":"no"}, xchat=${f.debug.crossChatIncluded?"yes":"no"} (${f.debug.planLatencyMs}ms) \u2014 ${f.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Fs&&H&&(this.sessions.clearClaudeSessionId(e.agentId,w,S),H=void 0)}let fn=`${e.agentId}:${w}:${S}`,wt=wr(e.message);wt&&(wt==="default"?(this.activeSouls.delete(fn),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(fn,wt),this.log(`[${e.agentId}] Soul switched to: ${wt}`)));let Mc=this.activeSouls.get(fn),Rc=hr(c.def.workspace,Mc),_c=yr(Rc),Pc=le?"":this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Ec=mp(c.def.tier),Oc=Mp(c.def.richMessages,w),Dc=c.def.tier==="claude-code"&&(le||Ge!=="lean"||oa(ft)),Hs="";if(c.def.workspace&&!Dc){let g=K(c.def.workspace,"CLAUDE.md");if(de(g))try{let f=gt(g,"utf-8");Hs=`[Project CLAUDE.md]
|
|
170
170
|
${f.length>4e3?f.slice(0,4e3)+`
|
|
@@ -178,9 +178,9 @@ ${$e}`),f+=$e.length}catch{}}}let Lc=mn.length>0?mn.join(`
|
|
|
178
178
|
|
|
179
179
|
`)||void 0,xt={channel:w,chatId:S,channelScope:e.context?.group?"group":w==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:c.def.name,agentHandle:this.getChannelHandle(e.agentId,w),systemPrompt:c.def.systemPrompt,sender:gn,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:ue||Ke||uc(w,c.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:ue?void 0:Tc||void 0,procedureContext:[Ps,$s].filter(Boolean).join(`
|
|
180
180
|
|
|
181
|
-
`)||void 0,workflowRunContext:xc,references:Os,skillInjection:_s||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ns??ht,memoryContext:Ms||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Ls||void 0,contextOnDemand:Ke&&!H?la(w,S):void 0,wikiContext:$c,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Ts)}catch{return}})(),rotationMemo:Ac,eventDigest:H?void 0:Tp(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=ao(w,!H,c.def.richMessages);return g?$p(c.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(xt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let St=e.model?void 0:gr({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?mt:null});St?.downgraded&&this.log(`[${e.agentId}] ${St.reason}`);let js=lr(c.def.tier,this.config.decisions.routing),Bs=St?.downgraded?Promise.resolve(St.model):!e.model&&js&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
181
|
+
`)||void 0,workflowRunContext:xc,references:Os,skillInjection:_s||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Ns??ht,memoryContext:Ms||void 0,crossChatContext:Ds||void 0,longMemoryRecall:Ls||void 0,contextOnDemand:Ke&&!H?la(w,S):void 0,wikiContext:$c,handoverNote:this.buildHandoverNote(e.agentId,w,S),watcherNote:(()=>{try{return this.runNote?.(Ts)}catch{return}})(),rotationMemo:Ac,eventDigest:H?void 0:Tp(e.agentId,this.config.agents[e.agentId]?.subscriptions??c.def.subscriptions),attachHint:(()=>{let g=ao(w,!H,c.def.richMessages);return g?$p(c.def.workspace,g):void 0})(),intent:ne?{path:ne.path,pathLabel:ne.pathLabel,pathId:ne.pathId,axes:ne.axes,leaf:ne.leaf,status:ne.status}:void 0,message:e.message};le&&Object.assign(xt,{landscape:void 0,patternContext:void 0,procedureContext:void 0,workflowRunContext:void 0,references:void 0,skillInjection:void 0,sessionHistory:void 0,memoryContext:void 0,crossChatContext:void 0,longMemoryRecall:void 0,contextOnDemand:void 0,wikiContext:void 0,handoverNote:void 0,rotationMemo:void 0,eventDigest:void 0,attachHint:void 0});let St=e.model?void 0:gr({tier:c.def.tier,channel:w,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!H,sessionIdleMs:H?mt:null});St?.downgraded&&this.log(`[${e.agentId}] ${St.reason}`);let js=lr(c.def.tier,this.config.decisions.routing),Bs=St?.downgraded?Promise.resolve(St.model):!e.model&&js&&(!ve.active||ve.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-CGH54RYG.js"),f=await R("route-model",()=>g({message:e.message,agent:e.agentId,channel:w,isFollowUp:!!H,sessionIdleMs:H?mt:null,cheapModel:js}));if(f.downgraded)return this.log(`[${e.agentId}] ${f.reason}`),f.model}catch{}})():Promise.resolve(void 0),Ws=!1;Bs.then(()=>{Ws=!0});let It=ve.active&&ve.preprocess?await te("select-context",()=>wc(xt),()=>({input:xt,excluded:[]})):{input:xt,excluded:[]};It.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${It.excluded.join(", ")}`);let Tt=fi(It.input,ue?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),Nc=Mr(Tt,{memory:Rs,procedures:Es,wikiContext:It.input.wikiContext}),yn=(Tt?.length??0)+(hn?.length??0)+(e.message?.length??0),kt={history:Tt?.length??0,sysPrompt:hn?.length??0,message:e.message?.length??0},qs=Qi(e.agentId,w,S);Xi(qs,yn,kt);let Gs=Yi(qs);Gs&&this.log(`[${e.agentId}] ${Gs}`),yn>16e3&&this.log(`[${e.agentId}] large context for ${w}:${S}: ${yn} bytes (history=${kt.history}, sysPrompt=${kt.sysPrompt}, message=${kt.message})`),Ws||ee("route-model");let Ks=await Bs,Js=c.def.tier!=="claude-code"?void 0:le?ca():Ge==="lean"?aa(c.def.workspace,ft,void 0,w):ua(c.def.workspace);Ge==="lean"&&!le&&!H&&this.log(`[${e.agentId}] session profile for ${w}: ${ga(Ge,ft,w)}`);let zs=c.def.tier==="claude-code"&&!H?bo({message:e.message??"",agent:e.agentId,channel:w,agentPrompt:c.def.systemPrompt??null,taskId:M},g=>this.log(g)):void 0,Uc={...e,systemPromptAppend:hn,...Js?{claudeArgs:Js}:{},...Ks?{model:Ks}:{}},se,Qs=Aa({agent:e.agentId,request:e.message,taskId:M,budgetMinutes:c.def.maxExecutionMinutes??20}),Fc=v,Xs=!1,wn=!0;v=g=>{if(Qs.observe(g),ae&&wn)for(let f of eo(g))Vr(f.name,f.input)||(wn=!1);Fc?.(g)};try{let g=this.workflowAutoRunner;if(he&&g){let D=he;try{let z=await R("workflow-auto-run",()=>g({workflowId:D.workflowId,agentId:e.agentId,channel:w,chatId:S,message:e.message,...D.follow?{follow:!0}:{},payload:{message:e.message,agentId:e.agentId,channel:w,chatId:S,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:ne?.path,matchedWorkflowId:D.workflowId,matchConfidence:D.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${he.workflowId} run=${z.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),se={content:D.follow?`Started the workflow "${z.title??D.workflowId}" for this${z.runId?` (run ${z.runId})`:""}. AgentX follows each step and tells the owner when it is done.`:"",duration:0,metadata:{handledByWorkflow:he.workflowId,workflowRunId:z.runId,workflowMatchConfidence:he.confidence}},se}catch(z){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${z?.message||z}`)}}if(ae&&ke)try{let D=no(ke,e.resumedFrom);to(ke,{runId:ae,agentId:e.agentId,channel:w,chatId:S,message:e.message,taskId:M,...D?{continues:D}:{}}),Xs=!0,h.workflow={runId:ae,workflowId:zr}}catch(D){this.log(`[${e.agentId}] workflows.required: could not create run ${ae} (non-fatal): ${D?.message||D}`)}let f=()=>{if(c.def.tier!=="claude-code")return null;ee("dispatch-gate");let D=c.def.persistentProcess?Ht():null,z=D!=null&&D.hasLive({agentId:e.agentId,channel:w,chatId:S}),ce=!!H||z,ge=[Oi(ce),Ji(ce,void 0,e.model||c.def.model)].find(Ct=>Ct&&Ct.abort);if(ge){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${ge.reason}`);let Ct={content:"",error:ge.message,errorKind:"dispatch_hold",duration:0};if(!t){A.buffer=`[error] ${ge.message}`;for(let Bc of A.subscribers)try{Bc(A.buffer)}catch{}}return Ct}Fi();let Je=zi();return Je&&this.log(`[${e.agentId}] ${Je}`),null},k=Et(e.agentId,void 0,Pt(e.agentId,e.context?.chatId));if(k){if(ee("budget-gate"),this.log(`[${e.agentId}] run refused \u2014 ${k.reason}`),!t){A.buffer=`[error] ${k.message}`;for(let D of A.subscribers)try{D(A.buffer)}catch{}}return c.errors++,se={content:"",error:k.message,errorKind:"budget_cap",duration:0},se}let I=this.planCloudSession(c.def,e);if(I.route==="local"){let D=f();if(D)return c.errors++,se=D,D}let B=c.def.tier==="claude-code",G=B?t:(D,z)=>{D&&_(D),t&&t(D,z)},Q=!1,$e=B?s:D=>{D&&(Q?_(D):(_(`\u{1F4AD} ${D}`),Q=!0)),s&&s(D)},ye=()=>{Q&&(_(`
|
|
182
182
|
`),Q=!1)},Hc=B?G:G?(D,z)=>{ye(),G(D,z)}:void 0,$=await R("agent",async()=>{if(I.route!=="local"){let z=await this.runCloudSession(c.def,e,I,M);if(z)return z;let ce=f();if(ce)return ce}let D=await this.inTaskWorktree(c.def,Uc);return ri(D.def,D.task,this.providers,Hc,Tt,D.fresh?void 0:H,v,O.signal,$e)},wp);if(!$.error){let D=Ap(c.def.toolUseRequired,L);if(D){let z=Array.from(L.entries()).map(([ce,At])=>`${ce}=${At}`).join(", ")||"none";$.error=`tool_required_not_called: ${D} (invoked: ${z})`,$.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${D}, observed ${z}`)}}zs&&xo(zs,{toolUses:L,eventsSeen:q,error:$.error,agentId:e.agentId},D=>this.log(D));let vt=this.interruptedRuns.get(h.id);vt&&($.content="",$.error=vt,$.errorKind="interrupted");let bn=vt?void 0:this.stoppedRuns.get(h.id);bn&&($.content="",$.error=bn,$.errorKind="stopped"),se=$;let we=$.usage?Ar($.usage):void 0,jc=$.billedModel||e.model||c.def.model||void 0,$t=$.costUsd??($.usage?this.tokenTracker.runCost($.usage,jc,c.def.tier):void 0);if(un=!0,V().emit("task:completed",{taskId:M,agentId:e.agentId,channel:w,chatId:S,durationMs:Date.now()-Is,error:$.error||void 0,errorKind:$.error?$.errorKind:void 0,interrupted:vt?!0:void 0,stopped:bn?!0:void 0,inputTokens:we?.inputTokens,outputTokens:we?.outputTokens,cacheReadTokens:we?.cacheReadTokens,cacheCreateTokens:we?.cacheCreateTokens,tier2InputTokens:we?.tier2InputTokens,tier2OutputTokens:we?.tier2OutputTokens,tier2CacheReadTokens:we?.tier2CacheReadTokens,tier2CacheCreateTokens:we?.tier2CacheCreateTokens,resumed:!!H,resumeSessionId:H||void 0,jevArm:ve.arm,numTurns:$.numTurns,costUsd:$t!==void 0&&Number.isFinite($t)&&$t>0?$t:void 0,injectedContext:Nc,finalResponse:$.content||void 0,billedModel:$.billedModel||e.model||c.def.model||void 0,at:new Date().toISOString()}),!t&&($.content||$.error)){let D=$.error?`[error] ${$.error}`:$.content;A.buffer=D;for(let z of A.subscribers)try{z(D)}catch{}}if($.error)c.errors++,this.log(`[${e.agentId}] error: ${$.error}`);else{if(this.sessions.addAgentMessage(e.agentId,w,S,$.content),Ma({agent:e.agentId,channel:w,chatId:S,request:e.message,reply:$.content,taskId:M}),$.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,w,S,$.claudeSessionId),$.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,w,S,$.codexSessionId),$.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,w,S,$.opencodeSessionId),($.claudeSessionId||$.codexSessionId||$.opencodeSessionId)&&$.usage&&this.sessions.recordTurnUsage(e.agentId,w,S,$.usage,$.contextTokens),$.usage){let ge=$.contextTokens,Je=($.usage.inputTokens||0)+($.usage.cacheReadTokens||0)+($.usage.cacheCreateTokens||0);(ge??Je)>=this.sessions.getTierTwoThresholdTokens(w)&&this.log(`[${e.agentId}] TIER-2 HIT on ${w}:${S}: context=${ge??"n/a"} tokens (cumulative turn total=${Je}) \u2014 next turn will rotate`)}if(Sr({channel:w,content:`User: ${e.message}`,responseLength:$.content.length}).capture){await vs(ap);try{let ge=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ge,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:w,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
183
183
|
|
|
184
184
|
Agent: ${$.content}`,meta:Ip(ne,e.context)})}catch{}Tr(e.agentId,e.message,$.content,{channel:w,chatId:S,sender:gn},this.memoryStore).catch(()=>{}),Ci(e.agentId,e.message,$.content,{channel:w,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let z=$.billedModel||e.model||c.def.model,ce=e.context?.channel,At=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,$.duration||0,$.usage,e.message.length,$.content.length,!1,z,ce,At),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${J()}`)}return $}catch(g){c.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let f=Nt(g.message);return se={content:"",error:Ut(f),errorKind:f.kind},se}finally{if(Qs.stop(),Xs&&ae&&ke)try{let g=se?.usage,f=so(ke,ae,{error:se?se.error||void 0:O.signal.aborted?Pe(O.signal).message:"run ended before completion",canceled:ro(se?.errorKind)||this.stoppedRuns.has(h.id)||this.interruptedRuns.has(h.id)||!se&&O.signal.aborted,durationMs:Date.now()-h.startedAt.getTime(),...g?{inputTokens:g.inputTokens,outputTokens:g.outputTokens}:{},readOnly:wn,exemptQuestions:this.config.workflows?.required?.exemptQuestions??!0});f&&f!=="discarded"&&this.log(`[${e.agentId}] workflow run ${ae} ${f.status} (${f.meta?.wrap?.mode??"linear"})`)}catch(g){this.log(`[${e.agentId}] workflows.required: could not close run ${ae} (non-fatal): ${g?.message||g}`)}ws(se),xs(se)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:this.withLastActivity(this.withWorkflowSteps(e.runningTasks)),lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}withLastActivity(e){return e.map(t=>{let s=this.taskOutputs.get(t.id),r=s?hp(s.buffer.slice(-2e3)):void 0;return r?{...t,lastActivity:r}:t})}withWorkflowSteps(e){let t=this.workflowRuns;return!t||!e.some(s=>s.workflow)?e:e.map(s=>{if(!s.workflow)return s;try{let r=t.get(s.workflow.runId);return r?{...s,workflow:{...s.workflow,workflowId:r.workflowId,step:oo(r),title:r.meta?.title??r.workflowId}}:s}catch{return s}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=K(process.cwd(),qe,this.safe(e.agentId),t);de(s)||cp(s,{recursive:!0});let r=K(s,`${this.safe(e.id)}.json`);up(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=K(process.cwd(),qe,this.safe(e));if(!de(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let d=new Date(s).toISOString().slice(0,10),c=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[c,d]){let p=K(a,l);if(de(p))try{for(let m of me(p)){if(!m.endsWith(".json"))continue;let y=m.split("-")[0],b=parseInt(y,10);if(!Number.isFinite(b)||b<i||b>s)continue;let C=Math.floor((s-b)/36e5),h=t-1-C;h>=0&&h<t&&o[h]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=K(process.cwd(),qe);if(!de(e))return 0;let t=0;for(let s of me(e)){let r=K(e,s),o;try{o=me(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=K(r,i),d;try{d=me(a).filter(c=>c.endsWith(".json")).sort().reverse()}catch{continue}for(let c of d)try{let u=JSON.parse(gt(K(a,c),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let p=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:p,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Sp){let t=K(process.cwd(),qe);if(!de(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of me(t)){let i=K(t,o),a;try{a=me(i)}catch{continue}for(let d of a){let c=Date.parse(d+"T00:00:00Z");if(!(Number.isNaN(c)||c>=s))try{dp(K(i,d),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=K(process.cwd(),qe,this.safe(e));if(!de(s))return[];let r=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=K(s,i),d;try{d=me(a).filter(c=>c.endsWith(".json"))}catch{continue}d.sort().reverse();for(let c of d){if(o.length>=t)break;try{let u=JSON.parse(gt(K(a,c),"utf-8")),{transcript:l,responseText:p,...m}=u;o.push(m)}catch{}}}return o}getTaskRecord(e,t){let s=K(process.cwd(),qe,this.safe(e));if(!de(s))return null;let r=this.safe(t),o=me(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=K(s,i,`${r}.json`);if(de(a))try{return JSON.parse(gt(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}armBudgetRelease(){this.budgetReleaseTimer||(this.budgetReleaseTimer=setInterval(()=>this.releaseBudgetHolds(),6e4),this.budgetReleaseTimer.unref?.())}releaseBudgetHolds(){let e=0;for(let t of this.budgetHolds.agents()){let s=this.budgetHolds.take(t,r=>!Et(t,void 0,Pt(t,r.chatId)));if(s.length){e+=s.length,this.log(`[${t}] budget allows runs again \u2014 releasing ${s.length} held message(s)`);for(let r of s){let o=r.context||{channel:r.channel,chatId:r.chatId};this.execute({message:r.text,agentId:t,context:o,queuedAt:r.heldAt}).then(i=>this.postQueuedResponseToChannel(t,o,i)).catch(i=>this.log(`[${t}] held message failed: ${i?.message??i}`))}}}return this.budgetHolds.size===0&&this.budgetReleaseTimer&&(clearInterval(this.budgetReleaseTimer),this.budgetReleaseTimer=null),e}heldForBudget(e){return this.budgetHolds.count(e)}postQueuedResponseToChannel(e,t,s){let r=Rn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||s.errorKind==="stopped"||Ye(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();if(a){if(!r.getChannel(o)){pp.has(o.split("@")[0])||this.log(`[${e}] queued response not posted: no adapter for channel "${o}"`);return}r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(d=>this.log(`[${e}] queued response post failed: ${d?.message??d}`))}}runningTaskRoot(e){return this.taskAborts.get(e)?.rootId}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}runningTraceId(e,t){return this.agents.get(e)?.runningTasks.find(s=>s.id===t)?.traceId??null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let d=Jt(a);return d.channel===t.channel&&d.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o,...r.autonomy?{autonomy:r.autonomy}:{},...r.workflow?{workflowRunId:r.workflow.runId}:{}}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}stopRunningTask(e,t){let s=this.taskAborts.get(e);if(!s||s.controller.signal.aborted)return!1;this.stoppedRuns.set(e,t);try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} stopped \u2014 ${t}`),!0}whenRunEnds(e,t){return this.taskAborts.has(e)?new Promise(s=>{let r=setTimeout(s,t);r.unref?.();let o=this.runEndWaiters.get(e)??[];o.push(()=>{clearTimeout(r),s()}),this.runEndWaiters.set(e,o)}):Promise.resolve()}signalTarget(e){let t;if(e.taskId)t=this.taskAborts.has(e.taskId)?e.taskId:void 0;else if(e.agentId&&e.channel&&e.chatId){let s=[...this.taskAborts].filter(([,r])=>r.agentId===e.agentId&&r.channel===e.channel&&r.chatId===e.chatId).map(([r])=>r);t=s.length===1?s[0]:void 0}return t?this.signalTargetOf(t):null}signalTargets(){return[...this.taskAborts].filter(([,e])=>!e.controller.signal.aborted).map(([e])=>this.signalTargetOf(e)).filter(e=>e!==null)}signalTargetOf(e){let t=this.taskAborts.get(e);return t?{taskId:e,traceId:t.traceId,agentId:t.agentId,channel:t.channel,chatId:t.chatId,sender:t.sender,rootId:t.rootId,originalMessage:t.originalMessage,origin:t.origin??null,...t.workflowRunId?{workflowRunId:t.workflowRunId}:{}}:null}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:d,originalMessage:c}=o,u=o.controller.signal.aborted,l=!1;u&&c&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,d,c));let p=Date.now();this.messageQueue.enqueue(i,a,d,{text:t,sender:s,timestamp:p,channel:a,chatId:d,originalContext:{channel:a,chatId:d,sender:s}});let m=this.messageQueue.pendingCount(i,a,d);V().emit("task:queued",{agentId:i,channel:a,chatId:d,at:new Date(p).toISOString(),sender:{name:s},humanRoot:!1,person:rr(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:p});let y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${m}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:d,replaced:y,edited:l,pending:m}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,d=i.chatId;return new Promise(c=>{let u=!1,l=p=>{u||(u=!0,c(p))};this.log(`[${e}] operator resumed ${a}:${d} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(d),context:{channel:a,chatId:d,sender:r},onStart:p=>l({ok:!0,agentId:e,channel:a,chatId:d,taskId:p,queued:!1})}).then(p=>{Ye(p.error)?l({ok:!0,agentId:e,channel:a,chatId:d,queued:!0}):p.error?l({ok:!1,status:500,error:p.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:d,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>l({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Mp(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(`
|
|
185
185
|
`)}export{$o as a,qp as b,Co as c,id as d,Mo as e,jt as f,sf as g,cf as h,df as i,ff as j,Jt as k,Cd as l,ti as m,Ed as n,Od as o,Dd as p,ri as q,Qt as r,Xt as s,su as t,Bf as u,Wf as v,Gf as w,Zt as x,zf as y,Qn as z,V as A,Mi as B,Su as C,vu as D,Pi as E,um as F,Ei as G,Ni as H,Wi as I,km as J,qi as K,tn as L,Pm as M,Em as N,at as O,Ll as P,Nl as Q,Ul as R,Fl as S,Hl as T,ss as U,on as V,dh as W,cn as X,an as Y,Ua as Z,dt as _,Fa as $,hh as aa,yh as ba,wh as ca,bh as da,xh as ea,Sh as fa,Ih as ga,wg as ha,Ya as ia,We as ja,fp as ka,mp as la,Zy as ma,Vy as na,hp as oa,xp as pa,Ip as qa,Tp as ra,vp as sa,ys as ta,gc as ua,pc as va,Ap as wa,fc as xa,mc as ya,Mp as za};
|
|
186
|
-
//# sourceMappingURL=chunk-
|
|
186
|
+
//# sourceMappingURL=chunk-33DLG4I2.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,ca as N,ha as Oe}from"./chunk-
|
|
1
|
+
import{a as k}from"./chunk-IMLAPB7G.js";import{k as y}from"./chunk-LQS27HSV.js";import{d as V}from"./chunk-QPABR72X.js";import{b as z}from"./chunk-KP7KDLZ2.js";import{V as B,W as J,X,Y as K,ca as N,ha as Oe}from"./chunk-KOY3EOPH.js";import{existsSync as Q,readFileSync as Ie}from"node:fs";import{dirname as A,join as h}from"node:path";import{fileURLToPath as Ee}from"node:url";import{homedir as Ce}from"node:os";var M="tn.acme.agentx.voice",gt="AgentX Desktop.app",Y="AgentX Helper.app";function yt(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function ht(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function T(e){return`'${e.replace(/'/g,"'\\''")}'`}var Z="/usr/bin:/bin:/usr/sbin:/sbin";function wt(e,t){return t||[...new Set([...e?[A(e)]:[],...Z.split(":")])].join(":")}function R(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function St(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?R(t[1]):Z}var xt=e=>/agentx\.voice.*\.plist$/.test(e);function vt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,u)=>s.file<u.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],u=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!u||!R(u).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:R(s)}):n={file:o,label:R(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function ee(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function bt(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${T(e.cwd)} && ${T(e.node)} ${T(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??M)}</string>
|
|
@@ -33,4 +33,4 @@ function run(argv) {
|
|
|
33
33
|
`),it(r,n)}var ut=5*6e4;function Cn(e,t,n=Date.now()){let r=Ae(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=ut)?!1:r.items[`card:${t}`]?.state!=="failed"}var U=24*36e5;function Re(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function lt(e,t,n,r){let o=Date.parse(e.expires),i=[f(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,u)=>`${u+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${f(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:f(e.title,y.title),notes:i.join(`
|
|
34
34
|
`),due:Re(r,t,o),priority:Number.isFinite(o)&&o-r<=U?"high":"none"}}function ct(e,t,n,r){let o=[f(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:W(e,y.title).headline,notes:o.join(`
|
|
35
35
|
`),due:Re(r,t,i),priority:i!==void 0&&i-r<=U?"high":"none"}}async function Tn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),u={created:0,completed:0,dismissed:0,failed:0},l=Ae(t);delete l.lastError;let p=a=>{l.lastError={at:s,message:a}},S=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&S.set(`card:${a.id}`,lt(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&S.set(`request:${a.id}`,ct(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),p(String(a?.message??a)),Ne(t,l),u}let G=!0,v=new Map,Pe=async a=>{if(!v.has(a))try{v.set(a,new Set((await r.listOpen(a)).map(c=>c.id)))}catch(c){o(`[mirror] could not read list "${a}": ${c?.message??c}`),p(String(c?.message??c)),v.set(a,null),G=!1}return v.get(a)};for(let[a,c]of Object.entries(l.items)){if(c.state!=="open"||!c.id)continue;let d=await Pe(c.list);if(d)if(S.has(a))d.has(c.id)||(l.items[a]={...c,state:"dismissed",at:s},u.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(c.id))try{await r.complete(c.id)}catch(g){o(`[mirror] ${a}: could not complete its task: ${g?.message??g}`),p(String(g?.message??g));continue}l.items[a]={...c,state:"completed",at:s},u.completed++}}let E=null,x=[];for(let[a,c]of S){let d=l.items[a];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=j)continue;if(E===null)try{await r.ensureList(n.list),E=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),p(String(m?.message??m)),E=!1}let g=d?.state==="failed"?d.failures:0;try{let{id:m}=await r.add({list:n.list,title:c.title,notes:c.notes,due:c.due,priority:c.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},u.created++}catch(m){let b=String(m?.message??m),C=g+1;l.items[a]={list:n.list,state:"failed",at:s,failures:C,lastError:b},p(b),u.failed++,o(`[mirror] ${a}: could not add to Reminders (${C}/${j}): ${b}`),C===j&&x.push({title:c.title,message:b})}}let $e=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(x.length&&!(i-$e<U)){let a=x[0],c=x.length>1?` (and ${x.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${c}: ${f(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}G&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,c]of Object.entries(l.items))c.state!=="open"&&!S.has(a)&&i-Date.parse(c.at)>at&&delete l.items[a];return Ne(t,l),u}export{gn as a,he as b,H as c,F as d,yn as e,hn as f,Ze as g,wn as h,Sn as i,xn as j,W as k,f as l,Rn as m,gt as n,Y as o,yt as p,ht as q,wt as r,St as s,xt as t,vt as u,ee as v,bt as w,Nt as x,Te as y,Me as z,_e as A,_ as B,se as C,q as D,ye as E,un as F,ln as G,cn as H,Ae as I,Cn as J,Tn as K};
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
36
|
+
//# sourceMappingURL=chunk-5LPCJZKI.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-
|
|
1
|
+
import{B as N,D as k,F as O,I,s as R,v as x}from"./chunk-5LPCJZKI.js";import{a as E}from"./chunk-OSH2PEBH.js";import{pb as j,yb as F}from"./chunk-KOY3EOPH.js";F();import{Command as X}from"commander";import f from"chalk";import{execFileSync as m}from"child_process";import{accessSync as W,constants as M,existsSync as w,readFileSync as b,readdirSync as C,statSync as B}from"fs";import{join as H,resolve as y}from"path";import{homedir as z}from"os";import{createRequire as G}from"module";var T="Open System Settings \u203A Notifications \u203A AgentX Helper, turn on Allow notifications and choose Banners.";async function P(t={}){let n=t.helper===void 0?N():t.helper,e=k({},{platform:t.platform,io:{capture:t.run,helper:n}}).banner;if(!e)return{state:"unsupported",message:"Desktop banners are only shown on a Mac."};let i=await e.status();return i==="missing"?{state:"missing",message:"AgentX Helper is not installed, so banners come from Script Editor and show its icon.",fix:'Run agentx desktop install, then run agentx notify "Hello" --title "Test" and click Allow.'}:i==="outdated"?{state:"outdated",path:n,message:"AgentX Helper is too old to report whether it may notify.",fix:"Run agentx desktop install to update it."}:i==="not-asked"?{state:"not-asked",path:n,message:"macOS has not asked yet whether AgentX Helper may notify; banners show the Script Editor icon until it does.",fix:'Run agentx notify "Hello" --title "Test" and click Allow when macOS asks.'}:i==="not-allowed"?{state:"not-allowed",path:n,message:"macOS does not allow AgentX Helper to notify, so banners show the Script Editor icon.",fix:T}:i==="hidden"?{state:"hidden",path:n,message:"AgentX Helper may notify, but its banner style is None, so nothing appears on screen.",fix:T}:{state:"ready",path:n,message:"AgentX Helper posts banners with the AgentX icon."}}async function Z(t={}){let n=[];await Q(n),Y(n);let e=ee(n);return e&&te(n,e),e&&se(n,e),e&&re(n,e),e&&ae(n,e),e&&ie(n,e),e&&ce(n,e),e&&await J(n,e),e&&U(n,e),e&&await K(n,e),e&&V(n,e),t.running!==!1&&e&&await de(n,e),{checks:n,summary:D(n)}}var Ne=new X().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async t=>{let{checks:n,summary:e}=await Z({running:t.running!==!1});t.json?process.stdout.write(JSON.stringify({checks:n,summary:e},null,2)+`
|
|
2
2
|
`):ue(n),process.exit(e.errors>0?1:0)});async function J(t,n,e=P){if(!O(n.notifications?.local).banner)return;let i=await e();i.state!=="unsupported"&&t.push({severity:i.state==="ready"?"ok":"warn",group:"Notifications",title:i.message,detail:i.path,fix:i.fix})}async function K(t,n,e){let i;try{i=await(e??k(n)).describe()}catch(s){t.push({severity:"warn",group:"Native",title:"Native apps: could not be read",detail:s?.message??String(s)});return}let o=["tasks","notes","banner","sound","focus"].filter(s=>i[s]);t.push({severity:"ok",group:"Native",title:i.os==="none"?"Native apps: none on this machine":`Native apps (${i.os}): ${o.join(", ")||"nothing available"}`,detail:i.problems.join(" ")||void 0})}function V(t,n,e=process.cwd(),i=k(n)){let o=n.native?.mirror;if(!o?.enabled)return;if(!i.tasks){t.push({severity:"warn",group:"Native",title:"Reminders mirror is on, but this machine has no task app",detail:"native.mirror.enabled is set; nothing is mirrored here.",fix:"Turn it on on the machine that holds the owner's cards (the Mac), or set native.mirror.enabled to false here."});return}let s=I(e),a=Object.values(s.items),l=a.filter(g=>g.state==="open").length,u=a.filter(g=>g.state==="failed").length;t.push({severity:s.lastError||u?"warn":"ok",group:"Native",title:`Reminders mirror: ${l} open in "${o.list}"${u?`, ${u} could not be added`:""}`,detail:s.lastError?`Last error ${s.lastError.at}: ${s.lastError.message}`:void 0,fix:s.lastError?"Run remindctl status, and allow Reminders for the app that runs the daemon in System Settings \u203A Privacy & Security \u203A Reminders.":void 0})}function U(t,n,e=process.platform,i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}}){let o=n.reminders;if(!o?.enabled)return;if(e!=="darwin"){t.push({severity:"warn",group:"Reminders",title:"Reminders hand-back unavailable on this machine",detail:"reminders.enabled is set, but Apple Reminders exists only on macOS. The daemon starts without it.",fix:"Set reminders.enabled to false here, or enable it on the Mac node instead."});return}let s=o.command||"remindctl",a=s.includes("/")?i(s)?s:null:x(s,process.env.PATH||"",i);t.push(a?{severity:"ok",group:"Reminders",title:`Watching ${(o.lists||[]).join(", ")} for due reminders`,detail:a}:{severity:"fail",group:"Reminders",title:`${s} not found`,detail:"The daemon reads Apple Reminders through remindctl.",fix:"brew install steipete/tap/remindctl, or set reminders.command to its full path."})}async function Q(t){let n=E(process.versions.node);t.push({severity:n?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:n?void 0:"AgentX requires Node 22.19 or newer, up to Node 26.",fix:n?void 0:"Install Node 22 (nvm install 22 && nvm use 22)"});let e=l=>{try{return m(process.platform==="win32"?"where":"which",[l],{encoding:"utf-8"}).trim().split(`
|
|
3
3
|
`)[0]}catch{return null}},i=e("npm");t.push({severity:i?"ok":"fail",group:"Environment",title:i?"npm on PATH":"npm not found",detail:i||void 0});let o=e("claude");if(o){let l;try{l=m("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`claude CLI ${l||"installed"}`,detail:o})}else t.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let s=e("codex");if(s){let l;try{l=m("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`codex CLI ${l||"installed"}`,detail:s})}else t.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let a=e("opencode");if(a){let l;try{l=m("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"Environment",title:`opencode CLI ${l||"installed"}`,detail:a})}else t.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{G(import.meta.url)("better-sqlite3"),t.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(l){t.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:l?.message??String(l),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function Y(t){if(process.platform!=="darwin")return;let n=H(z(),"Library/LaunchAgents"),e=[];try{e=C(n).filter(o=>/agentx\.voice.*\.plist$/.test(o))}catch{return}let i=o=>{try{return W(o,M.X_OK),!0}catch{return!1}};for(let o of e){let s=R(b(H(n,o),"utf-8")),a=x("ffmpeg",s,i);t.push(a?{severity:"ok",group:"Desktop",title:"ffmpeg reachable by the desktop app",detail:`${a} (${o})`}:{severity:"warn",group:"Desktop",title:"ffmpeg not reachable by the desktop app",detail:`Local Whisper transcription fails without it. ${o} sets PATH to ${s}.`,fix:"Install ffmpeg (brew install ffmpeg), then rerun agentx desktop install."})}}function ee(t){let n=y(process.cwd(),"agentx.json");if(!w(n))return t.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${n}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(b(n,"utf-8"))}catch(a){return t.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:a.message}),null}try{j(n),t.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(a){t.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:a.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let i=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="claude-code");i.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${i.length} agent(s) use claude-code tier but claude CLI is missing`,detail:i.map(([l])=>l).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let o=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="codex-cli");o.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:o.map(([l])=>l).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let s=Object.entries(e.agents||{}).filter(([,a])=>a.tier==="opencode");return s.length>0&&((()=>{try{return m(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||t.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:s.map(([l])=>l).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function te(t,n){let e=new Set;if(A(n,e),e.size===0){t.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let i=_(),o=[],s=[];for(let a of e){let l=process.env[a]??i[a];l===void 0?o.push(a):(!l.trim()||/^["']?\s*["']?$/.test(l))&&s.push(a)}o.length===0&&s.length===0?t.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(o.length>0&&t.push({severity:"fail",group:"Secrets",title:`${o.length} env var(s) referenced in agentx.json but missing`,detail:o.join(", "),fix:`Add to .env \u2014 e.g. ${o[0]}=<value>`}),s.length>0&&t.push({severity:"warn",group:"Secrets",title:`${s.length} env var(s) set but empty`,detail:s.join(", ")}))}function _(){let t=y(process.cwd(),".env"),n={};if(w(t))for(let e of b(t,"utf-8").split(/\r?\n/)){let i=e.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);i&&(n[i[1]]=i[2])}return n}function ne(t,n){let e="With a shared token this node cannot tell which peer is calling. For example, closing an approval card forwarded from that peer is refused, and its stop/resume signals are judged as the owner's.",i="Give this pair a token of its own: set the same new value as mesh.peers[].token here and on the peer.",o=[];for(let s of t){let a=(s.token??"").trim();a?n&&a===n&&o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" uses this node's own MESH_TOKEN`,detail:e,fix:i}):o.push({severity:"warn",group:"Mesh",title:`mesh peer "${s.name}" has no token; calls to it use the shared MESH_TOKEN`,detail:e,fix:i})}return t.length>0&&o.length===0&&o.push({severity:"ok",group:"Mesh",title:`${t.length} mesh peer(s), each with a token of its own`}),o}function ie(t,n){t.push(...oe(n))}function oe(t,n=process.env,e=_()){let i=a=>(n[a]||e[a]||"").trim(),o=a=>typeof a=="string"?a.replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(l,u)=>i(u)):void 0,s=(t.mesh?.peers??[]).filter(a=>typeof a?.name=="string").map(a=>({name:a.name,token:o(a.token)}));return ne(s,i("MESH_TOKEN")||void 0)}function A(t,n){if(typeof t=="string")for(let e of t.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))n.add(e[1]);else if(Array.isArray(t))for(let e of t)A(e,n);else if(t&&typeof t=="object")for(let e of Object.values(t))A(e,n)}function se(t,n){let e=[];for(let[i,o]of Object.entries(n.agents||{})){if(!o.workspace)continue;let s=o.workspace.startsWith("/")?o.workspace:y(process.cwd(),o.workspace);try{B(s).isDirectory()||e.push(`${i}: ${s} (exists but not a directory)`)}catch{e.push(`${i}: ${s}`)}}e.length===0?t.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):t.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
4
|
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function re(t,n){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,i=[];for(let[o,s]of Object.entries(n.agents||{})){if(!s.workspace)continue;let a=s.workspace.startsWith("/")?s.workspace:y(process.cwd(),s.workspace);for(let l of["settings.json","settings.local.json"]){let u=y(a,".claude",l);if(!w(u))continue;let g;try{g=JSON.parse(b(u,"utf-8"))}catch(c){i.push({severity:"fail",agent:o,msg:`${l}: JSON parse error \u2014 ${c.message}`});continue}let $=g.env||{};for(let[c,h]of Object.entries($)){if(typeof h!="string")continue;let p=h.match(e);p&&i.push({severity:"fail",agent:o,msg:`${l} env.${c} contains unexpanded ${[...new Set(p)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let r=$.PATH;if(typeof r=="string"){let c=r.split(":").filter(Boolean);c.includes("/usr/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),c.includes("/bin")||i.push({severity:"fail",agent:o,msg:`${l} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let d=g.permissions;if(d&&typeof d=="object"&&"allow"in d){let c=d.allow,h=d.deny;Array.isArray(c)&&c.length===0&&Array.isArray(h)&&h.length>0&&i.push({severity:"warn",agent:o,msg:`${l} permissions.allow is explicitly [] with ${h.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(i.length===0){t.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(n.agents||{}).length} agent .claude/settings.json files clean`});return}for(let o of i)t.push({severity:o.severity,group:"Workspace settings",title:`${o.agent}: ${o.msg}`,fix:o.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function ae(t,n){let e=n.webhooks??[],i=[],o=y(process.cwd(),n.workflows?.dir||".agentx/workflows"),s=new Set;try{if(w(o))for(let r of C(o))r.endsWith(".json")&&!r.startsWith("_")&&!r.endsWith(".disabled.json")&&s.add(r.replace(/\.json$/,""))}catch{}let a=new Set(["github","gitlab"]);for(let r of e){if(!r.enabled||!a.has(r.source))continue;!(r.triggers&&Object.keys(r.triggers).length>0)&&!r.defaultWorkflow&&i.push({severity:"warn",title:`webhook "${r.id}" (${r.source} -> ${r.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let r of e)if(!(!r.enabled||!r.triggers)){for(let[d,c]of Object.entries(r.triggers))s.size>0&&!s.has(c)&&i.push({severity:"fail",title:`webhook "${r.id}".triggers["${d}"] -> "${c}" \u2014 no such workflow under ${n.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});r.defaultWorkflow&&s.size>0&&!s.has(r.defaultWorkflow)&&i.push({severity:"fail",title:`webhook "${r.id}".defaultWorkflow -> "${r.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(w(o)){for(let r of C(o))if(!(!r.endsWith(".json")||r.startsWith("_")||r.endsWith(".disabled.json")))try{let d=JSON.parse(b(y(o,r),"utf-8"));d?.status==="active"&&d?.state==="quarantined"&&i.push({severity:"warn",title:`workflow "${d.id??r}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let l=new Set((n.mesh?.peers??[]).map(r=>r.name));for(let r of e)!r.enabled||!r.node||l.has(r.node)||i.push({severity:"fail",title:`webhook "${r.id}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let u=new Map;for(let r of e){if(!r.enabled)continue;let d=`${r.source}:${r.agentId}`,c=u.get(d);c?i.push({severity:"warn",title:`webhook entries "${c}" and "${r.id}" both enabled for ${r.source} -> ${r.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):u.set(d,r.id)}let g=new Set(Object.keys(n.agents??{}));for(let r of n.channels?.gitlab?.agentMappings??[])if(r?.agentId){if(r.node){l.has(r.node)||i.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${r.agentId}" routes to mesh peer "${r.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}g.has(r.agentId)||i.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${r.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[r,d]of Object.entries(n.channels?.telegram?.accounts??{}))d.agentBinding?g.has(d.agentBinding)||i.push({severity:"fail",title:`telegram account "${r}".agentBinding -> "${d.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):i.push({severity:"fail",title:`telegram account "${r}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let $=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[r,d]of Object.entries(n.agents??{})){let c=d.integrations??[];if(!c.length)continue;let h=new Set;for(let p of c){let S=`${p.kind}::${p.label}`;h.has(S)&&i.push({severity:"warn",title:`agents.${r}.integrations: duplicate (${p.kind}, ${p.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),h.add(S),$.has(p.kind)||i.push({severity:"warn",title:`agents.${r}.integrations: unknown kind "${p.kind}" on integration "${p.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let L=p.credentials||{};for(let[q,v]of Object.entries(L))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&i.push({severity:"warn",title:`agents.${r}.integrations[${p.kind}/${p.label}].${q} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(i.length===0){t.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(n.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let r of i)t.push({severity:r.severity,group:"Routing",title:r.title,fix:r.fix})}function le(t){return typeof t?.canMeasure!="boolean"?null:t.canMeasure?{severity:"ok",group:"Runtime",title:"Daemon finds ffmpeg to measure phone recordings"}:{severity:"warn",group:"Runtime",title:t.allowUnmeasured?"Daemon can't find ffmpeg: phone recordings go unmeasured (voice.allowUnmeasured)":"Daemon can't find ffmpeg: phone voice input is refused",fix:"Install ffmpeg (brew install ffmpeg / sudo apt install ffmpeg), or set AGENTX_FFMPEG in the service's environment. The daemon's PATH is shorter than your shell's."}}async function de(t,n){let e=n.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",i={};n.dashboard?.token&&(i.Authorization=`Bearer ${n.dashboard.token}`);try{let o=new AbortController,s=setTimeout(()=>o.abort(),2e3),a=await fetch(e+"/health",{headers:i,signal:o.signal});if(clearTimeout(s),!a.ok){t.push({severity:"warn",group:"Runtime",title:`Daemon responded ${a.status}`,detail:e});return}let l=await a.json();t.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${l.agents?.length??0} agents live, uptime ${Math.round((l.uptime??0)/60)}m`,detail:e});let u=le(l.voice);u&&t.push(u)}catch{t.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function ce(t,n){let e=Object.entries(n.agents||{}).filter(([,o])=>o?.codegraph===!0&&(o.tier==="claude-code"||o.tier==="codex-cli"));if(e.length===0)return;let i=null;try{i=m(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
5
|
`)[0]||null}catch{i=null}if(i){let o;try{o=m("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}t.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${o||"installed"}`,detail:i})}else t.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[o,s]of e){if(!s.workspace||!w(s.workspace)){t.push({severity:"warn",group:"CodeGraph",title:`${o}: workspace missing`,detail:`Workspace path ${s.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let a=y(s.workspace,".codegraph","codegraph.db");w(a)?t.push({severity:"ok",group:"CodeGraph",title:`${o}: index present`,detail:a}):t.push({severity:"warn",group:"CodeGraph",title:`${o}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${s.workspace}\` to build it now.`})}}function D(t){return{errors:t.filter(n=>n.severity==="fail").length,warnings:t.filter(n=>n.severity==="warn").length,ok:t.filter(n=>n.severity==="ok").length}}function ue(t){console.log(),console.log(f.bold(" agentx doctor")),console.log();let n=new Map;for(let i of t)n.has(i.group)||n.set(i.group,[]),n.get(i.group).push(i);for(let[i,o]of n){console.log(f.bold(" "+i));for(let s of o){let a=s.severity==="ok"?f.green("\u2713"):s.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${a} ${s.title}`),s.detail&&console.log(f.dim(" "+s.detail.replace(/\n/g,`
|
|
6
6
|
`))),s.fix&&console.log(f.dim(" \u2192 "+s.fix))}console.log()}let e=D(t);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{P as a,Z as b,Ne as c,J as d,K as e,V as f,U as g,ne as h,oe as i,le as j};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-5RSTB45Q.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-
|
|
1
|
+
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-IYITREE5.js";import{y as C,z as K}from"./chunk-NI2XD6P3.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
|
|
4
4
|
`));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-7RVJWLIP.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as w}from"./chunk-
|
|
1
|
+
import{c as w}from"./chunk-UHTIZCKU.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
|
|
2
2
|
${a.content}`),t.previous??""].join(`
|
|
3
3
|
`),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
|
|
4
4
|
`).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
|
|
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
|
|
|
33
33
|
{"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
|
|
34
34
|
`)+`
|
|
35
35
|
`}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
36
|
+
//# sourceMappingURL=chunk-CF7CPE7K.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Fe}from"./chunk-GTJIKXDB.js";import{C as vn,J as Cn,k as P}from"./chunk-
|
|
1
|
+
import{a as Fe}from"./chunk-GTJIKXDB.js";import{C as vn,J as Cn,k as P}from"./chunk-5LPCJZKI.js";import{f as An,g as In,h as Tn,k as Dn}from"./chunk-WZUY7VGL.js";import{a as k}from"./chunk-N6VBEITO.js";import{b as $n}from"./chunk-2VDO2HEK.js";import{f as En,i as _n,k as Me,l as Ue,n as G,o as j,q as Rn}from"./chunk-LQS27HSV.js";import{t as Sn,u as xn}from"./chunk-SDINSYTN.js";import{d as wn,e as kn}from"./chunk-AQASR6KR.js";import{a as dn,b as pn,d as gn,e as fn}from"./chunk-MNG2AMKZ.js";import{h as K,j as mn,l as hn,m as bn,n as yn}from"./chunk-RX5O5637.js";import{h as on,i as an,j as ln,l as cn,m as un}from"./chunk-TZ7GB7FI.js";import{a as rn,c as sn}from"./chunk-KP7KDLZ2.js";import{Aa as Oe,Ca as Pe,b as Ce,s as Ne,u as Le,xa as nn,za as le}from"./chunk-VK3M3TVL.js";import{r as tn}from"./chunk-SD6UDSXV.js";import{a as Qt,b as ae,e as en}from"./chunk-IRZYRLXQ.js";import{a as Zt}from"./chunk-QUFIUXMQ.js";import{da as Ht,ea as zt,fb as De,ga as Xt,ha as Kt,ob as Gt,p as ie,pb as Jt,q as Vt,r as Bt,s as ro,yb as Yt}from"./chunk-KOY3EOPH.js";import{a as Ie,h as so}from"./chunk-VJ5HC63R.js";import{j as Te,r as oo}from"./chunk-UEEB3UTU.js";import{existsSync as io,readdirSync as ao,readFileSync as lo,statSync as co}from"fs";import{resolve as uo}from"path";function Nn(t,e,n=Date.now(),r=7){let s=r*864e5,o=new Map;for(let i of e){let a=o.get(i.workflowId);a?a.push(i):o.set(i.workflowId,[i])}return t.map(i=>{let a=o.get(i.id)??[],l=a.filter(f=>n-f.at<=s),u=a.filter(f=>n-f.at>s&&n-f.at<=s*2),c=l.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?u.length>0&&l.length===0?"dormant":l.length>0&&c*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:u.length,failed:c,paused:d}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ce=new Map;function Uc(t,e=1e3){if(!io(t))return[];let n=ao(t).filter(o=>o.endsWith(".jsonl")).map(o=>{let i=uo(t,o);return{path:i,mtime:co(i).mtimeMs}}).sort((o,i)=>i.mtime-o.mtime).slice(0,e),r=new Set(n.map(o=>o.path));for(let o of ce.keys())r.has(o)||ce.delete(o);let s=[];for(let{path:o,mtime:i}of n){let a=ce.get(o);if(a&&a.mtime===i){a.summary&&s.push(a.summary);continue}let l=po(o,i);ce.set(o,{mtime:i,summary:l}),l&&s.push(l)}return s}function po(t,e){try{let n=lo(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),s=r.run?.workflowId;if(!s)return null;let o=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),l=a.status??a.run?.status;if(l){o=l;break}}return{workflowId:s,status:o,at:e}}catch{return null}}var Ln=7,go={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},S={routines:200,summary:160,filters:6,filterValue:60,text:120},fo=(t,e,n)=>{try{return tn(t,e,n)}catch{return null}},On=864e5;function qc(t){let e=t.now??Date.now(),n={...go,...t.thresholds},r=t.nextFire??fo,s=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],u=a.timezone||"UTC",c=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:I(a.id,S.text),trigger:{schedule:I(a.schedule,S.text),timezone:u},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?We(a.nextRun)??We(r(a.schedule,new Date(e),u)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:ko(d.status==="success"?void 0:d.errorSummary,S.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Pn(c),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Ln).map(g=>({at:g.startedAt,status:g.status}))};p.flags=Mn(p,c,a.schedule,u,null,e,n,r),s.push(Un(p))}let o=new Map(Nn(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(w=>w.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let u=l.config??{},c=a.state||"active",d=c==="active",p=(i.get(a.id)??[]).slice().sort((w,Ae)=>Ae.at-w.at),g=p.map(w=>({at:w.at,status:bo(w.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof u.spec=="string"?u.spec:"",v=typeof u.timezone=="string"?u.timezone:"UTC",W={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:I(a.title||a.id,S.text),trigger:m?{schedule:I(b,S.text),timezone:v}:{event:I(typeof u.event=="string"?u.event:"",S.text),filters:wo(u.filter,a)},agent:yo(a),enabled:d,state:c,nextRunAt:m&&d&&b?We(r(b,new Date(e),v)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let w=g.find(Ae=>Ae.status==="success");return w?new Date(w.at).toISOString():null})(),consecutiveFailures:Pn(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Ln).map(w=>({at:new Date(w.at).toISOString(),status:w.status}))},oe=Date.parse(a.updated||a.created||"");W.flags=m?Mn(W,g,b,v,Number.isFinite(oe)?oe:null,e,n,r):mo(W,o.get(a.id)?.state==="dormant",Number.isFinite(oe)?oe:null,e,n),s.push(Un(W))}return s.sort(ho).slice(0,S.routines)}function Pn(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function Mn(t,e,n,r,s,o,i,a){let l=[],u=e.length?e[0].at:null;if(!t.enabled){let p=Wn(u,s,o,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),u===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let c=new Date(u),d=null;for(let p=0;p<i.missedFires&&(d=a(n,c,r),!!d);p++)c=d;return d&&o>d.getTime()+i.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(u).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function mo(t,e,n,r,s){let o=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Wn(i,n,r,s);return a&&o.push(a),o}return t.consecutiveFailures>=s.failStreak&&o.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?o.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&o.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),o}function Wn(t,e,n,r){let s=Math.max(t??0,e??0);return s&&n-s<r.disabledDays*On?null:{reason:"disabled-long",detail:s?`Disabled; no activity for ${Math.floor((n-s)/On)} days`:"Disabled and never ran"}}function Un(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var Fn={critical:0,warning:1,info:2};function ho(t,e){let n=t.attention?Fn[t.attention]:3,r=e.attention?Fn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function bo(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function yo(t){if(t.ownerAgent)return I(t.ownerAgent,S.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?I(String(e.config.agentId),S.text):null}function wo(t,e){let n=[],r=e?.project;if(r&&n.push(I(`project=${r}`,S.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[s,o]of Object.entries(t)){let i=Array.isArray(o)?o.map(String):o==null?[]:[String(o)];i.length&&n.push(I(`${s}=${i.join(",")}`,S.filterValue))}return n.slice(0,S.filters)}function We(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function I(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ko(t,e){return t===void 0?void 0:I(t,e)}import{mkdirSync as So,readFileSync as xo,renameSync as vo,writeFileSync as $o}from"fs";import{resolve as Eo}from"path";function jn(t){return Eo(Ue(t),"_state.json")}function $(t){try{let e=JSON.parse(xo(jn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function J(t,e){So(Ue(t),{recursive:!0});let n=jn(t),r=`${n}.${process.pid}.tmp`;$o(r,JSON.stringify(e,null,2)+`
|
|
3
3
|
`),vo(r,n)}function qn(t,e,n,r=Date.now()){let s=$(t),o={};for(let[i,a]of Object.entries(s.snoozed))Date.parse(a)>r&&(o[i]=a);o[e]=n.toISOString(),J(t,{...s,snoozed:o})}function Xc(t,e){J(t,{...$(t),lastDigest:e})}function je(t,e,n,r=Date.now()){let s=$(t),o=new Set(n),i={};for(let[l,u]of Object.entries(s.popped??{}))o.has(l)&&(i[l]=u);i[e]=new Date(r).toISOString();let a=(s.wanted??[]).filter(l=>l!==e&&o.has(l));J(t,{...s,popped:i,wanted:a})}function Vn(t,e){let n=$(t);J(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Kc(t,e=Date.now()){J(t,{...$(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as _o,readFileSync as Ro}from"fs";Yt();so();function Bn(t){let e=Qt(t),n={};if(_o(e))try{n=Gt(JSON.parse(Ro(e,"utf-8")))}catch{n={}}let r=De.safeParse(n?.requests);return r.success?r.data:De.parse(void 0)}async function eu(t,e={}){let n=(t.channels??[]).filter(r=>!Ie.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Ie].join(", ")}`}:ae(r=>{let s=r.requests??={};for(let o of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])t[o]!==void 0&&(s[o]=t[o]);if(t.plans){let o=s.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(o[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((s.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let o=s.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(o[i]=t.catchPromises[i])}if(t.checkers){let o=s.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(o[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as Y,readdirSync as Go,readFileSync as ze}from"fs";import{dirname as Jo,resolve as E}from"path";import{randomBytes as Xn}from"crypto";import{existsSync as Io,mkdirSync as To,readdirSync as Do,readFileSync as Co,renameSync as Kn,unlinkSync as No,writeFileSync as Lo}from"fs";import{resolve as Gn}from"path";function Hn(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Ao=t=>t.trim().split(`
|
|
4
4
|
`).pop()?.slice(0,300)||"no output";async function zn(t,e,n,r=Fe){let s=await r(t.bin,[...Hn(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return s.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Ao(s.stderr||s.stdout)}`}}async function ru(t,e,n,r,s=Fe){return(await s(t.bin,[...Hn(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Oo=2e3,Po=t=>zn(t.wacli,t.to,t.text);function qe(t){return Gn(t,".agentx","whatsapp-triage","drafts")}var Mo=t=>/^[a-z0-9-]{8,64}$/.test(t),ue=(t,e)=>Gn(qe(t),`${e}.json`);function Jn(t,e){To(qe(t),{recursive:!0});let n=ue(t,e.id),r=`${n}.${process.pid}.tmp`;Lo(r,JSON.stringify(e,null,2)+`
|
|
@@ -577,4 +577,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
577
577
|
claude-code ${qt(t)} --arg value
|
|
578
578
|
\`\`\`
|
|
579
579
|
`}Yt();var Qs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function eo(t){return{...Qs,...t??{},regions:{...t?.regions??{}},buffer:{...Qs.buffer,...t?.buffer??{}}}}function lf(t){try{return eo(Jt(t).screen)}catch{return eo(void 0)}}var Oc=/^[a-z][\w-]*$/,to=["window","screen","menubar","notifications"];function se(t,e,n,r){let s=Number(t);if(t===""||t===null||!Number.isFinite(s)||!n(s))throw new Error(`${e} must be ${r}`);return s}var Re=(t,e)=>se(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function no(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function cf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Re(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Re(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Re(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=se(e.stableMs,"stableMs",s=>Number.isInteger(s)&&s>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=se(e.changeThreshold,"changeThreshold",s=>s>=0&&s<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let s={...n.regions??{}};for(let[o,i]of Object.entries(e.regions)){if(!Oc.test(o))throw new Error(`region name "${o}" must be lowercase letters, digits, - or _`);i===null?delete s[o]:s[o]=no(i)}n.regions=s}if(e.buffer&&typeof e.buffer=="object"){let s=e.buffer,o={...n.buffer??{}};"enabled"in s&&(o.enabled=!!s.enabled),"seconds"in s&&(o.seconds=se(s.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in s&&(o.fps=se(s.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in s&&(o.maxPixels=Re(s.maxPixels,"buffer.maxPixels")),"region"in s&&(o.region=String(s.region).trim()),n.buffer=o}let r=n.buffer?.region;if(r!==void 0&&!to.includes(r)&&!n.regions?.[r])try{no(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...to,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Nn as a,Uc as b,kt as c,Aa as d,Ia as e,Jd as f,Yd as g,Zd as h,tp as i,np as j,rp as k,Qr as l,es as m,sp as n,ts as o,ip as p,lp as q,L as r,ns as s,S as t,qc as u,os as v,fp as w,bp as x,as as y,yp as z,ls as A,wp as B,ee as C,nl as D,kp as E,Sp as F,us as G,ru as H,Po as I,cu as J,Zn as K,du as L,$ as M,Xc as N,Kc as O,wu as P,pe as Q,ku as R,Bn as S,eu as T,M as U,Vu as V,pr as W,gr as X,gi as Y,fi as Z,zu as _,Xu as $,Si as aa,Yu as ba,ps as ca,$p as da,ed as ea,td as fa,Gr as ga,dt as ha,Sa as ia,Es as ja,eg as ka,tg as la,jl as ma,og as na,Ds as oa,ig as pa,ag as qa,gg as ra,Zl as sa,fg as ta,rd as ua,sd as va,od as wa,id as xa,ad as ya,ld as za,ud as Aa,dd as Ba,kd as Ca,nt as Da,Sd as Ea,xd as Fa,Z as Ga,Q as Ha,sc as Ia,vg as Ja,$g as Ka,Eg as La,_g as Ma,Tt as Na,Rg as Oa,ot as Pa,it as Qa,ke as Ra,Xi as Sa,Gi as Ta,Rd as Ua,lt as Va,ct as Wa,Ji as Xa,Yi as Ya,Ur as Za,qr as _a,Ad as $a,ea as ab,Id as bb,la as cb,da as db,ut as eb,ga as fb,Vr as gb,O as hb,qs as ib,Vs as jb,Bs as kb,Ct as lb,Ng as mb,gc as nb,zs as ob,Xs as pb,Bg as qb,Hg as rb,Ic as sb,zg as tb,Gs as ub,Se as vb,jd as wb,yt as xb,Kd as yb,Jg as zb,Yg as Ab,Zg as Bb,Qg as Cb,ef as Db,tf as Eb,nf as Fb,rf as Gb,sf as Hb,Qs as Ib,eo as Jb,lf as Kb,to as Lb,cf as Mb};
|
|
580
|
-
//# sourceMappingURL=chunk-
|
|
580
|
+
//# sourceMappingURL=chunk-DUZOHLTF.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-XJWSLJ4O.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-FRVFRWFN.js.map
|