agentix-cli 0.75.0 → 0.75.2
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/apps/mac-voice/Sources/AgentXVoice/PillMenu.swift +16 -0
- package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +3 -3
- package/dist/{agent-UOOL6R4V.js → agent-B46X7Y6V.js} +2 -2
- package/dist/{board-dashboard-CDBPGUU3.js → board-dashboard-W64VXH6Y.js} +2 -2
- package/dist/{chunk-OEUII2QP.js → chunk-2HMI5PJG.js} +2 -2
- package/dist/{chunk-5B5J3WVW.js → chunk-55RM7V4N.js} +2 -2
- package/dist/{chunk-SKIDVXWG.js → chunk-663BLK67.js} +2 -2
- package/dist/{chunk-APYG4RB3.js → chunk-6CCJMHBA.js} +2 -2
- package/dist/{chunk-YZVX4RDY.js → chunk-7ZO2UZRI.js} +11 -11
- package/dist/{chunk-L3MEAKL7.js → chunk-CAVAMWI5.js} +2 -2
- package/dist/{chunk-BAPRRPNU.js → chunk-F2RIMHW5.js} +2 -2
- package/dist/{chunk-6HPJKD3X.js → chunk-KHEI4VNM.js} +13 -13
- package/dist/{chunk-6HPJKD3X.js.map → chunk-KHEI4VNM.js.map} +1 -1
- package/dist/{chunk-LWPRFAQX.js → chunk-KIXYU2DD.js} +4 -4
- package/dist/{chunk-KEJOBB5E.js → chunk-NWL5KPBJ.js} +2 -2
- package/dist/chunk-PBUJBWOF.js +152 -0
- package/dist/chunk-PBUJBWOF.js.map +1 -0
- package/dist/{chunk-WC4TPXD3.js → chunk-Q2FFZX7Y.js} +2 -2
- package/dist/{chunk-ISBM2C3D.js → chunk-RGTHA2EI.js} +2 -2
- package/dist/{chunk-UBGQ7AOG.js → chunk-TS4JCBSP.js} +2 -2
- package/dist/{chunk-66VSATH3.js → chunk-UJ5JLS6Z.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1 -1
- package/dist/{program-EHCDAWI7.js → program-3DBXC6DX.js} +2 -2
- package/dist/{promote-KSYTHPYB.js → promote-PMMUU4G2.js} +2 -2
- package/dist/{query-GRLLX7RG.js → query-CB6FV6JU.js} +2 -2
- package/dist/{registry-WJRF3D5H.js → registry-A2LPURNS.js} +2 -2
- package/dist/{request-planner-G2NJIXQY.js → request-planner-44WOTYCY.js} +2 -2
- package/dist/{review-candidates-F5QKVUQ4.js → review-candidates-BZLS37MN.js} +2 -2
- package/dist/{routing-XIDQWGKT.js → routing-CPLPRA2E.js} +2 -2
- package/dist/{seat-DNI7G7B2.js → seat-CBAZAYGY.js} +2 -2
- package/dist/{select-L45K2452.js → select-4CW3CXBU.js} +2 -2
- package/dist/wiki-4LKOLCP4.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-DIHLL45I.js +0 -152
- package/dist/chunk-DIHLL45I.js.map +0 -1
- package/dist/wiki-WWVSDXSX.js +0 -2
- /package/dist/{agent-UOOL6R4V.js.map → agent-B46X7Y6V.js.map} +0 -0
- /package/dist/{board-dashboard-CDBPGUU3.js.map → board-dashboard-W64VXH6Y.js.map} +0 -0
- /package/dist/{chunk-OEUII2QP.js.map → chunk-2HMI5PJG.js.map} +0 -0
- /package/dist/{chunk-5B5J3WVW.js.map → chunk-55RM7V4N.js.map} +0 -0
- /package/dist/{chunk-SKIDVXWG.js.map → chunk-663BLK67.js.map} +0 -0
- /package/dist/{chunk-APYG4RB3.js.map → chunk-6CCJMHBA.js.map} +0 -0
- /package/dist/{chunk-YZVX4RDY.js.map → chunk-7ZO2UZRI.js.map} +0 -0
- /package/dist/{chunk-L3MEAKL7.js.map → chunk-CAVAMWI5.js.map} +0 -0
- /package/dist/{chunk-BAPRRPNU.js.map → chunk-F2RIMHW5.js.map} +0 -0
- /package/dist/{chunk-LWPRFAQX.js.map → chunk-KIXYU2DD.js.map} +0 -0
- /package/dist/{chunk-KEJOBB5E.js.map → chunk-NWL5KPBJ.js.map} +0 -0
- /package/dist/{chunk-WC4TPXD3.js.map → chunk-Q2FFZX7Y.js.map} +0 -0
- /package/dist/{chunk-ISBM2C3D.js.map → chunk-RGTHA2EI.js.map} +0 -0
- /package/dist/{chunk-UBGQ7AOG.js.map → chunk-TS4JCBSP.js.map} +0 -0
- /package/dist/{chunk-66VSATH3.js.map → chunk-UJ5JLS6Z.js.map} +0 -0
- /package/dist/{program-EHCDAWI7.js.map → program-3DBXC6DX.js.map} +0 -0
- /package/dist/{promote-KSYTHPYB.js.map → promote-PMMUU4G2.js.map} +0 -0
- /package/dist/{query-GRLLX7RG.js.map → query-CB6FV6JU.js.map} +0 -0
- /package/dist/{registry-WJRF3D5H.js.map → registry-A2LPURNS.js.map} +0 -0
- /package/dist/{request-planner-G2NJIXQY.js.map → request-planner-44WOTYCY.js.map} +0 -0
- /package/dist/{review-candidates-F5QKVUQ4.js.map → review-candidates-BZLS37MN.js.map} +0 -0
- /package/dist/{routing-XIDQWGKT.js.map → routing-CPLPRA2E.js.map} +0 -0
- /package/dist/{seat-DNI7G7B2.js.map → seat-CBAZAYGY.js.map} +0 -0
- /package/dist/{select-L45K2452.js.map → select-4CW3CXBU.js.map} +0 -0
- /package/dist/{wiki-WWVSDXSX.js.map → wiki-4LKOLCP4.js.map} +0 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/// "Show floating pill" in the menu.
|
|
2
|
+
///
|
|
3
|
+
/// Closing the pill hides it without turning the setting off, so the
|
|
4
|
+
/// setting alone said "checked" over an empty screen, and the first click
|
|
5
|
+
/// only turned it off. The checkmark follows what is on screen instead,
|
|
6
|
+
/// and a click on an unchecked item always brings the pill back.
|
|
7
|
+
enum PillMenu {
|
|
8
|
+
static func isChecked(showPill: Bool, visible: Bool) -> Bool {
|
|
9
|
+
showPill && visible
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/// The setting after a click.
|
|
13
|
+
static func click(showPill: Bool, visible: Bool) -> Bool {
|
|
14
|
+
!isChecked(showPill: showPill, visible: visible)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -47,7 +47,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
47
47
|
var onHidePill: (() -> Void)?
|
|
48
48
|
/// Put the pill back in the bottom-right corner.
|
|
49
49
|
var onResetPosition: (() -> Void)?
|
|
50
|
-
/// Whether the pill is on screen, for "Hide pill".
|
|
50
|
+
/// Whether the pill is on screen, for "Hide pill" and "Show floating pill".
|
|
51
51
|
var pillVisible: () -> Bool = { false }
|
|
52
52
|
var onSettings: (() -> Void)?
|
|
53
53
|
|
|
@@ -238,7 +238,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
238
238
|
hold.state = Hold.isOn ? .on : .off
|
|
239
239
|
menu.addItem(hold)
|
|
240
240
|
let pill = action("Show floating pill", #selector(togglePill), key: "")
|
|
241
|
-
pill.state = Config.showPill ? .on : .off
|
|
241
|
+
pill.state = PillMenu.isChecked(showPill: Config.showPill, visible: pillVisible()) ? .on : .off
|
|
242
242
|
menu.addItem(pill)
|
|
243
243
|
let orb = action("Animated orb", #selector(toggleOrb), key: "")
|
|
244
244
|
orb.state = Config.animatedOrb ? .on : .off
|
|
@@ -293,7 +293,7 @@ final class StatusMenu: NSObject, NSMenuDelegate {
|
|
|
293
293
|
}
|
|
294
294
|
|
|
295
295
|
@objc private func togglePill() {
|
|
296
|
-
Config.showPill.
|
|
296
|
+
Config.showPill = PillMenu.click(showPill: Config.showPill, visible: pillVisible())
|
|
297
297
|
onPillChanged?(Config.showPill)
|
|
298
298
|
}
|
|
299
299
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as a,B as b,C as c}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=agent-
|
|
1
|
+
import{A as a,B as b,C as c}from"./chunk-F2RIMHW5.js";import"./chunk-SFQUP3BP.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import"./chunk-QIJLFPWE.js";export{a as createAgentContext,b as generate,c as generateStream};
|
|
2
|
+
//# sourceMappingURL=agent-B46X7Y6V.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as gn}from"./chunk-2NYP4OQU.js";import{a as kn}from"./chunk-62EJKQFX.js";import{a as le,b as hn}from"./chunk-JWDJMFU6.js";import{a as A,b as _n,c as En,d as Sn,e as Tn,h as An,i as Re,j as Cn,k as In,l as Ln,m as Rn,n as $n}from"./chunk-
|
|
1
|
+
import{a as gn}from"./chunk-2NYP4OQU.js";import{a as kn}from"./chunk-62EJKQFX.js";import{a as le,b as hn}from"./chunk-JWDJMFU6.js";import{a as A,b as _n,c as En,d as Sn,e as Tn,h as An,i as Re,j as Cn,k as In,l as Ln,m as Rn,n as $n}from"./chunk-TS4JCBSP.js";import{a as Mn}from"./chunk-Z3IP66SL.js";import{a as xn,b as U,c as vn,d as L,e as O,j as lt,k as ct,l as ne,m as W,n as dt,o as bn,p as yn,q as wn}from"./chunk-C4CDVE2E.js";import{$a as it,Aa as rn,Ba as on,H as tt,I as at,J as Va,K as Ya,Ka as sn,Ma as Me,R as z,Ra as cn,S as Qa,T as Za,Ta as Le,Ua as nt,Va as rt,Wa as ot,Xa as st,Ya as dn,Za as pn,_a as un,a as Fa,bb as mn,c as Ze,d as Dt,e as qa,eb as fn,i as et,l as He,n as Ua,p as ae,q as ye,r as Xa,s as Ht,xa as an,za as nn}from"./chunk-663BLK67.js";import{g as Ba,h as za}from"./chunk-RGTHA2EI.js";import{p as Wa,s as Ga}from"./chunk-BYJ3A55Y.js";import{c as ln}from"./chunk-7XB2CVC3.js";import{a as en,b as tn}from"./chunk-LQRBGQIR.js";import"./chunk-Q2FFZX7Y.js";import"./chunk-AQASR6KR.js";import{b as Ka,c as Ja}from"./chunk-2D3RYIDU.js";import{a as Pa,f as ja,g as Ot,h as Nt,l as Oa,m as Na,n as Da,t as Ye,u as Qe,v as ie,w as Ha}from"./chunk-2HMI5PJG.js";import"./chunk-WP6KLXTP.js";import{a as Ie}from"./chunk-N6EWZGIX.js";import"./chunk-DP7RTNDM.js";import"./chunk-S5JGQKON.js";import"./chunk-2AXFYDWF.js";import"./chunk-AFRHKA7B.js";import"./chunk-PUU2ESI2.js";import"./chunk-IR2Q63IV.js";import"./chunk-CAVAMWI5.js";import"./chunk-UJ5JLS6Z.js";import"./chunk-KA2UIZXG.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-QD6IICK7.js";import"./chunk-CECHWYJ2.js";import{g as $a}from"./chunk-NWL5KPBJ.js";import"./chunk-WPNRDEHW.js";import"./chunk-2GIDVZ4H.js";import"./chunk-KHEI4VNM.js";import"./chunk-FX3D7YON.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-QOYAX2FT.js";import"./chunk-5MUJZODV.js";import"./chunk-7I7IEX4S.js";import{A as te,D as jt,a as La,b as Ra,c as Qs,r as Ve,s as Zs}from"./chunk-CXZ4YDHJ.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";function Bt(t,e,a=Date.now()){let n=Math.max(0,a-(t.updatedAt||a)),r=t.clientId?e[t.clientId]:void 0;if(!r)return{score:n/864e5,ageMs:n,rising:!1,overdue:!1};let o=n/(r*6e4);return{score:1e3+o,ageMs:n,rising:!0,overdue:o>=1}}function Pn(t,e,a=Date.now()){return t.map((n,r)=>({i:r,s:Bt(n,e,a).score})).sort((n,r)=>r.s-n.s||n.i-r.i).map(n=>n.i)}var re={refresh:'<path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/>',clock:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',alert:'<path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/>',gavel:'<path d="M12 3 6 9"/><path d="m9 6 6 6"/><path d="M15 9 9 15"/><path d="m12 12 6 6"/><path d="M4 21h10"/>',loop:'<path d="M17 2l4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>',broom:'<path d="M3 21h18"/><path d="M12 3v9"/><path d="m7 12 5-3 5 3-1.5 6h-7Z"/>',server:'<rect x="2" y="3" width="20" height="7" rx="2"/><rect x="2" y="14" width="20" height="7" rx="2"/><path d="M6 6.5h.01"/><path d="M6 17.5h.01"/>',inbox:'<path d="M21 12h-6l-2 3h-2l-2-3H3"/><path d="M5 5h14l2 7v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Z"/>',cross:'<circle cx="12" cy="12" r="9"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',file:'<path d="M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7Z"/><path d="M14 2v5h5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',chev:'<path d="m6 9 6 6 6-6"/>',chevr:'<path d="m9 6 6 6-6 6"/>',ext:'<path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>',pulse:'<path d="M3 12h4l3-8 4 16 3-8h4"/>',plug:'<path d="M9 2v6"/><path d="M15 2v6"/><path d="M6 8h12v3a6 6 0 0 1-12 0Z"/><path d="M12 17v5"/>',check:'<path d="M20 6 9 17l-5-5"/>',route:'<circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a4 4 0 0 0 0-8H9a4 4 0 0 1 0-8h6"/>',branch:'<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="8" r="3"/><path d="M18 11v1a3 3 0 0 1-3 3H9"/><path d="M6 9v6"/>',send:'<path d="M22 2 11 13"/><path d="M22 2l-7 20-4-9-9-4Z"/>',msg:'<path d="M21 11.5a8.4 8.4 0 0 1-12.9 7.5L3 21l2-5.1A8.4 8.4 0 1 1 21 11.5Z"/>',code:'<path d="m9 18-6-6 6-6"/><path d="m15 6 6 6-6 6"/>',hash:'<path d="M4 9h16"/><path d="M4 15h16"/><path d="M10 3 8 21"/><path d="M16 3l-2 18"/>',x:'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',trace:'<path d="M4 4v16h16"/><path d="m7 15 4-4 3 3 5-6"/>'},we=(t,e=14)=>'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="'+e+'" height="'+e+'" aria-hidden="true">'+t+"</svg>",pt=(t,e,a,n="")=>'<div class="ax-sec-label"><h3>'+we(t,13)+e+(a?'<span class="ax-sec-label__n" id="'+a+'"></span>':"")+"</h3>"+n+"</div>";function jn(t={}){return L({title:"AgentX \xB7 Monitor",activeTab:"monitor",subtitle:"Monitor",peers:t.peers,body:`<div class="bf">
|
|
2
2
|
|
|
3
3
|
<div class="bf-head">
|
|
4
4
|
<div>
|
|
@@ -18459,4 +18459,4 @@ data: ${h.replace(/\n/g," ")}
|
|
|
18459
18459
|
`)}catch{}}};s.stdout?.on("data",l),s.stderr?.on("data",l);let c=setInterval(()=>{try{e.write(`: hb
|
|
18460
18460
|
|
|
18461
18461
|
`)}catch{}},15e3),p=()=>{clearInterval(c);try{s.kill()}catch{}try{e.end()}catch{}};t.on("close",p),s.on("exit",p),s.on("error",p)}async function Fs(t,e,a,n){let r=a.url+n,o=(t.method||"GET").toUpperCase(),i=o!=="GET"&&o!=="HEAD"?await new Promise((u,m)=>{let h=[];t.on("data",w=>h.push(w)),t.on("end",()=>u(Buffer.concat(h))),t.on("error",m)}):void 0,l={},c=t.headers["content-type"];c&&(l["Content-Type"]=Array.isArray(c)?c[0]:c);let p=t.headers["x-requested-with"];p&&(l["X-Requested-With"]=Array.isArray(p)?p[0]:p),a.token&&(l.Authorization=`Bearer ${a.token}`),l["X-Agentx-Peer"]="primary";try{let u=await fetch(r,{method:o,headers:l,body:i&&i.length>0?i:void 0}),m=Buffer.from(await u.arrayBuffer());e.writeHead(u.status,{"Content-Type":u.headers.get("content-type")||"application/json","Cache-Control":"no-store"}),e.end(m)}catch(u){y(e,502,{error:`proxy to peer failed: ${u?.message||u}`,target:r})}}function Je(t,e){let a=t.replace(/\/+$/,""),n=(e.dashboard?.daemons||[]).find(r=>r.url.replace(/\/+$/,"")===a);return n?{url:Ks(n),token:n.dashboardToken||n.token}:null}export{Zp as applyAttachSessions,Gp as fetchDaemonAgents,Bp as handleBoardRequest,Vx as resetLiveCaches,be as resolveNodeTargets,Jx as startBoardDashboard,Qp as withLastGood};
|
|
18462
|
-
//# sourceMappingURL=board-dashboard-
|
|
18462
|
+
//# sourceMappingURL=board-dashboard-W64VXH6Y.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as Je,c as Ye}from"./chunk-WP6KLXTP.js";import{a as ne}from"./chunk-N6EWZGIX.js";import{b as ae}from"./chunk-AFRHKA7B.js";import{b as He,e as Ue,f as Ke,i as Be,k as ze,l as qe,q as Ge}from"./chunk-PUU2ESI2.js";import{c as Ce,e as _e,f as Le}from"./chunk-KA2UIZXG.js";import{e as Fe,g as je,h as Me,i as se}from"./chunk-GQ76J72O.js";import{a as Ee,b as re,c as oe,d as De,e as ie}from"./chunk-QD6IICK7.js";import{v as We,w as Vt}from"./chunk-
|
|
1
|
+
import{b as Je,c as Ye}from"./chunk-WP6KLXTP.js";import{a as ne}from"./chunk-N6EWZGIX.js";import{b as ae}from"./chunk-AFRHKA7B.js";import{b as He,e as Ue,f as Ke,i as Be,k as ze,l as qe,q as Ge}from"./chunk-PUU2ESI2.js";import{c as Ce,e as _e,f as Le}from"./chunk-KA2UIZXG.js";import{e as Fe,g as je,h as Me,i as se}from"./chunk-GQ76J72O.js";import{a as Ee,b as re,c as oe,d as De,e as ie}from"./chunk-QD6IICK7.js";import{v as We,w as Vt}from"./chunk-KHEI4VNM.js";import{b as Oe,f as Gt}from"./chunk-72SZI2UW.js";import{c as Te,d as Ne}from"./chunk-QOYAX2FT.js";import{existsSync as Zt,mkdirSync as Ve,readFileSync as Qt,writeFileSync as Xt,renameSync as en}from"fs";import{resolve as Ze,dirname as tn}from"path";var Qe=class{filePath;log;constructor(e={}){let t=e.baseDir??Ze(process.cwd(),".agentx");this.filePath=Ze(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Ve(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Zt(this.filePath))return{version:1,overrides:{}};try{let e=Qt(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Ve(tn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Xt(t,JSON.stringify(e,null,2)),en(t,this.filePath)}get(e,t,r){let i=this.load().overrides[this.key(e,t,r)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),i=this.key(e,t,r);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),i=o.overrides[this.key(e,t,r)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as rt,writeFileSync as de,appendFileSync as sn,mkdirSync as an,existsSync as ot,statSync as dn}from"fs";import{resolve as L}from"path";var Xe="[Agent Memory \u2014 persistent facts from past conversations]",nn=2400;function et(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function rn(n,e=Date.now()){let t=_e(n,e),r=n.undated?"UNVERIFIED (never checked) ":et(t,Fe(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function on(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=Me(n,e);return{line:`- [${n.category}] ${et(o,je(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function tt(n,e=[],t=Date.now()){let r=[],o=new Set,i=Xe.length,s=!1;for(let a of n){let d=e.length>0?Le(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),c=rn(d,t),u=d.id}else c=on(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?se.length:0;if(i+f+c.line.length>nn)break;r.push({fact:a,...c,...u?{wikiRef:u}:{}}),i+=f+c.line.length,f&&(s=!0)}return r}function nt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[se]:[];return[Xe,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var it=200,cn=7,st=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=L(e,".agentx/memory"),this.ledger=new Ce(L(e,".agentx/wiki")),ot(this.memoryDir)||an(this.memoryDir,{recursive:!0})}filePath(e){return L(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||re(t.content))return!1;let r=t.source.trust??Ee(t.source.channel),o=t.review??De(r),i={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return sn(this.filePath(e),JSON.stringify(i)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!ot(t))return[];try{let{mtimeMs:r,size:o}=dn(t),i=this.parsedCache.get(t);if(i&&i.mtimeMs===r&&i.size===o)return i.facts.slice();let a=rt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(ie);if(o.length===0)return[];let i=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=L(this.memoryDir,`${t}_bm25_cache.json`),a=Ne(i,s),d=Te(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,h)=>{let m=c.get(h)??0;return g.category==="commitment"&&(m+=1),{memory:g,score:m}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,h)=>h.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return nt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return tt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),i=!1;for(let s of r)if(o.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),i=!0}i&&de(this.filePath(e),r.map(s=>JSON.stringify(s)).join(`
|
|
@@ -18,4 +18,4 @@ import{b as Je,c as Ye}from"./chunk-WP6KLXTP.js";import{a as ne}from"./chunk-N6E
|
|
|
18
18
|
`)}clearIndex(e){let t=this.indexPath(e);if(E(t))try{St(t)}catch{}}};import{existsSync as At,mkdirSync as Cn,readFileSync as _n,unlinkSync as Ln,writeFileSync as Hn}from"fs";import{resolve as he}from"path";import{z as D}from"zod";var Rt=D.object({version:D.literal(1),nodes:D.record(D.object({x:D.number(),y:D.number()}))}),we=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??he(process.cwd(),".agentx/workflows"),this.layoutsDir=he(this.baseDir,"_layouts"),Cn(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return he(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!At(t))return null;try{let r=Rt.safeParse(JSON.parse(_n(t,"utf-8")));return r.success?r.data:null}catch{return null}}save(e,t){let r=Rt.parse(t);return Hn(this.pathFor(e),JSON.stringify(r,null,2)+`
|
|
19
19
|
`),r}sync(e,t){let r=this.get(e);if(!r)return null;let o={};for(let s of t)r.nodes[s]&&(o[s]=r.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return At(t)?(Ln(t),!0):!1}};function $t(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Un(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&t++;return t/Math.max(n.size,e.size)}function Kn(n,e){let t=$t(n.message),r=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of r){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===n.agentId&&(s+=.25,a.push("owner-agent")),n.channel&&i.tags.includes(n.channel)&&(s+=.15,a.push("channel-tag")),n.intentPath?.length&&i.intentPath.length){let p=n.intentPath.filter((f,g)=>i.intentPath[g]===f).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),c=Un(t,$t(d));c>0&&(s+=Math.min(.35,c),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let u=Math.max(0,Math.min(1,s));(!o||u>o.confidence)&&(o={workflow:i,confidence:u,reasons:a})}return o&&o.confidence>0?o:null}function ye(n){let{workflow:e,fromNodeId:t,selectedPort:r}=n,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(r??"")):i).map(a=>a.to)}}function ke(n,e){let t=n.config.cases??[],r=n.config.default??"";for(let o of t)if(Bn(o.when,e))return o.to;return r}function Bn(n,e){let t=n.params??{},r=String(t.path??""),o=q(e,r);switch(n.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function q(n,e){if(!e)return;let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function J(n){let e=n.nodes.find(r=>r.type.startsWith("trigger."));if(!e)return null;let t=n.edges.filter(r=>r.from===e.id).map(r=>r.to);return{triggerId:e.id,pending:t}}function N(n,e){return n.nodes.find(t=>t.id===e)}Gt();Vt();function zn(n,e,t){let r=n.split(".");if(r[0]==="env"){if(r.length!==2)return"";let i=r[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of r){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function A(n,e,t={}){let r=new Set(t.envAllow||[]);return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>zn(i,e,r))}function b(n,e,t={}){let r={};for(let[o,i]of Object.entries(n))typeof i=="string"?r[o]=A(i,e,t):Array.isArray(i)?r[o]=i.map(s=>typeof s=="string"?A(s,e,t):s):i&&typeof i=="object"?r[o]=b(i,e,t):r[o]=i;return r}var xt="workflow-classify",Y="unsure",Pt=async n=>{let e=n.node.config,t=n.run.context,r={envAllow:n.workflow.envAllow},o=A(String(e.input??""),t,r).trim();if(!o)return{error:`classify node "${n.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(m=>[String(m),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([m,y])=>[m,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${n.node.id}" needs at least two labels`};if(a.includes(Y))return{error:`classify node "${n.node.id}": "${Y}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,c=e.instructions?A(String(e.instructions),t,r):void 0,u={input:o};if(e.state&&typeof e.state=="object")for(let[m,y]of Object.entries(e.state)){let w=typeof y=="string"?A(y,t,r):y;(w===null||["string","number","boolean"].includes(typeof w))&&(u[m]=w)}let p=await We(xt,u,{label:Oe(s,c)},{features:{workflow:n.workflow.id,node:n.node.id}});if(!p)return{error:`classify node "${n.node.id}": decision seat unavailable (set decisions.seats.${xt}.mode)`};let f=p.answers.label,g=f.confidence>=d,h=g?f.choice:Y;return n.log(`[node:${n.node.id}] classify \u2192 ${f.choice} (${f.confidence.toFixed(2)})${g?"":` \u2014 below ${d}, routing to ${Y}`}`),{output:{result:f.choice,label:f.choice,confidence:f.confidence,probabilities:f.probabilities,unsure:!g,port:h},port:h}};var be=class{active=new Map;waiters=new Map;async acquire(e,t){let r=this.active.get(e)??0;if(r<t){this.active.set(e,r+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let r=this.waiters.get(e);r&&r.length>0&&r.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},G=new be;function Tt(n,e){return`${n}:${e}`}var F=async n=>({output:n.run.context[n.node.id]??{}}),qn=async n=>{let e=n.node.config,t=String(e.agentId??""),r=String(e.prompt??"");if(!t)return{error:`agent node "${n.node.id}" missing config.agentId`};let o=A(r,n.run.context,{envAllow:n.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${n.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?Tt(n.workflow.id,n.node.id):null;if(d&&a){let u=G.stats(d);u.active>=a&&n.log(`[node:${n.node.id}] gated: ${u.active} active (cap ${a}), ${u.waiting+1} waiting`),await G.acquire(d,a)}let c=Date.now();try{let u=await n.agents.execute({agentId:t,message:o,workflowRunId:n.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-c;if(u.error){let h=u.errorKind??"unknown";return n.log(`[node:${n.node.id}] agent "${t}" failed (${h}): ${u.error}`),{error:`[${h}] ${u.error}`}}let g=String(e.resultParser??"acme-result-token")==="json"?hr(u.content):Ot(u.content);return{output:{reply:u.content,result:g.result,json:g.json,taskId:u.taskId,durationMs:p,...u.autonomyBlocks?.length?{autonomyBlocks:u.autonomyBlocks}:{}}}}catch(u){return n.log(`[node:${n.node.id}] agent "${t}" threw: ${u.message}`),{error:u.message}}finally{d&&G.release(d)}},Jn=async n=>{let e=ke(n.node,n.run.context);return e?{output:{port:e},port:e}:(n.log(`[node:${n.node.id}] branch matched no case and no default port`),{output:{port:null}})},Yn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.text??"");if(!t||!r){let a=String(n.node.config.chatId??""),d=String(n.node.config.channel??""),c=[];return t||c.push(`channel config="${d}" rendered=""`),r||c.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&c.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${n.node.id}" needs channel + chatId \u2014 ${c.join("; ")}`}}let i=Ie(n,e.accountId),s=n.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:r,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(n.forwardChannelSend)try{return{output:{messageId:(await n.forwardChannelSend({channel:t,chatId:r,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return n.log(`[node:${n.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return n.log(`[node:${n.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},Gn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!r||!o)return{error:`action.createIssue "${n.node.id}" needs project + title`};let d=Se(n),c=n.channels[t];if(!c?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let u=await c.createIssue({project:r,title:o,description:i,labels:s,assignees:a,agentId:d});return u?{output:{issue:{iid:u.iid,url:u.url,webUrl:u.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(u){return{error:`action.createIssue failed: ${u.message}`}}},Vn=async()=>({output:{}}),Zn=async n=>{let e=n.node.config,t=String(e.name??n.node.id),r=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:n.node.id,checkpointName:t,resumeMatch:{...r,...o}}}},Qn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!r||!o)return{error:`action.setLabel "${n.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=n.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=Se(n),c=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:r,kind:c,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},Xn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??"");if(!r||!o)return{error:`action.readLabel "${n.node.id}" needs project + iid`};let i=n.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:r,kind:s,iid:o})??[]}}},er=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!r||!o)return{error:`action.react "${n.node.id}" needs channel + chatId + messageId`};let s=Ie(n,e.accountId),a=n.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(r,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},tr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!r||!o||!i)return{error:`action.editMessage "${n.node.id}" needs channel + chatId + messageId + text`};let a=Ie(n,e.accountId),d=n.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(r,o,i,s,a)}}}catch(c){return{error:`action.editMessage failed: ${c.message}`}}},nr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.chatId??""),o=Number(e.durationMs??0);if(!r||!o)return{error:`action.logTime "${n.node.id}" needs chatId + durationMs`};let i=n.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=Se(n);try{return await i.logTimeSpent(r,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},rr=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${n.node.id}" needs url`};let r=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:r,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},or=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${n.node.id}" needs actionId`};let r=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-TWQPEM5V.js"),{runAction:i}=await import("./runner-56G3N7M4.js"),s=new o().get(t);if(!s)return{error:`action.run "${n.node.id}": no action "${t}" in registry`};try{let a=await i(s,r),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},ir=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${n.node.id}" needs a "name" (e.g. "http.fetch")`};let r=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-W6KNX7RS.js");if(!i(t))return{error:`action.builtin "${n.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,r)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},sr=async n=>{let e=n.node.config,t=n.run.context;return typeof e.path=="string"&&e.path?{output:{value:q(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:n.workflow.envAllow})}:{output:{}}};function ar(n){if(n!=null){if(typeof n=="number")return new Date(Date.now()+n*6e4).toISOString();if(typeof n=="object"&&n&&"minutes"in n){let e=Number(n.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof n=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(n);if(e){let t=Number(e[1]??0),r=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+r)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var dr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.workflowId??"");if(!r)return{error:`subProcess "${n.node.id}" missing config.workflowId`};let o=n.run.depth??0,i=n.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${n.workflow.id} \u2192 ${r} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...n.run.context};else if(s&&typeof s=="object")for(let[d,c]of Object.entries(s))c&&typeof c=="object"&&!Array.isArray(c)?a[d]=b(c,n.run.context,{envAllow:n.workflow.envAllow}):typeof c=="string"&&(a[d]={value:A(c,n.run.context,{envAllow:n.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:n.node.id,childRunId:"",childWorkflowId:r},spawnChild:{workflowId:r,input:a}}},cr=F,lr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.emit "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:r,scope:o,payload:i},emitSignal:{name:r,scope:o,payload:i}}},ur=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.wait "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:n.node.id,signalName:r,match:i,scope:o}}},pr=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=ar(t.after??e.after);return r?{paused:!0,pausedAt:{kind:"timerWait",nodeId:n.node.id,fireAt:r}}:{error:`timer.boundary "${n.node.id}" needs config.after (duration or minutes)`}},fr=async()=>({output:{}}),gr=async n=>{let e=n.node.config,r=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?A(s,n.run.context,{envAllow:n.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==r.length)continue;let d=!0;for(let c=0;c<a.length;c++)if(!mr(a[c],r[c])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function mr(n,e){if(n==null||n==="*")return!0;let t=String(n),r=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof r=="number"?r:Number(r);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(r)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(r))}catch{return!1}return String(r)===t}var Nt={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":cr,agent:qn,classify:Pt,branch:Jn,transform:sr,"gateway.parallel":fr,rule:gr,"action.send":Yn,"action.createIssue":Gn,"action.setLabel":Qn,"action.readLabel":Xn,"action.react":er,"action.editMessage":tr,"action.logTime":nr,"action.callHTTP":rr,"action.run":or,"action.builtin":ir,subProcess:dr,"signal.emit":lr,"signal.wait":ur,"timer.boundary":pr,checkpoint:Zn,end:Vn};function ve(n){return Nt[n]}function Ie(n,e){if(typeof e=="string"&&e)return e;let t=n.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=n.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function Se(n){for(let e=n.run.history.length-1;e>=0;e--){let t=n.run.history[e],r=n.workflow.nodes.find(o=>o.id===t.nodeId);if(r?.type==="agent")return r.config.agentId??void 0}}function Ot(n){if(!n)return{};let e=n.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=n.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function hr(n){let{result:e}=Ot(n);if(!n)return{result:e};let t=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var j=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function V(n,e){if(n.name!==e.name||n.scope==="workflow"&&n.workflowId!==e.workflowId)return!1;for(let[t,r]of Object.entries(n.match??{}))if(!(r===void 0||r===""||r==="*")&&e.payload[t]!==r)return!1;return!0}function wr(n,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${n.workflowId}:${n.eventId}`,project:n.project,subject:`workflow:${n.workflowId}:entity:${n.entityRef.backend}:${n.entityRef.id}`,intent:`workflow.${n.triggerSource}`,rawJson:e}}function yr(n){return n.claimed&&n.runId?{agentId:`workflow-run:${n.runId}`,outcome:"dispatched",reason:n.reason??"claimed"}:n.claimed&&!n.runId?{agentId:null,outcome:"halted",reason:n.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:n.reason??"not-claimed"}}function kr(n){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:n.agentId,outcome:n.outcome==="deduped"?"halted":n.outcome,reason:n.outcome==="deduped"?`legacy-dedup: ${n.reason??""}`.trim():n.reason??null})}}function Wt(n,e,t,r,o=Date.now){let i=wr(e,t,o),s=yr(r),a=kr(s),d=ze(n,i,a,o);return qe(n,"workflow",d,s,o),d}var br=4e3,vr=8,Ae=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new ae({log:t=>this.log(t)}),this.signals=e.signals??new j,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode,rootId:e.rootId})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let r of t){if(r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="signalWait")continue;let o={name:r.pausedAt.signalName,scope:r.pausedAt.scope,workflowId:r.workflowId,match:r.pausedAt.match??{}};if(!V(o,e))continue;let i=this.store.list().find(s=>s.id===r.workflowId);i&&(await this.commit(r.id,()=>{let s=this.runs.get(r.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!V({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=N(i,s.pausedAt.nodeId),d=a?i.edges.filter(u=>u.from===a.id).map(u=>u.to):[],c={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:c.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:c,idempotencyKey:T(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:c}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`,rootId:s.eventRootId})}),this.walk(i,r.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(r=>r.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let r=this.runs.get(e.runId);if(!r||r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="timerWait"||r.pausedAt.nodeId!==e.nodeId)return;let o=N(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:r.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(r.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...r.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${r.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:r.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`,rootId:r.eventRootId})}),this.walk(t,e.runId,`timer:${e.id}`).catch(r=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${r.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let r=String(t.channel??""),o=String(t.chatId??"");if(!r||!o)return;let i=this.channels[r];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let c=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};c();let u=setInterval(c,br);this.ackTypingTimers.set(e,u)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let r=this.store.list(),o=[];for(let i of r){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let c=i.mesh.peers;if(c&&c.length>0&&!c.includes(t.peer))continue}let s=i.nodes.find(c=>c.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&Z(e.source,d.chat)!==Z(e.source,e.chat))continue;if(d.labels?.length){let c=new Set(e.labels??[]);if(!d.labels.some(p=>c.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,r,o){let i=await this.dispatchOneLegacy(e,t,r,o);if(Be("workflow")!=="off")try{Wt(He(),{workflowId:e.id,eventId:r.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:r,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,r,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:r,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!Sr(a.pausedAt.resumeMatch,o,r))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=N(e,a.pausedAt.nodeId),c=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],u={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:r.payload},idempotencyKey:T(a.id,a.pausedAt.nodeId,`resume:${r.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:r.payload}},f=a.pausedAt.checkpointName,g=this.runs.recordExecution({runId:a.id,entry:u,nextPending:c,status:"running",pausedAt:null,context:p});g&&(a=g),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${f}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${r.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${r.id}`),{claimed:!1,run:null});else{let d=J(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:r.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode,rootId:a.eventRootId}),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}return this.walk(e,a.id,r.id),{claimed:!0,run:a}}async walk(e,t,r){let o=this.runs.get(t)?.eventRootId,i=()=>this.walkInner(e,t,r);try{await(o?Ke({rootId:o},i):i())}finally{this.stopChannelAck(t)}}async walkInner(e,t,r){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,vr);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,r)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,r,o){let i=T(t,r,o),s=await this.commit(t,()=>{let m=this.runs.get(t);if(!m)return{kind:"done"};if(m.status!=="running")return{kind:"done"};let y=N(e,r);if(!y)return this.log(`[workflow:${e.id}] missing node "${r}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:m.pending.filter(R=>R!==r),status:"failed"}),{kind:"done"};let w=ve(y.type);return w?m.history.some(R=>R.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:m.pending.filter(R=>R!==r)}),{kind:"done"}):{kind:"go",run:m,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:m.pending.filter(R=>R!==r),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:c}=s,u=e.edges.filter(m=>m.to===r).map(m=>m.from),p;if(d.type!=="agent"){let m=ne();if(m)try{p=Je(m,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${r}`,workflowRunId:t,workflowId:e.id,workflowNodeId:r,messagePreview:`${d.type} ${r}`})}catch{}}let f=d.retry??{maxAttempts:1,backoffMs:1e3},g={error:"retry-loop did not run"},h=0;for(;h<f.maxAttempts;){h++;try{g=await c({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(m){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${m.message}`),g={error:m.message}}if(!g.error||g.paused)break;if(h<f.maxAttempts){let m=f.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${r}" failed (attempt ${h}/${f.maxAttempts}): ${g.error.slice(0,120)} \u2014 retrying in ${m}ms`),await new Promise(y=>setTimeout(y,m))}}if(p){let m=ne();if(m)try{Ye(m,p,{status:g.error?"error":"ok",error:g.error??null})}catch{}}await this.commit(t,async()=>{let m=this.runs.get(t);if(!m)return;let y=new Date().toISOString(),w=m.pending.filter(k=>k!==r);if(g.error){let k=m.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"failed",idempotencyKey:i,note:g.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"failed",status:k??m.status,note:g.error.slice(0,200)});return}if(g.paused&&g.pausedAt){let k=g.pausedAt,P=null;if(g.spawnChild&&k.kind==="subProcess"){if(P=await this.spawnChild({parent:m,parentNodeId:r,childWorkflowId:g.spawnChild.workflowId,input:g.spawnChild.input}),!P){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${g.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:P.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"paused",status:"paused",note:k.kind}),P&&this.kickChildWalk(P),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(Pe){this.log(`[workflow:${e.id}] timer schedule failed: ${Pe.message}`)}return}let R=g.output??{},Kt={...m.context,[r]:R},{nextPending:Bt}=ye({workflow:e,fromNodeId:r,selectedPort:g.port}),te=[],M={...m.joinCounters??{}};for(let k of Bt){let P=N(e,k);if(!(P?.type==="gateway.parallel"&&String(P.config?.mode??"fanOut")==="join")){te.push(k);continue}let _=M[k]??[];_.includes(r)||_.push(r),M[k]=_;let Jt=e.edges.filter(Yt=>Yt.to===k).length;_.length>=Jt&&(te.push(k),delete M[k])}let zt=[...w,...te],C=d.type==="end",qt=m.status==="running"?C?String(d.config.status??"completed"):"running":void 0,O=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:u,status:"ok",output:R,idempotencyKey:i},nextPending:C?[]:zt,status:qt,context:Kt,joinCounters:M});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:C?"completed":"ok",status:O?.status??m.status}),g.emitSignal&&this.emitSignal({name:g.emitSignal.name,scope:g.emitSignal.scope,workflowId:e.id,payload:g.emitSignal.payload}),C&&O&&O.parentRunId&&O.parentNodeId&&this.resumeParent({parentRunId:O.parentRunId,parentNodeId:O.parentNodeId,childRun:O}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let r=J(t);if(!r)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[r.triggerId]={...o[r.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(r=>r.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(r=>this.log(`[workflow:${t.id}] child walk failed: ${r.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let r=this.store.list().find(o=>o.id===t.workflowId);r&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=N(r,e.parentNodeId),s=i?r.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:Ir(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:T(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${r.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:r.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`,rootId:o.eventRootId})}),this.walk(r,e.parentRunId,`child:${e.childRun.id}`))}};function Ir(n){for(let e=n.history.length-1;e>=0;e--){let t=n.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function Sr(n,e,t){let r=i=>{let s=n[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?Z(e.source,String(s))===Z(e.source,e.chat):e[i]===s};if(!r("source")||!r("project")||!r("repo")||!r("chat"))return!1;let o=n.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function Z(n,e){return e==null?"":n==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Ar(n){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let r=Rr(t.channel);if(!r)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await n.dispatch({trigger:{source:r,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:$r(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(u=>u.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,r=e.iid,o=e.issueEvent;if(!t||r===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${r}`};return await n.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:r,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${r}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,r=e.iid,o=e.mrEvent;if(!t||r===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(c=>typeof c=="string"?c:c?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${r}`};return await n.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${r}`,iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,r=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!r||!o||!i)return{};let c=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await n.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:c,event:{id:`gitlab-note:${t}:${o}:${i}:${r}`,payload:{note:{id:r,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:r,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,r=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await n.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${r}:${o}`,payload:{pipeline:{id:r,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function Rr(n){switch(n){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function $r(n){let e=n.group?.id??n.sender.id;return{channel:n.channel,chatId:e,accountId:n.accountId,text:n.text,fromJid:n.sender.id,sender:{id:n.sender.id,name:n.sender.name,username:n.sender.username},contact:n.channelMeta?.facts?{facts:n.channelMeta.facts}:void 0,group:n.group?{id:n.group.id,name:n.group.name}:void 0,channelMeta:n.channelMeta,replyTo:n.replyTo,replyToText:n.replyToText,media:n.media,event:{id:n.id,timestamp:n.timestamp?.toISOString?.()??new Date().toISOString()}}}var Q=n=>n.trim().toLowerCase().replace(/^@/,"");function xr(n){let e=typeof n.author=="string"?n.author:typeof n.authorUsername=="string"?n.authorUsername:void 0;if(e)return Q(e);let r=n.payload?.sender?.login;return typeof r=="string"&&r?Q(r):void 0}function Pr(n,e){let t=typeof e.project=="string"?e.project:"";if(n==="on:gitlab-issue"||n==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${n==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(n==="on:gitlab-note"){let r=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!r||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${r}`}if(n==="on:github-issue"||n==="on:github-pr"){let r=e.payload??{},o=typeof e.repo=="string"?e.repo:r.repository?.full_name,i=e.number??r.issue?.number??r.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function Tr(n){let e=new Set;for(let t of n.nodes){let r=t.type==="agent"?t.config.agentId:void 0;typeof r=="string"&&r&&e.add(r)}return[...e]}var X=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,r,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<r);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function Re(n,e,t){let r=n.logged??(n.logged=new Set);r.has(e)||(r.add(e),n.log(t))}function Et(n,e,t,r,o){let i=xr(t);if(i&&Array.isArray(r?.ignoreAuthors)&&r.ignoreAuthors.length>0&&r.ignoreAuthors.map(Q).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(r?.skipSelfAuthored===!0){let a=Tr(n),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let c=new Set(a.flatMap(u=>(o.forgeUsernames?.(u)??[]).map(Q)));if(c.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?Re(o,`noagents:${n.id}`,`[workflows] ${n.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):c.size===0&&!("authorAgent"in t)&&Re(o,`noident:${n.id}:${e}`,`[workflows] ${n.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=r?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=Pr(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,c=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${n.id}|${a}`,s.count,d*6e4,c))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else Re(o,`notarget:${n.id}:${e}`,`[workflows] ${n.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function Nr(n){let e=n.store.list(),t={fireWindow:new X,log:n.log,forgeUsernames:n.forgeUsernames,logged:new Set},r=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){n.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){n.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}Wr({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},n.dispatcher,n.log),r++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){n.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}n.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let c=typeof d.project=="string"?d.project:void 0;if(i.project&&c&&i.project!==c)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(m=>m.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,m=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!m.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let u=Et(i,a.event,d,a.filter,t);if(u.skip){if(n.log(`[workflows] ${i.id} skipping ${a.event} (${u.reason}): ${u.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=Or(i.id,a.event,d);if(await n.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let f=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(f)?f:[],i.id]}}}catch(c){return n.log(`[workflows] ${i.id} hook dispatch failed: ${c.message}`),{}}},60),o++}}}return{cronTimers:r,hookSubscribers:o}}function Or(n,e,t){let r=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&r&&o)return`${n}:${e}:${r}#${o}`;if(e==="on:gitlab-mr"&&r&&o)return`${n}:${e}:${r}!${o}`;if(e==="on:gitlab-pipeline"&&r){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${n}:${e}:${r}@pipeline:${i}`}return`${n}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Wr(n,e,t){let r=()=>{let o;try{o=Ge(n.spec,new Date,n.timezone)}catch(s){t(`[workflows] ${n.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${n.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:n.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${n.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:n.spec,workflowId:n.workflowId}}})}catch(a){t(`[workflows] ${n.workflowId} cron dispatch failed: ${a.message}`)}finally{r()}})()},i)};r()}function Dt(n){return n.nodes.find(r=>r.type.startsWith("trigger."))?.config?.inputSchema??null}function Ft(n,e){if(!n||!e?.properties)return{};let t=n.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,r,o,i]=t,s={};if(e.properties.project&&(s.project=r),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function jt(n,e){if(!n?.properties)return e;let t={...e};for(let[r,o]of Object.entries(n.properties))t[r]===void 0&&o&&"default"in o&&(t[r]=o.default);return t}function Mt(n,e){return!n?.required||!Array.isArray(n.required)?[]:n.required.filter(t=>{let r=e[t];return r===void 0||r===""||r===null})}function Dr(n,e){let t=Dt(n);if(!t?.properties){let d={};for(let[c,u]of Object.entries(e))u!==void 0&&(d[c]=u);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let r={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(r[d]=e[d]);let o=Ft(e.chatId,t),i={...r,...o},s={...i};i=jt(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:Mt(t,i),filledFrom:{passthrough:Object.keys(r),chatId:Object.keys(o),defaults:a}}}import{extname as Fr}from"path";var Ct=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,_t=/<agentx-artifact>[\s\S]*$/i;function Ci(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let i=o.replace(Ct,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";r.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?i.replace(_t,""):i).trim(),artifacts:r}}function _i(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Ct,(i,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});r=(e?o.replace(_t,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,i,s)=>i===void 0||s===void 0?o:`[${i||s}](${s})`)}var jr={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Li={bytes:20*1024*1024,perMessage:20,pathChars:512};function Hi(n){return jr[Fr(n).toLowerCase()]??null}var Mr=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
20
20
|
`);function Ui(n,e,t){return n==="app"&&e&&t!==!1?Mr:void 0}import{lstatSync as xe,mkdirSync as Cr,readdirSync as _r,realpathSync as $e,unlinkSync as Lr}from"fs";import{join as ee,resolve as Lt}from"path";var Ht=".agentx/outbox",Hr=7*24*60*60*1e3;function Ur(n,e){try{let t=$e(Lt(e,n)),r=ee(t,Ht);return $e(r)===r&&xe(r).isDirectory()?r:null}catch{return null}}function qi(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=$e(Lt(t,n));xe(ee(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||Cr(ee(o,Ht),{recursive:!0})}catch{return 0}let r=Ur(n,t);return r?Ut(r,(e.now??Date.now())-(e.maxAgeMs??Hr)):0}function Ut(n,e){let t=0;for(let r of _r(n)){let o=ee(n,r);try{let i=xe(o);i.isDirectory()?t+=Ut(o,e):Math.max(i.mtimeMs,i.ctimeMs)<e&&(Lr(o),t++)}catch{}}return t}export{Qe as a,st as b,at as c,oo as d,pn as e,io as f,$ as g,ce as h,v as i,H as j,Rn as k,fe as l,me as m,we as n,Ae as o,Ar as p,Nr as q,Kn as r,Dr as s,Ci as t,_i as u,Li as v,Hi as w,Ui as x,Ht as y,qi as z};
|
|
21
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
//# sourceMappingURL=chunk-2HMI5PJG.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-NWL5KPBJ.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{v as C,w as I}from"./chunk-KHEI4VNM.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -46,4 +46,4 @@ ${o}
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
48
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-55RM7V4N.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as we}from"./chunk-7XB2CVC3.js";import{t as bt,u as wt}from"./chunk-
|
|
1
|
+
import{a as we}from"./chunk-7XB2CVC3.js";import{t as bt,u as wt}from"./chunk-Q2FFZX7Y.js";import{d as ht,e as yt}from"./chunk-AQASR6KR.js";import{b as he,t as ut,v as J,w as ye,y as be}from"./chunk-2HMI5PJG.js";import{g as dt,h as gt,i as ft,k as pt,l as mt}from"./chunk-S5JGQKON.js";import{q as ct}from"./chunk-PUU2ESI2.js";import{A as lt,D as nr}from"./chunk-CXZ4YDHJ.js";import{existsSync as rr,readdirSync as sr,readFileSync as ir,statSync as or}from"fs";import{resolve as ar}from"path";function kt(t,e,n=Date.now(),s=7){let r=s*864e5,i=new Map;for(let o of e){let a=i.get(o.workflowId);a?a.push(o):i.set(o.workflowId,[o])}return t.map(o=>{let a=i.get(o.id)??[],l=a.filter(p=>n-p.at<=r),c=a.filter(p=>n-p.at>r&&n-p.at<=r*2),u=l.filter(p=>p.status==="failed").length,d=a.filter(p=>p.status==="paused").length,g=a.length?Math.max(...a.map(p=>p.at)):null,f=a.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:g,recent:l.length,prior:c.length,failed:u,paused:d}}).sort((o,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[o.state]-l[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var Y=new Map;function ko(t,e=1e3){if(!rr(t))return[];let n=sr(t).filter(i=>i.endsWith(".jsonl")).map(i=>{let o=ar(t,i);return{path:o,mtime:or(o).mtimeMs}}).sort((i,o)=>o.mtime-i.mtime).slice(0,e),s=new Set(n.map(i=>i.path));for(let i of Y.keys())s.has(i)||Y.delete(i);let r=[];for(let{path:i,mtime:o}of n){let a=Y.get(i);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let l=lr(i,o);Y.set(i,{mtime:o,summary:l}),l&&r.push(l)}return r}function lr(t,e){try{let n=ir(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let s=JSON.parse(n[0]),r=s.run?.workflowId;if(!r)return null;let i=s.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),l=a.status??a.run?.status;if(l){i=l;break}}return{workflowId:r,status:i,at:e}}catch{return null}}var cr={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},ur=(t,e,n)=>{try{return ct(t,e,n)}catch{return null}},St=864e5;function $o(t){let e=t.now??Date.now(),n={...cr,...t.thresholds},s=t.nextFire??ur,r=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",u=l.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=l[0],g={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ke(a.nextRun)??ke(s(a.schedule,new Date(e),c)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:hr(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:l.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:xt(u),sampledRuns:l.length,flags:[],attention:null};g.flags=vt(g,u,a.schedule,c,null,e,n,s),r.push($t(g))}let i=new Map(kt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let l=o.get(a.workflowId);l?l.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(A=>A.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=a.state||"active",d=u==="active",g=(o.get(a.id)??[]).slice().sort((A,me)=>me.at-A.at),f=g.map(A=>({at:A.at,status:fr(A.status)})),p=f[0],h=l.type==="trigger.cron",y=typeof c.spec=="string"?c.spec:"",C=typeof c.timezone=="string"?c.timezone:"UTC",O={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,k.text),trigger:h?{schedule:$(y,k.text),timezone:C}:{event:$(typeof c.event=="string"?c.event:"",k.text),filters:mr(c.filter,a)},agent:pr(a),enabled:d,state:u,nextRunAt:h&&d&&y?ke(s(y,new Date(e),C)):null,lastRun:p?{at:new Date(p.at).toISOString(),status:p.status}:null,lastSuccessAt:(()=>{let A=f.find(me=>me.status==="success");return A?new Date(A.at).toISOString():null})(),consecutiveFailures:xt(f),sampledRuns:g.length,flags:[],attention:null},q=Date.parse(a.updated||a.created||"");O.flags=h?vt(O,f,y,C,Number.isFinite(q)?q:null,e,n,s):dr(O,i.get(a.id)?.state==="dormant",Number.isFinite(q)?q:null,e,n),r.push($t(O))}return r.sort(gr).slice(0,k.routines)}function xt(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 vt(t,e,n,s,r,i,o,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let g=_t(c,r,i,o);return g&&l.push(g),l}if(t.consecutiveFailures>=o.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),d=null;for(let g=0;g<o.missedFires&&(d=a(n,u,s),!!d);g++)u=d;return d&&i>d.getTime()+o.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${o.missedFires} scheduled fires missed`}),l}function dr(t,e,n,s,r){let i=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=_t(o,n,s,r);return a&&i.push(a),i}return t.consecutiveFailures>=r.failStreak&&i.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?i.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&i.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),i}function _t(t,e,n,s){let r=Math.max(t??0,e??0);return r&&n-r<s.disabledDays*St?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/St)} days`:"Disabled and never ran"}}function $t(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 It={critical:0,warning:1,info:2};function gr(t,e){let n=t.attention?It[t.attention]:3,s=e.attention?It[e.attention]:3;return n-s||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function fr(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 pr(t){if(t.ownerAgent)return $(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),k.text):null}function mr(t,e){let n=[],s=e?.project;if(s&&n.push($(`project=${s}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,i]of Object.entries(t)){let o=Array.isArray(i)?i.map(String):i==null?[]:[String(i)];o.length&&n.push($(`${r}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function ke(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function hr(t,e){return t===void 0?void 0:$(t,e)}import{createHash as yr,randomBytes as At}from"crypto";import{existsSync as br,mkdirSync as wr,readFileSync as kr,writeFileSync as Sr}from"fs";import{resolve as xr,dirname as vr}from"path";var Se="agx_live_",$r=".agentx/tokens.json",Rt=class{file;constructor(e=process.cwd(),n=$r){this.file=xr(e,n)}load(){if(!br(this.file))return[];try{return JSON.parse(kr(this.file,"utf-8"))}catch{return[]}}save(e){wr(vr(this.file),{recursive:!0}),Sr(this.file,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8")}create(e){if(!e.name?.trim())throw new Error("Token name is required.");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("At least one scope is required.");for(let o of e.scopes)if(!Ir(o))throw new Error(`Invalid scope: ${o}`);let n=At(32).toString("hex"),s=Se+n,r={id:"tok_"+At(4).toString("hex"),name:e.name.trim(),prefix:Se+n.slice(0,4),hash:Ct(s),scopes:[...e.scopes],createdAt:new Date().toISOString(),expiresAt:e.expiresInDays?new Date(Date.now()+e.expiresInDays*86400*1e3).toISOString():void 0},i=this.load();return i.push(r),this.save(i),{token:s,record:r}}list(){return this.load()}revoke(e){let n=this.load(),s=n.find(r=>r.id===e);return s?(s.revokedAt=new Date().toISOString(),this.save(n),s):null}isActive(e){let n=this.load().find(s=>s.id===e);return!!n&&!n.revokedAt&&!(n.expiresAt&&Date.parse(n.expiresAt)<Date.now())}verify(e){if(!e||!e.startsWith(Se))return null;let n=Ct(e),s=this.load(),r=s.find(a=>a.hash===n);if(!r||r.revokedAt||r.expiresAt&&Date.parse(r.expiresAt)<Date.now())return null;let i=Date.now(),o=r.lastUsedAt?Date.parse(r.lastUsedAt):0;if(i-o>6e4){r.lastUsedAt=new Date(i).toISOString();try{this.save(s)}catch{}}return r}};function Co(t,e){return!!(t.scopes.includes(e)||e.startsWith("agent:")&&t.scopes.includes("agent:*")||e==="dashboard:read"&&t.scopes.includes("dashboard:write"))}function Ir(t){return t==="dashboard:read"||t==="dashboard:write"||t==="agent:*"||/^agent:[a-z0-9][a-z0-9_-]*$/.test(t)||t==="mesh:peer"||t==="app"}function Ct(t){return"sha256:"+yr("sha256").update(t).digest("hex")}function Do(t){let e=t.headers.authorization,n=Array.isArray(e)?e[0]:e;if(n&&n.toLowerCase().startsWith("bearer "))return n.slice(7).trim();if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{}return null}import{existsSync as ve,readdirSync as Zr,readFileSync as Qr}from"fs";import{resolve as j}from"path";import{randomBytes as Et}from"crypto";import{existsSync as Ar,mkdirSync as Rr,readdirSync as Cr,readFileSync as Dr,renameSync as Lt,unlinkSync as Tr,writeFileSync as Er}from"fs";import{resolve as Ot}from"path";function Dt(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var _r=t=>t.trim().split(`
|
|
4
4
|
`).pop()?.slice(0,300)||"no output";async function Tt(t,e,n,s=we){let r=await s(t.bin,[...Dt(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return r.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${_r(r.stderr||r.stdout)}`}}async function Lo(t,e,n,s,r=we){return(await r(t.bin,[...Dt(t),"--read-only","media","download","--chat",e,"--id",n,"--output",s],{timeoutMs:12e4})).code===0}var Lr=2e3,Or=t=>Tt(t.wacli,t.to,t.text);function xe(t){return Ot(t,".agentx","whatsapp-triage","drafts")}var Pr=t=>/^[a-z0-9-]{8,64}$/.test(t),Z=(t,e)=>Ot(xe(t),`${e}.json`);function Pt(t,e){Rr(xe(t),{recursive:!0});let n=Z(t,e.id),s=`${n}.${process.pid}.tmp`;Er(s,JSON.stringify(e,null,2)+`
|
|
@@ -153,4 +153,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
153
153
|
claude-code ${at(t)} --arg value
|
|
154
154
|
\`\`\`
|
|
155
155
|
`}nr();var Zn={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Qn(t){return{...Zn,...t??{},regions:{...t?.regions??{}},buffer:{...Zn.buffer,...t?.buffer??{}}}}function fc(t){try{return Qn(lt(t).screen)}catch{return Qn(void 0)}}var yo=/^[a-z][\w-]*$/,er=["window","screen","menubar","notifications"];function X(t,e,n,s){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${s}`);return r}var pe=(t,e)=>X(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function tr(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 pc(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=pe(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=pe(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=pe(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=X(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=X(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[i,o]of Object.entries(e.regions)){if(!yo.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);o===null?delete r[i]:r[i]=tr(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,i={...n.buffer??{}};"enabled"in r&&(i.enabled=!!r.enabled),"seconds"in r&&(i.seconds=X(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(i.fps=X(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(i.maxPixels=pe(r.maxPixels,"buffer.maxPixels")),"region"in r&&(i.region=String(r.region).trim()),n.buffer=i}let s=n.buffer?.region;if(s!==void 0&&!er.includes(s)&&!n.regions?.[s])try{tr(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...er,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{kt as a,ko as b,Xe as c,hi as d,yi as e,ol as f,al as g,ll as h,Dn as i,ul as j,gl as k,D as l,Tn as m,k as n,$o as o,Rt as p,Co as q,Ct as r,Do as s,Mt as t,Ft as u,U as v,Bo as w,Ho as x,zo as y,Ko as z,Go as A,Lo as B,Or as C,No as D,Vt as E,te as F,Zo as G,ca as H,ua as I,bl as J,Ei as K,wl as L,ga as M,fa as N,pa as O,ma as P,ha as Q,ya as R,wa as S,ka as T,Ca as U,De as V,Da as W,Ta as X,B as Y,H as Z,Mi as _,Rl as $,Cl as aa,Dl as ba,Tl as ca,qe as da,El as ea,Le as fa,Oe as ga,ce as ha,js as ia,Ms as ja,Va as ka,je as la,Ve as ma,Ns as na,Fs as oa,hn as pa,kn as qa,Ma as ra,Bs as sa,Na as ta,Ys as ua,ei as va,Me as wa,ni as xa,Sn as ya,T as za,Fn as Aa,Un as Ba,Wn as Ca,Ml as Da,Gi as Ea,Hn as Fa,zn as Ga,Kn as Ha,Jl as Ia,Yl as Ja,uo as Ka,Zl as La,Xn as Ma,ue as Na,Ya as Oa,An as Pa,Ne as Qa,Ke as Ra,sl as Sa,nc as Ta,rc as Ua,sc as Va,ic as Wa,oc as Xa,ac as Ya,lc as Za,cc as _a,uc as $a,Zn as ab,Qn as bb,fc as cb,er as db,pc as eb};
|
|
156
|
-
//# sourceMappingURL=chunk-
|
|
156
|
+
//# sourceMappingURL=chunk-663BLK67.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{v as l,w}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{v as l,w}from"./chunk-KHEI4VNM.js";import{a as i,f as p}from"./chunk-72SZI2UW.js";w();p();var d="task-tier";function u(e){return{task:m(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:i("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function m(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2,T=60*60*1e3;function F(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function _(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(e.channel==="voice"||e.channel==="desktop"||e.channel==="opencode")return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??T;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let a=e.threshold??h;return o>=a?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${a}) \u2192 ${e.cheapModel}`}}export{F as a,_ as b};
|
|
2
|
+
//# sourceMappingURL=chunk-6CCJMHBA.js.map
|