agentix-cli 0.113.0 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/apps/mac-helper/Resources/AppIcon.png +0 -0
  2. package/apps/mac-voice/Resources/AppIcon.png +0 -0
  3. package/apps/mac-voice/Resources/Info.plist +1 -0
  4. package/apps/mac-voice/build.sh +10 -0
  5. package/dist/{App-5ZI475WY.js → App-Q4UAYL2V.js} +2 -2
  6. package/dist/{ChatApp-PLR7J5D3.js → ChatApp-6KGP57OP.js} +2 -2
  7. package/dist/{agent-GRX75ANW.js → agent-5F4EKGQN.js} +2 -2
  8. package/dist/{board-dashboard-EKJHQKPH.js → board-dashboard-GGW5ZZLT.js} +553 -327
  9. package/dist/board-dashboard-GGW5ZZLT.js.map +1 -0
  10. package/dist/{chunk-QWI3FM5R.js → chunk-4COYYJJY.js} +2 -2
  11. package/dist/{chunk-QAIYUMHW.js → chunk-4VDA4UM7.js} +2 -2
  12. package/dist/{chunk-OZDSQVHU.js → chunk-6WNQY6K2.js} +2 -2
  13. package/dist/{chunk-74CQWVHE.js → chunk-A35RTVMM.js} +2 -2
  14. package/dist/{chunk-DG5I6PPM.js → chunk-BGG3ZSMW.js} +4 -2
  15. package/dist/chunk-BGG3ZSMW.js.map +1 -0
  16. package/dist/{chunk-X7E27RYS.js → chunk-C4S5XQKD.js} +2 -2
  17. package/dist/{chunk-A6B5JRUG.js → chunk-CYKPDILL.js} +2 -2
  18. package/dist/{chunk-XG2XVGSL.js → chunk-FDCTFT2Q.js} +2 -2
  19. package/dist/{chunk-MEXXGNNN.js → chunk-HG6QA6EU.js} +2 -2
  20. package/dist/{chunk-6FJ44HYY.js → chunk-HPY54DU6.js} +2 -2
  21. package/dist/{chunk-JBE4H7PL.js → chunk-ILGLEA3I.js} +2 -2
  22. package/dist/{chunk-THRWE4Y3.js → chunk-J3GXZQXY.js} +2 -2
  23. package/dist/{chunk-V3C2BOYR.js → chunk-LP227A6L.js} +2 -2
  24. package/dist/{chunk-RXQ2XCKP.js → chunk-O2RVUM2B.js} +2 -2
  25. package/dist/{chunk-B37WAFT5.js → chunk-QQIWLN3H.js} +160 -160
  26. package/dist/chunk-QQIWLN3H.js.map +1 -0
  27. package/dist/{chunk-N7HKIMMR.js → chunk-SCJ5ZXEN.js} +2 -2
  28. package/dist/{chunk-4QCYSKPD.js → chunk-VGI4EZTP.js} +2 -2
  29. package/dist/{chunk-DVJW3IWI.js → chunk-VQM77L54.js} +2 -2
  30. package/dist/{chunk-EEOQ5C5N.js → chunk-VTWSW4KB.js} +2 -2
  31. package/dist/{chunk-37EDS7SZ.js → chunk-XTO4GRGN.js} +5 -5
  32. package/dist/{chunk-R43TE2XX.js → chunk-XX7NXI3Y.js} +2 -2
  33. package/dist/{chunk-TXX5W3SH.js → chunk-Y5HBYSJW.js} +2 -2
  34. package/dist/{chunk-TXX5W3SH.js.map → chunk-Y5HBYSJW.js.map} +1 -1
  35. package/dist/{chunk-22LO3GBP.js → chunk-YLKCFW2R.js} +2 -2
  36. package/dist/{chunk-QF377BDS.js → chunk-YU5NDKPA.js} +2 -2
  37. package/dist/cli.js +1 -1
  38. package/dist/{client-DBQ5QNJJ.js → client-QTXWO46T.js} +2 -2
  39. package/dist/{config-4T62LT27.js → config-4XGZYYQP.js} +2 -2
  40. package/dist/config-mutator-QLSA6JOY.js +2 -0
  41. package/dist/{doctor-M32NIOZH.js → doctor-DO262COW.js} +2 -2
  42. package/dist/index.d.ts +49 -0
  43. package/dist/index.js +1 -1
  44. package/dist/processes-5MP32QZT.js +2 -0
  45. package/dist/{program-7MG42JKO.js → program-IEMICVO3.js} +14 -14
  46. package/dist/{promote-DAEKJVWN.js → promote-S7SKOKX2.js} +2 -2
  47. package/dist/{query-MCJYD66I.js → query-GOBQ3GL5.js} +2 -2
  48. package/dist/{registry-AYPPHZ3Z.js → registry-HUJEORRW.js} +2 -2
  49. package/dist/{request-planner-7NKKLY7C.js → request-planner-RYWFGBGK.js} +2 -2
  50. package/dist/{review-candidates-QG2U5YID.js → review-candidates-TXX532LY.js} +2 -2
  51. package/dist/{routing-HBNYDAGE.js → routing-IT4YS6X3.js} +2 -2
  52. package/dist/schedule-tool-FJKH2ERY.js +2 -0
  53. package/dist/scheduler-ALPDUE4H.js +2 -0
  54. package/dist/{seat-PQ7AMPMT.js → seat-LK45MTVI.js} +2 -2
  55. package/dist/{select-J6TO7RED.js → select-4LAHUZ74.js} +2 -2
  56. package/dist/{set-enabled-WXRUHFWW.js → set-enabled-F2K56HQZ.js} +2 -2
  57. package/dist/{tool-I3OGQKAD.js → tool-J4VHHZWN.js} +2 -2
  58. package/dist/{tool-KN2QEPDO.js → tool-W3ODKQM2.js} +2 -2
  59. package/dist/wiki-FZHSX4K3.js +2 -0
  60. package/package.json +1 -1
  61. package/dist/board-dashboard-EKJHQKPH.js.map +0 -1
  62. package/dist/chunk-B37WAFT5.js.map +0 -1
  63. package/dist/chunk-DG5I6PPM.js.map +0 -1
  64. package/dist/config-mutator-ARUEJ6V5.js +0 -2
  65. package/dist/processes-W5VHBP7T.js +0 -2
  66. package/dist/schedule-tool-6S35TPJJ.js +0 -2
  67. package/dist/scheduler-KZ6VVZZA.js +0 -2
  68. package/dist/wiki-2IKLQ6PO.js +0 -2
  69. /package/dist/{App-5ZI475WY.js.map → App-Q4UAYL2V.js.map} +0 -0
  70. /package/dist/{ChatApp-PLR7J5D3.js.map → ChatApp-6KGP57OP.js.map} +0 -0
  71. /package/dist/{agent-GRX75ANW.js.map → agent-5F4EKGQN.js.map} +0 -0
  72. /package/dist/{chunk-QWI3FM5R.js.map → chunk-4COYYJJY.js.map} +0 -0
  73. /package/dist/{chunk-QAIYUMHW.js.map → chunk-4VDA4UM7.js.map} +0 -0
  74. /package/dist/{chunk-OZDSQVHU.js.map → chunk-6WNQY6K2.js.map} +0 -0
  75. /package/dist/{chunk-74CQWVHE.js.map → chunk-A35RTVMM.js.map} +0 -0
  76. /package/dist/{chunk-X7E27RYS.js.map → chunk-C4S5XQKD.js.map} +0 -0
  77. /package/dist/{chunk-A6B5JRUG.js.map → chunk-CYKPDILL.js.map} +0 -0
  78. /package/dist/{chunk-XG2XVGSL.js.map → chunk-FDCTFT2Q.js.map} +0 -0
  79. /package/dist/{chunk-MEXXGNNN.js.map → chunk-HG6QA6EU.js.map} +0 -0
  80. /package/dist/{chunk-6FJ44HYY.js.map → chunk-HPY54DU6.js.map} +0 -0
  81. /package/dist/{chunk-JBE4H7PL.js.map → chunk-ILGLEA3I.js.map} +0 -0
  82. /package/dist/{chunk-THRWE4Y3.js.map → chunk-J3GXZQXY.js.map} +0 -0
  83. /package/dist/{chunk-V3C2BOYR.js.map → chunk-LP227A6L.js.map} +0 -0
  84. /package/dist/{chunk-RXQ2XCKP.js.map → chunk-O2RVUM2B.js.map} +0 -0
  85. /package/dist/{chunk-N7HKIMMR.js.map → chunk-SCJ5ZXEN.js.map} +0 -0
  86. /package/dist/{chunk-4QCYSKPD.js.map → chunk-VGI4EZTP.js.map} +0 -0
  87. /package/dist/{chunk-DVJW3IWI.js.map → chunk-VQM77L54.js.map} +0 -0
  88. /package/dist/{chunk-EEOQ5C5N.js.map → chunk-VTWSW4KB.js.map} +0 -0
  89. /package/dist/{chunk-37EDS7SZ.js.map → chunk-XTO4GRGN.js.map} +0 -0
  90. /package/dist/{chunk-R43TE2XX.js.map → chunk-XX7NXI3Y.js.map} +0 -0
  91. /package/dist/{chunk-22LO3GBP.js.map → chunk-YLKCFW2R.js.map} +0 -0
  92. /package/dist/{chunk-QF377BDS.js.map → chunk-YU5NDKPA.js.map} +0 -0
  93. /package/dist/{client-DBQ5QNJJ.js.map → client-QTXWO46T.js.map} +0 -0
  94. /package/dist/{config-4T62LT27.js.map → config-4XGZYYQP.js.map} +0 -0
  95. /package/dist/{config-mutator-ARUEJ6V5.js.map → config-mutator-QLSA6JOY.js.map} +0 -0
  96. /package/dist/{doctor-M32NIOZH.js.map → doctor-DO262COW.js.map} +0 -0
  97. /package/dist/{processes-W5VHBP7T.js.map → processes-5MP32QZT.js.map} +0 -0
  98. /package/dist/{program-7MG42JKO.js.map → program-IEMICVO3.js.map} +0 -0
  99. /package/dist/{promote-DAEKJVWN.js.map → promote-S7SKOKX2.js.map} +0 -0
  100. /package/dist/{query-MCJYD66I.js.map → query-GOBQ3GL5.js.map} +0 -0
  101. /package/dist/{registry-AYPPHZ3Z.js.map → registry-HUJEORRW.js.map} +0 -0
  102. /package/dist/{request-planner-7NKKLY7C.js.map → request-planner-RYWFGBGK.js.map} +0 -0
  103. /package/dist/{review-candidates-QG2U5YID.js.map → review-candidates-TXX532LY.js.map} +0 -0
  104. /package/dist/{routing-HBNYDAGE.js.map → routing-IT4YS6X3.js.map} +0 -0
  105. /package/dist/{schedule-tool-6S35TPJJ.js.map → schedule-tool-FJKH2ERY.js.map} +0 -0
  106. /package/dist/{scheduler-KZ6VVZZA.js.map → scheduler-ALPDUE4H.js.map} +0 -0
  107. /package/dist/{seat-PQ7AMPMT.js.map → seat-LK45MTVI.js.map} +0 -0
  108. /package/dist/{select-J6TO7RED.js.map → select-4LAHUZ74.js.map} +0 -0
  109. /package/dist/{set-enabled-WXRUHFWW.js.map → set-enabled-F2K56HQZ.js.map} +0 -0
  110. /package/dist/{tool-I3OGQKAD.js.map → tool-J4VHHZWN.js.map} +0 -0
  111. /package/dist/{tool-KN2QEPDO.js.map → tool-W3ODKQM2.js.map} +0 -0
  112. /package/dist/{wiki-2IKLQ6PO.js.map → wiki-FZHSX4K3.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-6W74CHNW.js";import{a as E}from"./chunk-R43TE2XX.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
1
+ import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{b as F}from"./chunk-6W74CHNW.js";import{a as E}from"./chunk-XX7NXI3Y.js";import{b as L}from"./chunk-CECHWYJ2.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c=""){return Z(r,s,t,o,i,c)}function Z(n,r,s,t,o,i=""){let c=r?`
2
2
  ## Worldview
3
3
 
4
4
  ${r}
@@ -240,4 +240,4 @@ ${g}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
240
240
  Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let u=[{role:"user",content:n}];s&&(u.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),u.push({role:"user",content:`Your previous response failed validation: ${s}
241
241
  Re-emit the FULL corrected JSON object.`}));let g=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:u}),signal:i.signal});if(!g.ok){let a=await g.text().catch(()=>"");throw new Error(`anthropic API ${g.status}: ${a.slice(0,500)}`)}let l=await g.json(),e=(Array.isArray(l.content)?l.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
242
242
  `).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...m)=>t(m.map(String).join(" "))),p=c.rebuildIndex(),u=z(r),g=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(g,p,u,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let l=p.articles.map(m=>({title:m.title,path:m.path,type:m.type})),d=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,l,d);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,l,d);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(m=>m.candidates),w=new Set(y.map(m=>m.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(m=>[m.stamp,m]));for(let m of f.articles){let A=c.readArticle(m.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${m.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(m.promotedFrom,T),S={id:Y(o,m.path),createdAt:v,status:"pending",article:m,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:m.path,title:m.title,type:m.type,stamps:m.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of m.promotedFrom)k.push({stamp:X,decision:"proposed",article:m.path,proposal:S.id,at:v})}for(let m of f.skipped)k.push({stamp:m.stamp,decision:"skipped",reason:m.reason,at:v}),i.skipped.push(m);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let u=s.now??Date.now(),g=new Date(u).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??g,lastUpdated:g,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let d=new Date(u).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:d}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:d};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
243
- //# sourceMappingURL=chunk-QWI3FM5R.js.map
243
+ //# sourceMappingURL=chunk-4COYYJJY.js.map
@@ -1,4 +1,4 @@
1
- import{c as e}from"./chunk-N7HKIMMR.js";function i(t={}){let r=`<div class="ax-proc__kpis" id="proc-kpis" hidden></div>
1
+ import{c as e}from"./chunk-SCJ5ZXEN.js";function i(t={}){let r=`<div class="ax-proc__kpis" id="proc-kpis" hidden></div>
2
2
  <div class="ax-proc__root">
3
3
  <aside class="ax-proc__list">
4
4
  <header>
@@ -253,4 +253,4 @@ import{c as e}from"./chunk-N7HKIMMR.js";function i(t={}){let r=`<div class="ax-p
253
253
  setInterval(refresh, 5000);
254
254
  })();
255
255
  `;export{i as a};
256
- //# sourceMappingURL=chunk-QAIYUMHW.js.map
256
+ //# sourceMappingURL=chunk-4VDA4UM7.js.map
@@ -1,4 +1,4 @@
1
- import{q as Xt}from"./chunk-S2GAEH2F.js";import{a as Re}from"./chunk-GTJIKXDB.js";import{a as re,b as w}from"./chunk-DG5I6PPM.js";import{t as Gt,u as Kt}from"./chunk-QWI3FM5R.js";import{d as zt,e as qt}from"./chunk-AQASR6KR.js";import{b as Jt,c as Ie,e as B,f as H,h as Yt}from"./chunk-JIT5GPTX.js";import{A as Ae,b as ve,v as Lt,x as ne,y as $e}from"./chunk-THRWE4Y3.js";import{a as Mt,b as Nt}from"./chunk-SHEUCITK.js";import{a as Ut,b as Bt,d as Ht}from"./chunk-Y4CYQV7G.js";import{g as Ot,h as jt,i as Vt,k as Wt,l as Ft}from"./chunk-22LO3GBP.js";import{q as Et}from"./chunk-4QCYSKPD.js";import{a as Pt,b as Tt}from"./chunk-A6B5JRUG.js";import{A as Xr,ba as Se,ia as _t,ja as Ct,ma as Dt,n as te,o as vt,p as $t,q as qr,y as It,z as Rt}from"./chunk-TXX5W3SH.js";import{f as At,n as Kr}from"./chunk-UIBUZ2N3.js";import{a as xe,h as Gr}from"./chunk-BRK6M6LA.js";import{existsSync as Jr,readdirSync as Yr,readFileSync as Zr,statSync as Qr}from"fs";import{resolve as ei}from"path";function Zt(t,e,n=Date.now(),r=7){let i=r*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(f=>n-f.at<=i),l=a.filter(f=>n-f.at>i&&n-f.at<=i*2),u=c.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ie=new Map;function _a(t,e=1e3){if(!Jr(t))return[];let n=Yr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ei(t,s);return{path:o,mtime:Qr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ie.keys())r.has(s)||ie.delete(s);let i=[];for(let{path:s,mtime:o}of n){let a=ie.get(s);if(a&&a.mtime===o){a.summary&&i.push(a.summary);continue}let c=ti(s,o);ie.set(s,{mtime:o,summary:c}),c&&i.push(c)}return i}function ti(t,e){try{let n=Zr(t,"utf-8").split(`
1
+ import{q as Xt}from"./chunk-S2GAEH2F.js";import{a as Re}from"./chunk-GTJIKXDB.js";import{a as re,b as w}from"./chunk-BGG3ZSMW.js";import{t as Gt,u as Kt}from"./chunk-4COYYJJY.js";import{d as zt,e as qt}from"./chunk-AQASR6KR.js";import{b as Jt,c as Ie,e as B,f as H,h as Yt}from"./chunk-JIT5GPTX.js";import{A as Ae,b as ve,v as Lt,x as ne,y as $e}from"./chunk-J3GXZQXY.js";import{a as Mt,b as Nt}from"./chunk-SHEUCITK.js";import{a as Ut,b as Bt,d as Ht}from"./chunk-Y4CYQV7G.js";import{g as Ot,h as jt,i as Vt,k as Wt,l as Ft}from"./chunk-YLKCFW2R.js";import{q as Et}from"./chunk-VGI4EZTP.js";import{a as Pt,b as Tt}from"./chunk-CYKPDILL.js";import{A as Xr,ba as Se,ia as _t,ja as Ct,ma as Dt,n as te,o as vt,p as $t,q as qr,y as It,z as Rt}from"./chunk-Y5HBYSJW.js";import{f as At,n as Kr}from"./chunk-UIBUZ2N3.js";import{a as xe,h as Gr}from"./chunk-BRK6M6LA.js";import{existsSync as Jr,readdirSync as Yr,readFileSync as Zr,statSync as Qr}from"fs";import{resolve as ei}from"path";function Zt(t,e,n=Date.now(),r=7){let i=r*864e5,s=new Map;for(let o of e){let a=s.get(o.workflowId);a?a.push(o):s.set(o.workflowId,[o])}return t.map(o=>{let a=s.get(o.id)??[],c=a.filter(f=>n-f.at<=i),l=a.filter(f=>n-f.at>i&&n-f.at<=i*2),u=c.filter(f=>f.status==="failed").length,d=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var ie=new Map;function _a(t,e=1e3){if(!Jr(t))return[];let n=Yr(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let o=ei(t,s);return{path:o,mtime:Qr(o).mtimeMs}}).sort((s,o)=>o.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ie.keys())r.has(s)||ie.delete(s);let i=[];for(let{path:s,mtime:o}of n){let a=ie.get(s);if(a&&a.mtime===o){a.summary&&i.push(a.summary);continue}let c=ti(s,o);ie.set(s,{mtime:o,summary:c}),c&&i.push(c)}return i}function ti(t,e){try{let n=Zr(t,"utf-8").split(`
2
2
  `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),i=r.run?.workflowId;if(!i)return null;let s=r.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:i,status:s,at:e}}catch{return null}}var ni={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},ri=(t,e,n)=>{try{return Et(t,e,n)}catch{return null}},Qt=864e5;function Ta(t){let e=t.now??Date.now(),n={...ni,...t.thresholds},r=t.nextFire??ri,i=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),d=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,k.text),trigger:{schedule:$(a.schedule,k.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?_e(a.nextRun)??_e(r(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:li(d.status==="success"?void 0:d.errorSummary,k.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:en(u),sampledRuns:c.length,flags:[],attention:null};p.flags=tn(p,u,a.schedule,l,null,e,n,r),i.push(nn(p))}let s=new Map(Zt(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(_=>_.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",p=(o.get(a.id)??[]).slice().sort((_,ke)=>ke.at-_.at),g=p.map(_=>({at:_.at,status:oi(_.status)})),f=g[0],m=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",P=typeof l.timezone=="string"?l.timezone:"UTC",j={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:$(a.title||a.id,k.text),trigger:m?{schedule:$(y,k.text),timezone:P}:{event:$(typeof l.event=="string"?l.event:"",k.text),filters:ci(l.filter,a)},agent:ai(a),enabled:d,state:u,nextRunAt:m&&d&&y?_e(r(y,new Date(e),P)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let _=g.find(ke=>ke.status==="success");return _?new Date(_.at).toISOString():null})(),consecutiveFailures:en(g),sampledRuns:p.length,flags:[],attention:null},ee=Date.parse(a.updated||a.created||"");j.flags=m?tn(j,g,y,P,Number.isFinite(ee)?ee:null,e,n,r):ii(j,s.get(a.id)?.state==="dormant",Number.isFinite(ee)?ee:null,e,n),i.push(nn(j))}return i.sort(si).slice(0,k.routines)}function en(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 tn(t,e,n,r,i,s,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=sn(l,i,s,o);return p&&c.push(p),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let p=0;p<o.missedFires&&(d=a(n,u,r),!!d);p++)u=d;return d&&s>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function ii(t,e,n,r,i){let s=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=sn(o,n,r,i);return a&&s.push(a),s}return t.consecutiveFailures>=i.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function sn(t,e,n,r){let i=Math.max(t??0,e??0);return i&&n-i<r.disabledDays*Qt?null:{reason:"disabled-long",detail:i?`Disabled; no activity for ${Math.floor((n-i)/Qt)} days`:"Disabled and never ran"}}function nn(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 rn={critical:0,warning:1,info:2};function si(t,e){let n=t.attention?rn[t.attention]:3,r=e.attention?rn[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function oi(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 ai(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 ci(t,e){let n=[],r=e?.project;if(r&&n.push($(`project=${r}`,k.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[i,s]of Object.entries(t)){let o=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];o.length&&n.push($(`${i}=${o.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function _e(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 li(t,e){return t===void 0?void 0:$(t,e)}import{existsSync as ae,readdirSync as Ri,readFileSync as _i}from"fs";import{resolve as T}from"path";import{randomBytes as cn}from"crypto";import{existsSync as di,mkdirSync as pi,readdirSync as gi,readFileSync as fi,renameSync as ln,unlinkSync as mi,writeFileSync as hi}from"fs";import{resolve as un}from"path";function on(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ui=t=>t.trim().split(`
3
3
  `).pop()?.slice(0,300)||"no output";async function an(t,e,n,r=Re){let i=await r(t.bin,[...on(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return i.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ui(i.stderr||i.stdout)}`}}async function Ma(t,e,n,r,i=Re){return(await i(t.bin,[...on(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var yi=2e3,bi=t=>an(t.wacli,t.to,t.text);function Ce(t){return un(t,".agentx","whatsapp-triage","drafts")}var wi=t=>/^[a-z0-9-]{8,64}$/.test(t),se=(t,e)=>un(Ce(t),`${e}.json`);function dn(t,e){pi(Ce(t),{recursive:!0});let n=se(t,e.id),r=`${n}.${process.pid}.tmp`;hi(r,JSON.stringify(e,null,2)+`
4
4
  `,{mode:384}),ln(r,n)}function Fa(t,e,n=Date.now()){let r=e.text.trim().slice(0,yi);if(!r)throw new Error("empty draft");let i={...e,text:r,id:`${n.toString(36)}-${cn(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return dn(t,i),i}function oe(t,e){if(!wi(e))return null;try{return JSON.parse(fi(se(t,e),"utf-8"))}catch{return null}}function pn(t,e){let n=Ce(t);return di(n)?gi(n).filter(r=>r.endsWith(".json")).map(r=>oe(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,i)=>r.created_at.localeCompare(i.created_at)):[]}async function gn(t,e,n,r={}){let i=oe(t,e);if(!i||i.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${se(t,e)}.${process.pid}.${cn(3).toString("hex")}.claim`;try{ln(se(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let o={...i,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")o.status="rejected";else{let a=await(r.send??bi)(i).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?o.status="sent":(o.status="failed",o.error=a.error)}dn(t,o);try{mi(s)}catch{}return o.status==="failed"?{ok:!1,error:o.error??"send failed"}:{ok:!0,draft:o}}import{mkdirSync as ki,readFileSync as xi,renameSync as Si,writeFileSync as vi}from"fs";import{resolve as $i}from"path";function fn(t){return $i(Ie(t),"_state.json")}function A(t){try{let e=JSON.parse(xi(fn(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function z(t,e){ki(Ie(t),{recursive:!0});let n=fn(t),r=`${n}.${process.pid}.tmp`;vi(r,JSON.stringify(e,null,2)+`
@@ -479,4 +479,4 @@ Document the arguments, commands, or files the skill expects. Example:
479
479
  claude-code ${St(t)} --arg value
480
480
  \`\`\`
481
481
  `}Dt();var Ur={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Br(t){return{...Ur,...t??{},regions:{...t?.regions??{}},buffer:{...Ur.buffer,...t?.buffer??{}}}}function Ju(t){try{return Br(Ct(t).screen)}catch{return Br(void 0)}}var Aa=/^[a-z][\w-]*$/,Hr=["window","screen","menubar","notifications"];function Q(t,e,n,r){let i=Number(t);if(t===""||t===null||!Number.isFinite(i)||!n(i))throw new Error(`${e} must be ${r}`);return i}var we=(t,e)=>Q(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function zr(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Yu(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=we(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=we(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=we(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=Q(e.stableMs,"stableMs",i=>Number.isInteger(i)&&i>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=Q(e.changeThreshold,"changeThreshold",i=>i>=0&&i<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let i={...n.regions??{}};for(let[s,o]of Object.entries(e.regions)){if(!Aa.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);o===null?delete i[s]:i[s]=zr(o)}n.regions=i}if(e.buffer&&typeof e.buffer=="object"){let i=e.buffer,s={...n.buffer??{}};"enabled"in i&&(s.enabled=!!i.enabled),"seconds"in i&&(s.seconds=Q(i.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in i&&(s.fps=Q(i.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in i&&(s.maxPixels=we(i.maxPixels,"buffer.maxPixels")),"region"in i&&(s.region=String(i.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!Hr.includes(r)&&!n.regions?.[r])try{zr(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Hr,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Zt as a,_a as b,tt as c,Bs as d,Hs as e,cl as f,ll as g,ul as h,rr as i,pl as j,fl as k,E as l,ir as m,k as n,Ta as o,Ma as p,bi as q,Fa as r,gn as s,A as t,qa as u,Ga as v,bn as w,Qa as x,q as y,gc as z,vn as A,hl as B,nt as C,sr as D,wl as E,Sl as F,wr as G,Xl as H,Jl as I,nu as J,Uo as K,ru as L,mc as M,hc as N,yc as O,bc as P,wc as Q,kc as R,Sc as S,vc as T,Tc as U,Oe as V,Ec as W,Lc as X,G as Y,K as Z,Ko as _,pu as $,gu as aa,fu as ba,mu as ca,ut as da,hu as ea,We as fa,Fe as ga,ge as ha,ls as ia,ds as ja,Vc as ka,Be as la,He as ma,ps as na,gs as oa,Bn as pa,Gn as qa,Wc as ra,hs as sa,Fc as ta,$s as ua,Rs as va,ze as wa,Cs as xa,Kn as ya,L as za,Pr as Aa,Tr as Ba,Er as Ca,Su as Da,ra as Ea,Mr as Fa,Nr as Ga,Eu as Ha,Lu as Ia,wa as Ja,Mu as Ka,jr as La,fe as Ma,Qc as Na,er as Oa,qe as Pa,Qe as Qa,ol as Ra,Vu as Sa,Wu as Ta,Fu as Ua,Uu as Va,Bu as Wa,Hu as Xa,zu as Ya,qu as Za,Gu as _a,Ur as $a,Br as ab,Ju as bb,Hr as cb,Yu as db};
482
- //# sourceMappingURL=chunk-OZDSQVHU.js.map
482
+ //# sourceMappingURL=chunk-6WNQY6K2.js.map
@@ -1,4 +1,4 @@
1
- import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-TXX5W3SH.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-Y5HBYSJW.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
- //# sourceMappingURL=chunk-74CQWVHE.js.map
114
+ //# sourceMappingURL=chunk-A35RTVMM.js.map
@@ -1,4 +1,6 @@
1
- var g={};function v(t){g=t}function w(){return g}var y=`<link rel="preconnect" href="https://fonts.googleapis.com">
1
+ var g={};function v(t){g=t}function w(){return g}var y=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
2
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png">
3
+ <link rel="preconnect" href="https://fonts.googleapis.com">
2
4
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
3
5
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
4
6
  <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,k=`
@@ -298,4 +300,4 @@ var g={};function v(t){g=t}function w(){return g}var y=`<link rel="preconnect" h
298
300
  </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function d(t){return String(t||"").replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a])}function P(t,a={}){let e=String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(s,i,n)=>`<pre><code class="lang-${i}">${n.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>");let c=[],h=[],x=a.images?"axpic"+Math.random().toString(36).slice(2,10)+"n":"";if(a.images){let s=typeof a.images=="number"?a.images:8;e=e.replace(/<code[^>]*>[\s\S]*?<\/code>|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(i,n,r)=>n===void 0||r===void 0?i:/^https?:\/\/[^\s]+$/i.test(r)?c.length>=s?`[${n||r}](${r})`:(c.push(`<img src="${r}" alt="${n}" loading="lazy" referrerpolicy="no-referrer">`),h.push(n),x+(c.length-1)+"z"):n)}if(e=e.replace(/^(\|.+\|)\n(\|[-| :]+\|)\n((?:\|.+\|\n?)*)/gm,(s,i,n,r)=>{let p=i.split("|").filter(l=>l.trim()).map(l=>`<th>${l.trim()}</th>`).join(""),o=r.trim().split(`
299
301
  `).map(l=>`<tr>${l.split("|").filter(u=>u.trim()).map(u=>`<td>${u.trim()}</td>`).join("")}</tr>`).join("");return`<table><thead><tr>${p}</tr></thead><tbody>${o}</tbody></table>`}),e=e.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),e=e.replace(/^### (.+)$/gm,"<h3>$1</h3>"),e=e.replace(/^## (.+)$/gm,"<h2>$1</h2>"),e=e.replace(/^# (.+)$/gm,"<h1>$1</h1>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[\[([^\]]+)\]\]/g,(s,i)=>{let[n,r]=i.split("|",2),p=n.trim().replace(/^\//,""),o=(r||n).trim();return a.wikilink?a.wikilink(p,o):o}),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/^(>\s?.*(?:\n>\s?.*)*)/gm,s=>`<blockquote>${s.split(`
300
302
  `).map(n=>n.replace(/^>\s?/,"")).join("<br>")}</blockquote>`),e=e.replace(/^[-*] \[( |x|X)\] (.+)$/gm,(s,i,n)=>`<li class="task">${i.toLowerCase()==="x"?"\u2611":"\u2610"} ${n}</li>`),e=e.replace(/^[-*] (.+)$/gm,"<li>$1</li>"),e=e.replace(/^\d+\. (.+)$/gm,'<li data-ordered="1">$1</li>'),e=e.replace(/(<li data-ordered="1">.*?<\/li>(?:\n?<li data-ordered="1">.*?<\/li>)*)/g,"<ol>$1</ol>"),e=e.replace(/((?:<li(?! data-ordered)[^>]*>.*?<\/li>\n?)+)/g,"<ul>$1</ul>"),e=e.replace(/ data-ordered="1"/g,""),e=e.replace(/^---$/gm,"<hr>"),e=e.replace(/\n\n+/g,"</p><p>"),e=`<p>${e}</p>`,e=e.replace(/<p>\s*(<(?:h[1-6]|ul|ol|blockquote|table|pre|hr)\b[^>]*>[\s\S]*?<\/(?:h[1-6]|ul|ol|blockquote|table|pre)>)\s*<\/p>/g,"$1"),e=e.replace(/<p>\s*<hr>\s*<\/p>/g,"<hr>"),e=e.replace(/<p>\s*<\/p>/g,""),e=e.replace(/<p>(<(?:h[1-4]|pre|table|ul|hr|div))/g,"$1"),e=e.replace(/(<\/(?:h[1-4]|pre|table|ul|hr|div)>)<\/p>/g,"$1"),e=e.replace(/<p>\s*<\/p>/g,""),c.length){let s=new RegExp(x+"(\\d+)z","g");e=e.split(/(<[^>]*>)/).map(i=>i.charAt(0)==="<"?i.replace(s,(n,r)=>h[Number(r)]):i.replace(s,(n,r)=>c[Number(r)])).join("")}return e}function A(t){return String(t??"").replace(/[&<>"']/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[a])}export{P as a,A as b,v as c,w as d,y as e,k as f,_ as g,$ as h,S as i};
301
- //# sourceMappingURL=chunk-DG5I6PPM.js.map
303
+ //# sourceMappingURL=chunk-BGG3ZSMW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/daemon/topbar.ts","../src/utils/markdown-html.ts","../src/daemon/ui/util.ts"],"sourcesContent":["// --- Shared top-chrome for every dashboard surface ---\n//\n// Four pages render in different files (live + kanban + glossary in\n// board-dashboard.ts, settings in admin-panel.ts) but must share: design\n// tokens, fonts, theme switcher, brand, primary tab nav, and a mesh-node\n// selector. This module exports the CSS + HTML snippets so each page\n// composes exactly the same chrome and we never drift them again.\n//\n// Nothing here is page-specific — callers pass in { activeTab, subtitle,\n// subheader? } and compose their own <main> below.\n\nexport type TopbarTab = \"monitor\" | \"activity\" | \"live\" | \"mesh\" | \"boards\" | \"admin\" | \"graph\" | \"glossary\" | \"workflows\" | \"health\" | \"cost\" | \"wiki\" | \"procedures\" | \"inbox\" | \"projects\" | \"approvals\" | \"people\"\n\nexport interface TopbarPeer {\n /** Stable id: primary node id, or URL for configured daemons */\n id: string\n name: string\n /** Absolute URL of the peer's dashboard (http://host:port) — selector\n * navigates to <url>/admin when switched. */\n dashboardUrl: string\n /** True for the node hosting this dashboard (locks the default). */\n primary?: boolean\n /** Optional; shown in the dropdown as \"managing via token\" hint. */\n tokenScope?: string\n}\n\nexport interface TopbarFeatures {\n /** Show the Team/Business Settings sub-tabs — config.business.enabled. */\n business?: boolean\n}\n\n// Set once at server start (board-dashboard + daemon both call it).\n//\n// This used to carry `boards` and `workflows` flags that gated top-level\n// tabs. The nav is now fixed (Live, Operations, Settings), so those flags had\n// nothing left to gate and were removed rather than left describing chrome\n// that no longer exists.\nlet topbarFeatures: TopbarFeatures = {}\n\nexport function setTopbarFeatures(features: TopbarFeatures): void {\n topbarFeatures = features\n}\n\nexport function getTopbarFeatures(): TopbarFeatures {\n return topbarFeatures\n}\n\nexport interface TopbarOpts {\n activeTab: TopbarTab\n /** Text after the brand, e.g. \"Live\" / \"Settings\" / \"Boards\". */\n subtitle: string\n /** Optional HTML inserted as a second row under the topbar. */\n subheader?: string\n /** Peers to list in the mesh selector. */\n peers?: TopbarPeer[]\n /** id of the peer currently being managed — defaults to the primary. */\n currentPeerId?: string\n /** Optional right-side HTML added before the theme switcher (clocks,\n * connection dots, etc.). */\n rightExtras?: string\n}\n\n/**\n * Font link tags + tiny inline bootstrap script. Callers drop this in <head>.\n */\n// Fonts degrade to the system stack when the box is offline or air-gapped —\n// the tokens list real fallbacks, so a failed font fetch costs typography,\n// never layout.\n//\n// The theme bootstrap runs before first paint to avoid a flash. A stored\n// \"crt\" from before that theme was removed falls back to dark rather than\n// leaving data-theme set to a value no stylesheet defines.\nexport const TOPBAR_HEAD = `<link rel=\"icon\" type=\"image/svg+xml\" href=\"/favicon.svg\">\n<link rel=\"apple-touch-icon\" href=\"/apple-touch-icon.png\">\n<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n<link href=\"https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap\" rel=\"stylesheet\">\n<script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`\n\n/**\n * CSS for topbar + subheader + theme switch + mesh selector. No token\n * definitions — those are per-page because each page's CSS block owns its\n * own :root overrides.\n */\nexport const TOPBAR_CSS = `\n.ax-topbar{display:flex;align-items:center;justify-content:space-between;\n padding:8px 18px;border-bottom:1px solid var(--ax-border);\n background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}\n.ax-topbar__left{display:flex;align-items:center;gap:18px;min-width:0}\n.ax-brand{display:flex;align-items:center;gap:10px;font-weight:600;letter-spacing:-0.01em;flex-shrink:0}\n.ax-brand__mark{font-family:var(--ax-mono);font-size:12px;padding:2px 8px;\n border:1px solid var(--ax-border-2);color:var(--ax-accent);border-radius:4px}\n.ax-brand__name{font-size:14px}\n.ax-brand__subtitle{font-size:11px;color:var(--ax-muted);\n border-left:1px solid var(--ax-border);padding-left:12px;margin-left:4px}\n.ax-topbar__tabs{display:flex;gap:14px;min-width:0;overflow-x:auto;align-items:center}\n/* Tier groups (System / Processes / Procedures) — visual separators\n * mirror the docs/architecture/three-tier.md hierarchy. */\n.ax-topbar__group{display:flex;align-items:center;gap:0;padding:0 4px;\n border-left:1px solid var(--ax-border);position:relative}\n.ax-topbar__group:first-child{border-left:none;padding-left:0}\n.ax-topbar__group-label{font:inherit;font-family:var(--ax-mono);font-size:9px;\n letter-spacing:0.08em;text-transform:uppercase;color:var(--ax-muted);\n padding:0 8px;white-space:nowrap;opacity:0.7}\n.ax-topbar__tab{background:transparent;border:none;color:var(--ax-text-2);\n padding:8px 12px;font:inherit;cursor:pointer;font-size:12px;text-decoration:none;\n border-bottom:2px solid transparent;letter-spacing:-0.005em;white-space:nowrap}\n.ax-topbar__tab:hover{color:var(--ax-text)}\n.ax-topbar__tab.is-active{color:var(--ax-text);border-bottom-color:var(--ax-accent)}\n.ax-topbar__right{display:flex;align-items:center;gap:10px;font-size:11px;\n color:var(--ax-muted);flex-shrink:0}\n.ax-topbar__right .ax-mono{color:var(--ax-text-2)}\n\n/* Running build: version, commit, running since; warns when the code on\n * disk has moved on. */\n.ax-build{display:inline-flex;align-items:center;gap:8px;white-space:nowrap}\n.ax-build[hidden]{display:none}\n/* Two short lines, so the tabs keep their room on a laptop screen. */\n.ax-build__lines{display:flex;flex-direction:column;font-size:10px;line-height:1.3}\n.ax-build__stale{color:var(--ax-warn,var(--ax-accent));border:1px solid currentColor;\n border-radius:4px;padding:1px 6px}\n\n/* Mesh selector */\n.ax-mesh-sel{position:relative;display:inline-flex;align-items:center;gap:6px;\n padding:4px 10px;border:1px solid var(--ax-border-2);border-radius:4px;\n background:var(--ax-surface);cursor:pointer;font:inherit;font-size:11px;\n color:var(--ax-text-2);white-space:nowrap}\n.ax-mesh-sel:hover{border-color:var(--ax-accent);color:var(--ax-text)}\n.ax-mesh-sel.is-proxy{background:color-mix(in oklch,var(--ax-accent) 14%,var(--ax-surface));\n border-color:color-mix(in oklch,var(--ax-accent) 45%,var(--ax-border-2));color:var(--ax-accent)}\n.ax-mesh-sel .lbl{font-size:9px;letter-spacing:0.06em;text-transform:uppercase;color:var(--ax-muted);margin-right:2px}\n.ax-mesh-sel .name{font-weight:500;color:var(--ax-text)}\n.ax-mesh-sel .chev{font-size:9px;opacity:0.6;margin-left:2px}\n.ax-mesh-menu{position:absolute;top:calc(100% + 4px);right:0;min-width:240px;\n background:var(--ax-surface);border:1px solid var(--ax-border-2);\n border-radius:6px;box-shadow:0 8px 24px rgba(0,0,0,0.4);padding:4px;z-index:30;display:none}\n.ax-mesh-sel.is-open .ax-mesh-menu{display:block}\n.ax-mesh-menu a{display:block;padding:7px 10px;border-radius:4px;text-decoration:none;\n color:var(--ax-text-2);font-size:12px}\n.ax-mesh-menu a:hover{background:var(--ax-surface-2);color:var(--ax-text)}\n.ax-mesh-menu a.is-current{background:color-mix(in oklch,var(--ax-accent) 12%,var(--ax-surface));\n color:var(--ax-accent);border:1px solid color-mix(in oklch,var(--ax-accent) 30%,var(--ax-border-2))}\n.ax-mesh-menu a .row{display:flex;align-items:center;gap:8px}\n.ax-mesh-menu a .row .dot{width:6px;height:6px;border-radius:50%;background:var(--ax-accent)}\n.ax-mesh-menu a.is-offline .row .dot{background:var(--ax-border-2)}\n.ax-mesh-menu a .url{font-family:var(--ax-mono);font-size:10px;color:var(--ax-muted);margin-top:2px}\n\n/* Theme switcher segmented control */\n.ax-theme-switch{display:inline-flex;border:1px solid var(--ax-border-2);\n border-radius:4px;overflow:hidden}\n.ax-theme-switch button{background:transparent;border:none;color:var(--ax-muted);\n padding:3px 9px;font:inherit;font-size:10px;cursor:pointer;letter-spacing:0.04em;\n text-transform:uppercase;font-family:var(--ax-mono);border-right:1px solid var(--ax-border-2)}\n.ax-theme-switch button:last-child{border-right:none}\n.ax-theme-switch button:hover{color:var(--ax-text);background:var(--ax-surface-2,var(--ax-surface))}\n.ax-theme-switch button.is-active{color:var(--ax-accent);\n background:color-mix(in oklch,var(--ax-accent) 12%,var(--ax-surface))}\n\n/* Subheader — page-specific toolbar below the main topbar. Kanban uses it\n * for the board picker + search + filters; others can use it for context\n * bars if they want. */\n.ax-subheader{display:flex;align-items:center;gap:10px;padding:10px 18px;\n background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);\n flex-wrap:wrap}\n.ax-subheader > * {flex-shrink:0}\n.ax-subheader .spacer{flex:1}`\n\n/**\n * Shared click wiring for the theme switcher + mesh selector. Safe to call\n * multiple times — only binds once per element.\n */\nexport const TOPBAR_SCRIPT = `<script>\n(function(){\n function wireTheme(){\n var sw = document.querySelectorAll('[data-theme-opt]');\n if (!sw.length) return;\n var current = document.documentElement.getAttribute('data-theme') || 'dark';\n sw.forEach(function(b){\n if (b.dataset.wired) return; b.dataset.wired = '1';\n if (b.getAttribute('data-theme-opt') === current) b.classList.add('is-active');\n b.addEventListener('click', function(){\n var t = b.getAttribute('data-theme-opt');\n document.documentElement.setAttribute('data-theme', t);\n try { localStorage.setItem('ax-theme', t); } catch (e) {}\n sw.forEach(function(x){ x.classList.toggle('is-active', x === b); });\n });\n });\n }\n function currentPeer(){\n try { return localStorage.getItem('ax-peer') || 'primary'; } catch { return 'primary'; }\n }\n function setCurrentPeer(id){\n try {\n if (id && id !== 'primary') localStorage.setItem('ax-peer', id);\n else localStorage.removeItem('ax-peer');\n } catch {}\n }\n function reflectPeerPill(){\n var sel = document.querySelector('.ax-mesh-sel');\n if (!sel) return;\n var cur = currentPeer();\n sel.classList.toggle('is-proxy', cur !== 'primary');\n // If a proxy is active, update the visible pill label + highlight.\n var picked = null;\n sel.querySelectorAll('.ax-mesh-menu a').forEach(function(a){\n a.classList.toggle('is-current', a.getAttribute('data-peer-id') === cur || (cur === 'primary' && a.getAttribute('data-peer-id') === 'primary'));\n if (a.getAttribute('data-peer-id') === cur) picked = a;\n });\n if (picked) {\n var name = picked.querySelector('span'); // first <span> inside .row\n var visibleName = sel.querySelector('.name');\n if (name && visibleName) visibleName.textContent = name.textContent.replace(/ · primary/, '');\n }\n }\n function wireMesh(){\n var sel = document.querySelector('.ax-mesh-sel');\n if (!sel || sel.dataset.wired) return; sel.dataset.wired = '1';\n sel.addEventListener('click', function(e){\n var link = e.target.closest('.ax-mesh-menu a[data-peer-action=\"proxy\"]');\n if (link) {\n e.preventDefault();\n setCurrentPeer(link.getAttribute('data-peer-id'));\n reflectPeerPill();\n sel.classList.remove('is-open');\n // Reload so the admin panel re-reads state from the selected peer.\n location.reload();\n return;\n }\n if (e.target.closest('.ax-mesh-menu a')) return; // plain navigate anchor\n sel.classList.toggle('is-open');\n });\n document.addEventListener('click', function(e){\n if (!sel.contains(e.target)) sel.classList.remove('is-open');\n });\n reflectPeerPill();\n }\n function wireHostRewrite(){\n try {\n var h = location.hostname || 'localhost';\n document.querySelectorAll('.ax-topbar__tab[href*=\"__HOST__\"]').forEach(function(a){\n a.href = a.getAttribute('href').replace(/__HOST__/g, h);\n });\n } catch (e) {}\n }\n /**\n * Make the topbar peer selector actually drive page content. When the\n * operator picks a non-primary peer, every /api/admin/* request gets an\n * X-Agentx-Peer header (and every EventSource on that path gets a ?peer=\n * query, since EventSource can't set headers). The dashboard's existing\n * proxy handler picks it up and forwards to the chosen peer.\n *\n * Without this hook, the activity-graph (and other admin pages) silently\n * keep showing only the local node's data even after the operator picks\n * a different peer in the topbar.\n */\n function wirePeerProxy(){\n if (window.__axPeerWired) return; window.__axPeerWired = true;\n // Path-prefix allowlist for the peer-proxy interceptor. Extend here\n // when a new admin-side surface needs to follow the mesh selector.\n // /api/workflows is the workflow dashboard's read/write API — it\n // lives outside /api/admin for legacy reasons, but the page is part\n // of the admin surface and should proxy when a non-primary peer is\n // selected (otherwise the workflows page on Mac shows local-only\n // YAMLs while the runtime lives on peer).\n function shouldProxy(url){\n if (!url) return false;\n // Admin-side surfaces that follow the mesh selector. Each entry\n // is a path-prefix match. Extend when a new admin surface lands\n // outside /api/admin/* but should still proxy when the operator\n // picks a non-primary peer.\n // /api/admin/ — original admin surface (activity, ledger, …)\n // /api/workflows — workflow editor + observability page\n // /api/agents — agent dropdowns inside the workflow editor +\n // anywhere else the page asks \"which agents\n // exist on the selected node?\"\n return url.indexOf('/api/admin/') >= 0\n || url.indexOf('/api/workflows') >= 0\n || url.indexOf('/api/agents') >= 0;\n }\n var origFetch = window.fetch.bind(window);\n window.fetch = function(input, init){\n try {\n var peer = currentPeer();\n if (peer && peer !== 'primary') {\n var url = typeof input === 'string' ? input : (input && input.url) || '';\n if (shouldProxy(url)) {\n init = init || {};\n init.headers = new Headers(init.headers || {});\n init.headers.set('X-Agentx-Peer', peer);\n }\n }\n } catch (e) {}\n return origFetch(input, init);\n };\n var OrigES = window.EventSource;\n if (OrigES) {\n window.EventSource = function(url, cfg){\n try {\n var peer = currentPeer();\n if (peer && peer !== 'primary' && typeof url === 'string' && shouldProxy(url)) {\n url += (url.indexOf('?') >= 0 ? '&' : '?') + 'peer=' + encodeURIComponent(peer);\n }\n } catch (e) {}\n return new OrigES(url, cfg);\n };\n window.EventSource.prototype = OrigES.prototype;\n window.EventSource.CONNECTING = OrigES.CONNECTING;\n window.EventSource.OPEN = OrigES.OPEN;\n window.EventSource.CLOSED = OrigES.CLOSED;\n }\n }\n // wirePeerProxy() is synchronous and DOM-independent — it just wraps\n // window.fetch + window.EventSource. Fire it IMMEDIATELY (before\n // DOMContentLoaded) so deferred page bundles that issue their first\n // fetch on bundle-parse (e.g. the workflow editor's React useEffect)\n // see the wrapped fetch and pick up the X-Agentx-Peer header. Without\n // this, the workflow editor's load on Mac:4202 hit local /api/workflows\n // (instead of proxying to the selected peer), got a 404, and silently\n // fell back to blank-graph state — looking like a \"new workflow\".\n wirePeerProxy();\n // Which build the daemon is running and since when, on every page; says\n // so when the code on disk is newer. Asked again every minute, so a\n // rebuild or a restart shows without a reload.\n function wireBuild(){\n var el = document.querySelector('.ax-build');\n if (!el || el.dataset.wired) return; el.dataset.wired = '1';\n function span(cls, text){ var s = document.createElement('span'); if (cls) s.className = cls; s.textContent = text; return s; }\n function load(){\n fetch('/api/node/build').then(function(r){ return r.ok ? r.json() : null; }).then(function(b){\n if (!b || !b.version) return;\n el.textContent = '';\n var lines = span('ax-build__lines', '');\n lines.appendChild(span('ax-mono', b.version + (b.commit ? ' · ' + b.commit : '')));\n var d = b.startedAt ? new Date(b.startedAt) : null;\n if (d && !isNaN(d.getTime())) {\n lines.appendChild(span('', 'since ' + d.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));\n }\n el.appendChild(lines);\n if (b.diskNewer) {\n var w = span('ax-build__stale', 'restart pending');\n w.setAttribute('role', 'status');\n el.appendChild(w);\n }\n el.title = (b.diskNewer\n ? 'The code on disk is newer than the running daemon. Restart the daemon to load it.'\n : 'The build the daemon is running, and when it started.') + (b.node ? ' Node: ' + b.node : '');\n el.hidden = false;\n }).catch(function(){});\n }\n load();\n setInterval(load, 60000);\n }\n function wire(){ wireHostRewrite(); wireTheme(); wireMesh(); wireBuild(); /* wirePeerProxy already ran */ }\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', wire);\n } else { wire(); }\n})();\n</script>`\n\n/**\n * What the header shows of the daemon's GET /health (served to the page as\n * GET /api/node/build). The dashboard is its own process, so its own build\n * and start time would be the wrong answer.\n */\nexport function headerBuild(health: any): { node: string | null; version: string | null; commit: string | null; startedAt: string | null; diskNewer: boolean } {\n const text = (v: unknown) => (typeof v === \"string\" && v ? v : null)\n return {\n node: text(health?.node?.id),\n version: text(health?.version),\n commit: text(health?.commit),\n startedAt: text(health?.startedAt),\n diskNewer: health?.build?.newer === true,\n }\n}\n\n/** Where the page script (wireBuild) puts the daemon's build. Empty and\n * hidden until the daemon has answered. */\nexport const BUILD_PILL = '<span class=\"ax-build\" hidden></span>'\n\n/**\n * Render the topbar element. Caller places this at the start of <body>.\n * Emits a matching .ax-subheader row only when `subheader` HTML is provided.\n */\nexport function renderTopbar(opts: TopbarOpts): string {\n const peers = opts.peers && opts.peers.length > 0 ? opts.peers : [{ id: \"local\", name: \"this daemon\", dashboardUrl: \"\", primary: true }]\n const currentId = opts.currentPeerId || peers.find((p) => p.primary)?.id || peers[0].id\n const current = peers.find((p) => p.id === currentId) || peers[0]\n\n const meshMenu = peers.map((p) => {\n const isCurrent = p.id === currentId\n const primaryMark = p.primary ? ' <span style=\"color:var(--ax-muted);font-size:10px\">· primary</span>' : \"\"\n const proxyable = !!p.tokenScope && !p.primary\n // Proxyable peers: use data-peer-id so the click handler switches locally\n // via localStorage + reload. Un-proxyable (no token): legacy navigate.\n const href = proxyable\n ? \"#\"\n : p.dashboardUrl\n ? `${p.dashboardUrl.replace(/\\/+$/, \"\")}/admin`\n : \"#\"\n const dataAttr = proxyable ? ` data-peer-id=\"${esc(p.id)}\" data-peer-action=\"proxy\"` : p.primary ? ` data-peer-id=\"primary\" data-peer-action=\"proxy\"` : \"\"\n const hint = proxyable\n ? '<div class=\"url\" style=\"color:var(--ax-accent)\">manage from this dashboard ✓</div>'\n : p.tokenScope\n ? `<div class=\"url\">${esc(p.tokenScope)}</div>`\n : p.dashboardUrl\n ? '<div class=\"url\" style=\"color:var(--ax-muted)\">(open peer dashboard ↗)</div>'\n : \"\"\n return `<a href=\"${esc(href)}\" class=\"${isCurrent ? \"is-current\" : \"\"}\"${dataAttr}>\n <div class=\"row\"><span class=\"dot\"></span><span>${esc(p.name)}${primaryMark}</span></div>\n ${p.dashboardUrl ? `<div class=\"url\">${esc(p.dashboardUrl)}</div>` : \"\"}\n ${hint}\n </a>`\n }).join(\"\")\n\n const meshSelector = `<div class=\"ax-mesh-sel\" aria-haspopup=\"menu\">\n <span class=\"lbl\">managing</span>\n <span class=\"name\">${esc(current.name)}</span>\n <span class=\"chev\">▾</span>\n <div class=\"ax-mesh-menu\" role=\"menu\">${meshMenu}</div>\n </div>`\n\n // Minimal, mesh-first nav. The primary group answers the four ops\n // questions in order: who's alive and what are they doing (Live),\n // what happened (Ledger), what did it cost (Cost), how is it wired\n // (Settings). A second \"Work\" group appears only when the operator\n // actually configured that surface (boards / workflows) — flags are\n // set once per process via setTopbarFeatures().\n //\n // Deliberately NOT in the nav (all still routable by URL):\n // /admin/ledger /admin/cost what happened, what it cost\n // /workflows /inbox BPM surfaces\n // / (boards) Kanban\n // /admin/health /admin/graph /admin/projects\n // /procedures /admin/wiki /glossary /processes\n //\n // The nav is the set of surfaces an operator opens on purpose, not a site\n // map. Workflows earned its way back: automation that stops running reports\n // nothing anywhere else, so it needs somewhere to be found. Every page still\n // listed above is one link away from Live or Settings, and none of them is\n // where an operator starts their day —\n // \"who is alive and what are they doing\" (Live) and \"how is this wired\"\n // (Settings) are. A tab bar that lists every surface an app HAS is a site\n // map, not navigation; it makes the two answers people actually want\n // harder to find, which is the opposite of what chrome is for.\n //\n // Removing a tab does not remove the page. If view counts later show a\n // surface earning its place, adding a tab back is one line.\n type Tab = { id: TopbarTab; label: string; href: string; external?: boolean }\n const groups: Array<{ name: string; tabs: Tab[] }> = [\n {\n name: \"Mesh\",\n tabs: [\n { id: \"live\", label: \"Live\", href: \"/live\" },\n { id: \"mesh\", label: \"Operations\", href: \"/mesh\" },\n { id: \"monitor\", label: \"Monitor\", href: \"/monitor\" },\n { id: \"approvals\", label: \"Approvals\", href: \"/approvals\" },\n { id: \"people\", label: \"People\", href: \"/people\" },\n { id: \"activity\", label: \"Activity\", href: \"/activity\" },\n { id: \"workflows\", label: \"Workflows\", href: \"/workflows\" },\n { id: \"admin\", label: \"Settings\", href: \"/admin\" },\n ],\n },\n ]\n\n const tabs = groups.map((g) => {\n const inner = g.tabs.map((t) => {\n const cls = t.id === opts.activeTab ? \"ax-topbar__tab is-active\" : \"ax-topbar__tab\"\n const extAttrs = t.external ? ` target=\"_blank\" rel=\"noopener\"` : \"\"\n const extGlyph = t.external ? ' <span style=\"font-size:9px;opacity:0.6\">↗</span>' : \"\"\n return `<a href=\"${t.href}\" class=\"${cls}\"${extAttrs}>${t.label}${extGlyph}</a>`\n }).join(\"\")\n return `<div class=\"ax-topbar__group\" title=\"${esc(g.name)} tier\"><span class=\"ax-topbar__group-label\">${esc(g.name)}</span>${inner}</div>`\n }).join(\"\")\n\n const header = `<header class=\"ax-topbar\">\n <div class=\"ax-topbar__left\">\n <div class=\"ax-brand\">\n <span class=\"ax-brand__mark\">AX</span>\n <span class=\"ax-brand__name\">AgentX</span>\n <span class=\"ax-brand__subtitle\">${esc(opts.subtitle)}</span>\n </div>\n <nav class=\"ax-topbar__tabs\">${tabs}</nav>\n </div>\n <div class=\"ax-topbar__right\">\n ${opts.rightExtras || \"\"}\n ${BUILD_PILL}\n ${meshSelector}\n <div class=\"ax-theme-switch\" role=\"tablist\" aria-label=\"Theme\">\n <button data-theme-opt=\"dark\">Dark</button>\n <button data-theme-opt=\"light\">Light</button>\n </div>\n </div>\n</header>${opts.subheader ? `<div class=\"ax-subheader\">${opts.subheader}</div>` : \"\"}`\n return header\n}\n\nfunction esc(s: string): string {\n return String(s || \"\").replace(/[&<>\"']/g, (c) => ({ \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\" }[c] as string))\n}\n","// --- Markdown to HTML, shared -------------------------------------------\n//\n// One renderer for the wiki, the dashboard's ask-an-agent drawer and the task\n// conversation view. It escapes first and only then adds markup, because\n// everything it renders — wiki articles, agent replies — is written by\n// someone or something other than the person reading it.\n//\n// Deliberately small: headings, bold/italic, code, links, lists, tables,\n// blockquotes and rules, and pictures for a caller that asks. Anything it\n// does not know stays as text.\n\nexport interface MarkdownOptions {\n /** Resolve [[wikilinks]]. Omitted, they render as their display text. */\n wikilink?: (target: string, display: string) => string\n /** Render `![alt](https://…)` as a picture: `true` for up to 8, or the\n * most to show. Web addresses only; pictures past the limit become links.\n * Omitted, a picture stays a link, as it always was. */\n images?: boolean | number\n}\n\nexport function markdownToHtml(text: string, opts: MarkdownOptions = {}): string {\n // Strip section-tag HTML comments before escaping so they don't render\n // as literal \"<!-- tags: ... -->\" in the output.\n // Inlined rather than a module-scope helper: this function is stringified\n // and shipped to the browser, where the minifier renames such a helper and\n // module scope does not travel with the source.\n let html = String(text ?? \"\")\n .replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\").replace(/'/g, \"&#39;\")\n\n // Code blocks (fenced)\n html = html.replace(/```(\\w*)\\n([\\s\\S]*?)```/g, (_m, lang, code) =>\n `<pre><code class=\"lang-${lang}\">${code.trim()}</code></pre>`)\n\n // Inline code\n html = html.replace(/`([^`]+)`/g, '<code>$1</code>')\n\n // Pictures, only for a caller that opts in. Code is left alone. Each\n // picture waits as a placeholder of plain letters and digits until every\n // other rule has run, so no later rule can take its markup apart; one\n // that ends up inside a tag (say, a link's address) becomes its alt text.\n // The text is escaped already, so the address and alt hold no quotes.\n const pics: string[] = []\n const alts: string[] = []\n const mark = opts.images ? \"axpic\" + Math.random().toString(36).slice(2, 10) + \"n\" : \"\"\n if (opts.images) {\n const most = typeof opts.images === \"number\" ? opts.images : 8\n html = html.replace(/<code[^>]*>[\\s\\S]*?<\\/code>|!\\[([^\\]\\n]*)\\]\\(([^)\\s]+)\\)/g, (m: string, alt?: string, src?: string) => {\n if (alt === undefined || src === undefined) return m\n if (!/^https?:\\/\\/[^\\s]+$/i.test(src)) return alt\n if (pics.length >= most) return `[${alt || src}](${src})`\n pics.push(`<img src=\"${src}\" alt=\"${alt}\" loading=\"lazy\" referrerpolicy=\"no-referrer\">`)\n alts.push(alt)\n return mark + (pics.length - 1) + \"z\"\n })\n }\n\n // Tables\n html = html.replace(/^(\\|.+\\|)\\n(\\|[-| :]+\\|)\\n((?:\\|.+\\|\\n?)*)/gm, (_m, header, _sep, body) => {\n const ths = header.split(\"|\").filter((c: string) => c.trim()).map((c: string) => `<th>${c.trim()}</th>`).join(\"\")\n const rows = body.trim().split(\"\\n\").map((row: string) => {\n const tds = row.split(\"|\").filter((c: string) => c.trim()).map((c: string) => `<td>${c.trim()}</td>`).join(\"\")\n return `<tr>${tds}</tr>`\n }).join(\"\")\n return `<table><thead><tr>${ths}</tr></thead><tbody>${rows}</tbody></table>`\n })\n\n // Headings\n html = html.replace(/^#### (.+)$/gm, '<h4>$1</h4>')\n html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>')\n html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>')\n html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>')\n\n // Bold and italic\n html = html.replace(/\\*\\*(.+?)\\*\\*/g, '<strong>$1</strong>')\n html = html.replace(/\\*(.+?)\\*/g, '<em>$1</em>')\n\n // Wikilinks — support three forms for the [[...]] body:\n // [[Title]] exact article title\n // [[path/to/article]] path without .md (e.g. \"people/alex\")\n // [[path/to/article.md]] full relative path\n // [[Title|custom display text]] optional display override (Obsidian-style)\n html = html.replace(/\\[\\[([^\\]]+)\\]\\]/g, (_m, inner: string) => {\n const [rawTarget, rawDisplay] = inner.split(\"|\", 2)\n const target = rawTarget.trim().replace(/^\\//, \"\")\n const display = (rawDisplay || rawTarget).trim()\n // Without a resolver a wikilink is just words — better than a dead link.\n return opts.wikilink ? opts.wikilink(target, display) : display\n })\n\n // External links\n html = html.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\" target=\"_blank\" rel=\"noopener noreferrer\">$1</a>')\n\n // Blockquotes (consecutive `> ` lines → one <blockquote>)\n html = html.replace(/^(>\\s?.*(?:\\n>\\s?.*)*)/gm, (block: string) => {\n const inner = block.split(\"\\n\").map(l => l.replace(/^>\\s?/, \"\")).join(\"<br>\")\n return `<blockquote>${inner}</blockquote>`\n })\n\n // Task-list items (render as plain text with unicode checkbox)\n html = html.replace(/^[-*] \\[( |x|X)\\] (.+)$/gm, (_m, chk, rest) =>\n `<li class=\"task\">${chk.toLowerCase() === \"x\" ? \"☑\" : \"☐\"} ${rest}</li>`)\n\n // Unordered lists\n html = html.replace(/^[-*] (.+)$/gm, '<li>$1</li>')\n\n // Ordered lists — match lines like \"1. foo\" (number, dot, space)\n html = html.replace(/^\\d+\\. (.+)$/gm, '<li data-ordered=\"1\">$1</li>')\n\n // Wrap consecutive ordered <li>s into <ol>. Keep the data-ordered marker\n // on each <li> inside the <ol> so the subsequent <ul> regex below can\n // correctly skip them via negative lookahead. Marker is stripped once all\n // list-wrapping is done.\n html = html.replace(/(<li data-ordered=\"1\">.*?<\\/li>(?:\\n?<li data-ordered=\"1\">.*?<\\/li>)*)/g, '<ol>$1</ol>')\n\n // Wrap consecutive unordered <li>s — the negative lookahead `(?! data-ordered)`\n // ensures ordered <li>s inside the <ol> above are NOT re-wrapped in <ul>.\n html = html.replace(/((?:<li(?! data-ordered)[^>]*>.*?<\\/li>\\n?)+)/g, '<ul>$1</ul>')\n\n // Clean up the ordered marker now that wrapping is settled.\n html = html.replace(/ data-ordered=\"1\"/g, \"\")\n\n // Horizontal rules\n html = html.replace(/^---$/gm, '<hr>')\n\n // Paragraphs — only wrap non-block lines. A paragraph is a run of\n // text that isn't already wrapped in a block-level tag.\n html = html.replace(/\\n\\n+/g, '</p><p>')\n html = `<p>${html}</p>`\n // Unwrap <p>...</p> that now contain block-level elements.\n html = html.replace(/<p>\\s*(<(?:h[1-6]|ul|ol|blockquote|table|pre|hr)\\b[^>]*>[\\s\\S]*?<\\/(?:h[1-6]|ul|ol|blockquote|table|pre)>)\\s*<\\/p>/g, \"$1\")\n html = html.replace(/<p>\\s*<hr>\\s*<\\/p>/g, \"<hr>\")\n // Drop empty paragraphs that remain.\n html = html.replace(/<p>\\s*<\\/p>/g, \"\")\n\n html = html.replace(/<p>(<(?:h[1-4]|pre|table|ul|hr|div))/g, '$1')\n html = html.replace(/(<\\/(?:h[1-4]|pre|table|ul|hr|div)>)<\\/p>/g, '$1')\n html = html.replace(/<p>\\s*<\\/p>/g, '')\n\n if (pics.length) {\n const at = new RegExp(mark + \"(\\\\d+)z\", \"g\")\n html = html.split(/(<[^>]*>)/).map((part) => part.charAt(0) === \"<\"\n ? part.replace(at, (_m, i) => alts[Number(i)])\n : part.replace(at, (_m, i) => pics[Number(i)])).join(\"\")\n }\n\n return html\n}\n","// Shared small utilities for UI renderers.\n\n/**\n * HTML-escape a string so it's safe to interpolate inside attributes or text\n * content. Every page used to ship its own `esc` / `escapeHtml` / `safe` —\n * this is the canonical one.\n */\nexport function esc(s: unknown): string {\n return String(s ?? \"\").replace(/[&<>\"']/g, (c) => ({\n \"&\": \"&amp;\", \"<\": \"&lt;\", \">\": \"&gt;\", '\"': \"&quot;\", \"'\": \"&#39;\",\n }[c] as string))\n}\n\n/** Join class names, dropping falsy values. */\nexport function cx(...parts: Array<string | false | null | undefined>): string {\n return parts.filter(Boolean).join(\" \")\n}\n"],"mappings":"AAqCA,IAAIA,EAAiC,CAAC,EAE/B,SAASC,EAAkBC,EAAgC,CAChEF,EAAiBE,CACnB,CAEO,SAASC,GAAoC,CAClD,OAAOH,CACT,CA2BO,IAAMI,EAAc;AAAA;AAAA;AAAA;AAAA;AAAA,iRAYdC,EAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAuFbC,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAiMtB,SAASC,EAAYC,EAAmI,CAC7J,IAAMC,EAAQC,GAAgB,OAAOA,GAAM,UAAYA,EAAIA,EAAI,KAC/D,MAAO,CACL,KAAMD,EAAKD,GAAQ,MAAM,EAAE,EAC3B,QAASC,EAAKD,GAAQ,OAAO,EAC7B,OAAQC,EAAKD,GAAQ,MAAM,EAC3B,UAAWC,EAAKD,GAAQ,SAAS,EACjC,UAAWA,GAAQ,OAAO,QAAU,EACtC,CACF,CAIO,IAAMG,EAAa,wCAMnB,SAASC,EAAaC,EAA0B,CACrD,IAAMC,EAAQD,EAAK,OAASA,EAAK,MAAM,OAAS,EAAIA,EAAK,MAAQ,CAAC,CAAE,GAAI,QAAS,KAAM,cAAe,aAAc,GAAI,QAAS,EAAK,CAAC,EACjIE,EAAYF,EAAK,eAAiBC,EAAM,KAAME,GAAMA,EAAE,OAAO,GAAG,IAAMF,EAAM,CAAC,EAAE,GAC/EG,EAAUH,EAAM,KAAME,GAAMA,EAAE,KAAOD,CAAS,GAAKD,EAAM,CAAC,EAE1DI,EAAWJ,EAAM,IAAKE,GAAM,CAChC,IAAMG,EAAYH,EAAE,KAAOD,EACrBK,EAAcJ,EAAE,QAAU,0EAAyE,GACnGK,EAAY,CAAC,CAACL,EAAE,YAAc,CAACA,EAAE,QAGjCM,EAAOD,EACT,IACAL,EAAE,aACA,GAAGA,EAAE,aAAa,QAAQ,OAAQ,EAAE,UACpC,IACAO,EAAWF,EAAY,kBAAkBG,EAAIR,EAAE,EAAE,8BAAgCA,EAAE,QAAU,mDAAqD,GAClJS,EAAOJ,EACT,0FACAL,EAAE,WACA,oBAAoBQ,EAAIR,EAAE,UAAU,UACpCA,EAAE,aACA,oFACA,GACR,MAAO,YAAYQ,EAAIF,CAAI,aAAaH,EAAY,aAAe,MAAMI;AAAA,wDACrBC,EAAIR,EAAE,IAAI,IAAII;AAAA,QAC9DJ,EAAE,aAAe,oBAAoBQ,EAAIR,EAAE,YAAY,UAAY;AAAA,QACnES;AAAA,SAEN,CAAC,EAAE,KAAK,EAAE,EAEJC,EAAe;AAAA;AAAA,yBAEEF,EAAIP,EAAQ,IAAI;AAAA;AAAA,4CAEGC;AAAA,UA8CpCS,EAhB+C,CACnD,CACE,KAAM,OACN,KAAM,CACJ,CAAE,GAAI,OAAQ,MAAO,OAAQ,KAAM,OAAQ,EAC3C,CAAE,GAAI,OAAQ,MAAO,aAAc,KAAM,OAAQ,EACjD,CAAE,GAAI,UAAW,MAAO,UAAW,KAAM,UAAW,EACpD,CAAE,GAAI,YAAa,MAAO,YAAa,KAAM,YAAa,EAC1D,CAAE,GAAI,SAAU,MAAO,SAAU,KAAM,SAAU,EACjD,CAAE,GAAI,WAAY,MAAO,WAAY,KAAM,WAAY,EACvD,CAAE,GAAI,YAAa,MAAO,YAAa,KAAM,YAAa,EAC1D,CAAE,GAAI,QAAS,MAAO,WAAY,KAAM,QAAS,CACnD,CACF,CACF,EAEoB,IAAKC,GAAM,CAC7B,IAAMC,EAAQD,EAAE,KAAK,IAAKE,GAAM,CAC9B,IAAMC,EAAMD,EAAE,KAAOjB,EAAK,UAAY,2BAA6B,iBAC7DmB,EAAWF,EAAE,SAAW,kCAAoC,GAC5DG,EAAWH,EAAE,SAAW,yDAAsD,GACpF,MAAO,YAAYA,EAAE,gBAAgBC,KAAOC,KAAYF,EAAE,QAAQG,OACpE,CAAC,EAAE,KAAK,EAAE,EACV,MAAO,wCAAwCT,EAAII,EAAE,IAAI,gDAAgDJ,EAAII,EAAE,IAAI,WAAWC,SAChI,CAAC,EAAE,KAAK,EAAE,EAqBV,MAnBe;AAAA;AAAA;AAAA;AAAA;AAAA,yCAKwBL,EAAIX,EAAK,QAAQ;AAAA;AAAA,mCAEvBc;AAAA;AAAA;AAAA,MAG7Bd,EAAK,aAAe;AAAA,MACpBF;AAAA,MACAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMKb,EAAK,UAAY,6BAA6BA,EAAK,kBAAoB,IAElF,CAEA,SAASW,EAAIU,EAAmB,CAC9B,OAAO,OAAOA,GAAK,EAAE,EAAE,QAAQ,WAAaC,IAAO,CAAE,IAAK,QAAS,IAAK,OAAQ,IAAK,OAAQ,IAAK,SAAU,IAAK,OAAQ,GAAEA,CAAC,CAAY,CAC1I,CC9dO,SAASC,EAAeC,EAAcC,EAAwB,CAAC,EAAW,CAM/E,IAAIC,EAAO,OAAOF,GAAQ,EAAE,EACzB,QAAQ,KAAM,OAAO,EAAE,QAAQ,KAAM,MAAM,EAAE,QAAQ,KAAM,MAAM,EACjE,QAAQ,KAAM,QAAQ,EAAE,QAAQ,KAAM,OAAO,EAGhDE,EAAOA,EAAK,QAAQ,2BAA4B,CAACC,EAAIC,EAAMC,IACzD,0BAA0BD,MAASC,EAAK,KAAK,gBAAgB,EAG/DH,EAAOA,EAAK,QAAQ,aAAc,iBAAiB,EAOnD,IAAMI,EAAiB,CAAC,EAClBC,EAAiB,CAAC,EAClBC,EAAOP,EAAK,OAAS,QAAU,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,EAAI,IAAM,GACrF,GAAIA,EAAK,OAAQ,CACf,IAAMQ,EAAO,OAAOR,EAAK,QAAW,SAAWA,EAAK,OAAS,EAC7DC,EAAOA,EAAK,QAAQ,4DAA6D,CAACQ,EAAWC,EAAcC,IACrGD,IAAQ,QAAaC,IAAQ,OAAkBF,EAC9C,uBAAuB,KAAKE,CAAG,EAChCN,EAAK,QAAUG,EAAa,IAAIE,GAAOC,MAAQA,MACnDN,EAAK,KAAK,aAAaM,WAAaD,iDAAmD,EACvFJ,EAAK,KAAKI,CAAG,EACNH,GAAQF,EAAK,OAAS,GAAK,KAJYK,CAK/C,EAqFH,GAjFAT,EAAOA,EAAK,QAAQ,+CAAgD,CAACC,EAAIU,EAAQC,EAAMC,IAAS,CAC9F,IAAMC,EAAMH,EAAO,MAAM,GAAG,EAAE,OAAQI,GAAcA,EAAE,KAAK,CAAC,EAAE,IAAKA,GAAc,OAAOA,EAAE,KAAK,QAAQ,EAAE,KAAK,EAAE,EAC1GC,EAAOH,EAAK,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,IAAKI,GAEjC,OADKA,EAAI,MAAM,GAAG,EAAE,OAAQF,GAAcA,EAAE,KAAK,CAAC,EAAE,IAAKA,GAAc,OAAOA,EAAE,KAAK,QAAQ,EAAE,KAAK,EAAE,QAE9G,EAAE,KAAK,EAAE,EACV,MAAO,qBAAqBD,wBAA0BE,mBACxD,CAAC,EAGDhB,EAAOA,EAAK,QAAQ,gBAAiB,aAAa,EAClDA,EAAOA,EAAK,QAAQ,eAAgB,aAAa,EACjDA,EAAOA,EAAK,QAAQ,cAAe,aAAa,EAChDA,EAAOA,EAAK,QAAQ,aAAc,aAAa,EAG/CA,EAAOA,EAAK,QAAQ,iBAAkB,qBAAqB,EAC3DA,EAAOA,EAAK,QAAQ,aAAc,aAAa,EAO/CA,EAAOA,EAAK,QAAQ,oBAAqB,CAACC,EAAIiB,IAAkB,CAC9D,GAAM,CAACC,EAAWC,CAAU,EAAIF,EAAM,MAAM,IAAK,CAAC,EAC5CG,EAASF,EAAU,KAAK,EAAE,QAAQ,MAAO,EAAE,EAC3CG,GAAWF,GAAcD,GAAW,KAAK,EAE/C,OAAOpB,EAAK,SAAWA,EAAK,SAASsB,EAAQC,CAAO,EAAIA,CAC1D,CAAC,EAGDtB,EAAOA,EAAK,QAAQ,2BAA4B,+DAA+D,EAG/GA,EAAOA,EAAK,QAAQ,2BAA6BuB,GAExC,eADOA,EAAM,MAAM;AAAA,CAAI,EAAE,IAAIC,GAAKA,EAAE,QAAQ,QAAS,EAAE,CAAC,EAAE,KAAK,MAAM,gBAE7E,EAGDxB,EAAOA,EAAK,QAAQ,4BAA6B,CAACC,EAAIwB,EAAKC,IACzD,oBAAoBD,EAAI,YAAY,IAAM,IAAM,SAAM,YAAOC,QAAW,EAG1E1B,EAAOA,EAAK,QAAQ,gBAAiB,aAAa,EAGlDA,EAAOA,EAAK,QAAQ,iBAAkB,8BAA8B,EAMpEA,EAAOA,EAAK,QAAQ,0EAA2E,aAAa,EAI5GA,EAAOA,EAAK,QAAQ,iDAAkD,aAAa,EAGnFA,EAAOA,EAAK,QAAQ,qBAAsB,EAAE,EAG5CA,EAAOA,EAAK,QAAQ,UAAW,MAAM,EAIrCA,EAAOA,EAAK,QAAQ,SAAU,SAAS,EACvCA,EAAO,MAAMA,QAEbA,EAAOA,EAAK,QAAQ,sHAAuH,IAAI,EAC/IA,EAAOA,EAAK,QAAQ,sBAAuB,MAAM,EAEjDA,EAAOA,EAAK,QAAQ,eAAgB,EAAE,EAEtCA,EAAOA,EAAK,QAAQ,wCAAyC,IAAI,EACjEA,EAAOA,EAAK,QAAQ,6CAA8C,IAAI,EACtEA,EAAOA,EAAK,QAAQ,eAAgB,EAAE,EAElCI,EAAK,OAAQ,CACf,IAAMuB,EAAK,IAAI,OAAOrB,EAAO,UAAW,GAAG,EAC3CN,EAAOA,EAAK,MAAM,WAAW,EAAE,IAAK4B,GAASA,EAAK,OAAO,CAAC,IAAM,IAC5DA,EAAK,QAAQD,EAAI,CAAC1B,EAAI4B,IAAMxB,EAAK,OAAOwB,CAAC,CAAC,CAAC,EAC3CD,EAAK,QAAQD,EAAI,CAAC1B,EAAI4B,IAAMzB,EAAK,OAAOyB,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAG3D,OAAO7B,CACT,CC5IO,SAAS8B,EAAIC,EAAoB,CACtC,OAAO,OAAOA,GAAK,EAAE,EAAE,QAAQ,WAAaC,IAAO,CACjD,IAAK,QAAS,IAAK,OAAQ,IAAK,OAAQ,IAAK,SAAU,IAAK,OAC9D,GAAEA,CAAC,CAAY,CACjB","names":["topbarFeatures","setTopbarFeatures","features","getTopbarFeatures","TOPBAR_HEAD","TOPBAR_CSS","TOPBAR_SCRIPT","headerBuild","health","text","v","BUILD_PILL","renderTopbar","opts","peers","currentId","p","current","meshMenu","isCurrent","primaryMark","proxyable","href","dataAttr","esc","hint","meshSelector","tabs","g","inner","t","cls","extAttrs","extGlyph","s","c","markdownToHtml","text","opts","html","_m","lang","code","pics","alts","mark","most","m","alt","src","header","_sep","body","ths","c","rows","row","inner","rawTarget","rawDisplay","target","display","block","l","chk","rest","at","part","i","esc","s","c"]}
@@ -1,5 +1,5 @@
1
- import{ja as m,ma as b}from"./chunk-TXX5W3SH.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
1
+ import{ja as m,ma as b}from"./chunk-Y5HBYSJW.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
2
2
 
3
3
  `))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
4
4
  `))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
5
- //# sourceMappingURL=chunk-X7E27RYS.js.map
5
+ //# sourceMappingURL=chunk-C4S5XQKD.js.map
@@ -1,5 +1,5 @@
1
- import{ha as m,ia as $,ma as x}from"./chunk-TXX5W3SH.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
1
+ import{ha as m,ia as $,ma as x}from"./chunk-Y5HBYSJW.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
4
4
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
5
- //# sourceMappingURL=chunk-A6B5JRUG.js.map
5
+ //# sourceMappingURL=chunk-CYKPDILL.js.map
@@ -1,8 +1,8 @@
1
- import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-22LO3GBP.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-A6B5JRUG.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
1
+ import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-YLKCFW2R.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-CYKPDILL.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
2
2
  `)}async function k(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
4
4
  `),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
8
- //# sourceMappingURL=chunk-XG2XVGSL.js.map
8
+ //# sourceMappingURL=chunk-FDCTFT2Q.js.map
@@ -1,2 +1,2 @@
1
- import{y as l,z as f}from"./chunk-74CQWVHE.js";import{a,f as p}from"./chunk-72SZI2UW.js";f();p();var d="task-tier";function u(e){return{task:w(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function w(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function T(e){return e==="voice"||e==="desktop"||e==="opencode"}var k=60*60*1e3;function _(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 y(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(T(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??k;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}export{h as a,T as b,_ as c,y as d};
2
- //# sourceMappingURL=chunk-MEXXGNNN.js.map
1
+ import{y as l,z as f}from"./chunk-A35RTVMM.js";import{a,f as p}from"./chunk-72SZI2UW.js";f();p();var d="task-tier";function u(e){return{task:w(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function w(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function T(e){return e==="voice"||e==="desktop"||e==="opencode"}var k=60*60*1e3;function _(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 y(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(T(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??k;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}export{h as a,T as b,_ as c,y as d};
2
+ //# sourceMappingURL=chunk-HG6QA6EU.js.map
@@ -1,4 +1,4 @@
1
- import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-N7HKIMMR.js";import{C as se}from"./chunk-OZDSQVHU.js";import{a as de,b as le}from"./chunk-DG5I6PPM.js";import{c as ae,e as oe}from"./chunk-LQE73AZR.js";import{e as F,g as ie}from"./chunk-JIT5GPTX.js";import{a as ne,b as re}from"./chunk-A6B5JRUG.js";import{a as te}from"./chunk-DVJW3IWI.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as U,ma as j,w as L,x as Q}from"./chunk-TXX5W3SH.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function W(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
1
+ import{c as ce,d as J,e as E,f as K,g as z}from"./chunk-SCJ5ZXEN.js";import{C as se}from"./chunk-6WNQY6K2.js";import{a as de,b as le}from"./chunk-BGG3ZSMW.js";import{c as ae,e as oe}from"./chunk-LQE73AZR.js";import{e as F,g as ie}from"./chunk-JIT5GPTX.js";import{a as ne,b as re}from"./chunk-CYKPDILL.js";import{a as te}from"./chunk-VQM77L54.js";import{A as De,R as Z,Y as ze,ga as q,ia as ee,ja as U,ma as j,w as L,x as Q}from"./chunk-Y5HBYSJW.js";import{existsSync as M,readFileSync as ve,writeFileSync as be,appendFileSync as Oe,mkdirSync as Be}from"fs";import{dirname as He,resolve as P}from"path";import{fileURLToPath as Le}from"url";import{hostname as qe}from"os";import{spawn as je}from"child_process";j();import{existsSync as ge,readFileSync as pe,writeFileSync as Y,copyFileSync as Me}from"fs";import{resolve as me}from"path";function W(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(!ge(n))throw new Error(`agentx.json not found at ${n}`);let r=JSON.parse(pe(n,"utf-8")),a=e(r),o=typeof a=="string"?{summary:a}:a,s=JSON.stringify(r,null,2)+`
2
2
  `,l=n+".tmp";Y(l,s,"utf-8");try{JSON.parse(pe(l,"utf-8"))}catch(c){throw new Error(`config did not round-trip cleanly: ${c.message}`)}let i;return t.skipBackup||(i=`${n}.bak.${Date.now()}`,Me(n,i)),Y(n,s,"utf-8"),t.skipReload||Ne().catch(()=>{}),{summary:o.summary,payload:o.payload,backupPath:i}}function ue(e,t={}){let n=t.configPath||me(process.cwd(),"agentx.json");if(ge(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return Y(n,JSON.stringify(e,null,2)+`
3
3
  `,"utf-8"),{file:n}}async function Ne(){try{let t=U().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function fe(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",r=`<header class="ax-topbar">
4
4
  <div class="ax-topbar__left">
@@ -742,4 +742,4 @@ tr:hover td { background: var(--bg-hover); }
742
742
  WHERE person = ? AND state IN (${n.map(()=>"?").join(",")})
743
743
  ${r}`).all(t,...n,...a).map(s=>({id:s.id,state:s.state,channel:s.channel,agentId:s.agent_id,text:s.text,createdAt:s.created_at})):[]}function pn(e,t){return Ae(e,t,L,"ORDER BY created_at")}function gn(e,t,n=50){return Ae(e,t,[...L,...Q],"ORDER BY created_at DESC, rowid DESC LIMIT ?",Math.max(1,Math.min(n,500)))}ze();var V="member:",gt=90,mt="members",ut="tailscale-user-login",ft=400,ht=60*60*1e3;function vt(e){let t=e.scopes.find(n=>n.startsWith(V));return t?t.slice(V.length):null}function Ie(e,t){if(!e)return null;let n=t.verify(e),r=n?vt(n):null;return n&&r?{rec:n,personId:r}:null}function xn(e,t){let n=e.people().find(l=>l.id===t);if(!n)return{ok:!1,error:`No person "${t}". Add them first: agentx people add ${t} --name "\u2026"`};let{token:r,record:a}=e.tokens.create({name:`${n.name} (machine not paired yet)`,scopes:[`${V}${n.id}`],expiresInDays:gt}),{code:o,expiresAt:s}=e.codes.create({token:r,tokenId:a.id,name:n.id});return e.members.log({person:n.id,device:a.id,event:"invited"}),{ok:!0,code:o,expiresAt:s,tokenId:a.id,person:n}}var bt=Math.round(ae/6e4);function xt(e){return e==="client"?"Your project":"My work"}function yn(e){let t=xt(e.person.role),n=e.person.role==="client"?`I use AgentX to keep track of the work I do for you. It has a page for you, "${t}": what you asked us for, and where each request stands.`:`I use AgentX to give our AI agents their jobs. It has a page for you, "${t}": what you asked the agents for, and where each request stands.`;return[`Hi ${e.person.name},`,"",n,"","To open it:","1. Accept the Tailscale share I sent you. Tailscale is a small program that connects your computer to mine, privately.",`2. Open ${e.origin.replace(/\/+$/,"")}/member in Edge or Chrome, give your computer a name and type this code: ${oe(e.code)}`,` The code works once, for ${bt} minutes. If it has stopped working, tell me and I will send you a new one.`,"","I then approve your machine, and the page opens by itself."].join(`
744
744
  `)}var yt="The private network says someone else is connecting from this machine. Ask the person who invited you for a new code.",kt="Too many machines are waiting for the owner's answer. Try again later.",Se="That code didn't work. Check it, or ask the person who invited you for a new one.",Ee=(e,t)=>{let n=e.headers[t];return(Array.isArray(n)?n[0]:n||"").trim()};function Te(e){let t=e.socket?.remoteAddress||"";return t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1"}function wt(e){if(!Te(e))return null;let t=Ee(e,ut).toLowerCase();return t?t.slice(0,80):null}function $t(e){let t=e.socket?.remoteAddress||"unknown";if(!Te(e))return t;let n=Ee(e,"x-forwarded-for").split(",").pop().trim();return/^[0-9a-fA-F:.]{2,45}$/.test(n)?n:t}function At(e){return typeof e=="string"?e.replace(/[^\p{L}\p{N} ._'()-]/gu," ").replace(/\s+/g," ").trim().slice(0,60):""}function St(e){return e.identities.map(Z).filter(t=>!!t&&t.channel==="tailscale").map(t=>t.value)}async function kn(e,t){let n=Date.now(),r=t.now??Date.now,a=t.log??(m=>console.log(m)),o=$t(e),s=t.limiter.retryAfter(o);if(s>0)return a(`[member] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let l=null,i="";try{let m=await se(e,2048);l=m.code,i=At(m.machine)}catch{}let c=t.codes.redeem(l),g=c?Ie(c.token,t.tokens):null;if(await Et(n,t.minMs??ft),!c||!g)return t.limiter.fail(o),a(`[member] pair-code failed from ${o}`),{status:401,body:{error:Se}};t.limiter.succeed(o);let{rec:f,personId:d}=g,h=t.people().find(m=>m.id===d);if(!h)return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:"person no longer listed"}),a(`[member] pair-code for ${d} refused from ${o}: person no longer listed`),{status:403,body:{error:Se}};let u=wt(e),A=St(h);if(A.length&&(!u||!A.includes(u)))return t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:`network login ${u??"missing"}; expected ${A.join(" or ")}`}),a(`[member] ${d}: pairing from ${o} refused: the network says "${u??"nobody"}", expected ${A.join(" or ")}`),{status:403,body:{error:yt}};let x=i||"Unnamed machine",y=h.name.slice(0,40),v=ie(t.root,{title:`New machine for ${y}`,ask:`From ${o}, ${u?`network login ${u}`:"no network login reported"}. Machine name, as typed there: "${x}". Let it see ${y}'s own work?`,recommend:`Yes if ${y} told you they just paired this machine. No if you did not expect it.`,if_silent:"discard",raised_by:mt},{now:r()});return v.ok?(t.members.add({tokenId:f.id,personId:d,name:x,state:"pending",cardId:v.card.id,address:o,...u?{network:u}:{},createdAt:new Date(r()).toISOString()}),t.members.log({person:d,device:f.id,event:"paired",address:o,detail:x}),a(`[member] ${d} paired "${x}" from ${o}; waiting for the owner (card ${v.card.id})`),{status:200,body:{person:d,name:x,state:"pending"},token:c.token}):(t.tokens.revoke(f.id),t.members.log({person:d,device:f.id,event:"refused",address:o,detail:v.error}),a(`[member] ${d}: pairing from ${o} refused: ${v.error}`),{status:503,body:{error:kt}})}var H="this machine is not paired",It="waiting for the owner to approve this machine";function Ce(e){return e?e.status==="decided"?e.verdict??null:e.status==="expired"?"no":null:null}function wn(e,t){return t.state==="pending"&&t.cardId?Ce(F(e,t.cardId)):null}function $n(e,t,n){let r=t.now??Date.now,a=t.log??(g=>console.log(g)),o=Ie(e,t.tokens);if(!o)return{ok:!1,status:401,error:H};let{rec:s,personId:l}=o,i=t.members.byToken(s.id);if(!i||i.state==="removed"||i.personId!==l)return{ok:!1,status:401,error:H};if(t.people&&!t.people().some(g=>g.id===l))return Re(t,s.id,"person no longer listed"),a(`[member] ${l}: "${i.name}" ended: person no longer listed`),{ok:!1,status:401,error:H};if(i.state==="pending"){let g=i.cardId?F(t.root,i.cardId):null,f=Ce(g);if(f==="yes")i=t.members.update(s.id,{state:"active",approvedAt:new Date(r()).toISOString()})??i,t.members.log({person:l,device:s.id,event:"approved",detail:g?.decided_by}),a(`[member] ${l}: "${i.name}" approved`);else if(f==="no"){let d=g?.status==="expired"?"the owner did not answer in time":"the owner said no";return t.tokens.revoke(s.id),t.members.update(s.id,{state:"removed",removedAt:new Date(r()).toISOString(),removedReason:d}),t.members.log({person:l,device:s.id,event:"refused",detail:d}),a(`[member] ${l}: "${i.name}" refused: ${d}`),{ok:!1,status:401,error:H}}else return{ok:!1,status:403,error:It,waiting:!0}}let c=i.lastSeenAt?Date.parse(i.lastSeenAt):0;return n&&(r()-c>=ht||i.lastAddress!==n)&&(i=t.members.update(s.id,{lastSeenAt:new Date(r()).toISOString(),lastAddress:n})??i,t.members.log({person:l,device:s.id,event:"signed-in",address:n})),{ok:!0,device:i,personId:l,rec:s}}function Re(e,t,n="removed by the owner"){let r=e.members.byToken(t);if(!r)return null;e.tokens.revoke(t);let a=e.members.update(t,{state:"removed",removedAt:new Date((e.now??Date.now)()).toISOString(),removedReason:n});return e.members.log({person:r.personId,device:t,event:"removed",detail:n}),a}function An(e,t){return e.members.devices(t).filter(n=>n.state!=="removed").map(n=>Re(e,n.tokenId,"person removed by the owner")).filter(n=>!!n)}async function Et(e,t){let n=e+t-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}var Pe=["gitlab","github"];function Tt(e,t,n){let r=String(t||"").trim().toLowerCase();if(!Pe.includes(r))throw new Error(`Request status works on ${Pe.join(" and ")}, not on "${t}".`);e.requestStatus=e.requestStatus&&typeof e.requestStatus=="object"?e.requestStatus:{};let a=Array.isArray(e.requestStatus.channels)?e.requestStatus.channels.map(o=>String(o).toLowerCase()):[];return e.requestStatus.channels=n?[...new Set([...a,r])]:a.filter(o=>o!==r),`request status on ${r} is ${n?"on":"off"}`}function En(e){return Array.isArray(e?.requestStatus?.channels)?e.requestStatus.channels.map(t=>String(t).toLowerCase()):[]}function Tn(e){let{summary:t}=W(n=>Tt(n,e?.channel,!!e?.enabled));return{summary:t}}var Ct="https://ntfy.sh";function Rn(e){return{enabled:!!e?.enabled,server:e?.server||Ct,topicSet:!!e?.topic,tokenSet:!!e?.token}}function Pn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let r=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(r))throw new Error("ntfy server must be an http(s) URL");n.server=r}if("topic"in t){let r=String(t.topic).trim();if(!r)throw new Error("ntfy topic cannot be empty");n.topic=r}if("token"in t){let r=String(t.token??"").trim();r?n.token=r:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{W as a,xe as b,jt as c,Ft as d,Jt as e,Vt as f,Qt as g,Zt as h,cn as i,pn as j,gn as k,gt as l,xn as m,bt as n,xt as o,yn as p,$t as q,kn as r,wn as s,$n as t,Re as u,An as v,Pe as w,Tt as x,En as y,Tn as z,Rn as A,Pn as B,lt as C,sn as D};
745
- //# sourceMappingURL=chunk-6FJ44HYY.js.map
745
+ //# sourceMappingURL=chunk-HPY54DU6.js.map
@@ -1,6 +1,6 @@
1
- import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{v as R,y as E,z as W}from"./chunk-74CQWVHE.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-2PJKGZWP.js";V();var be="wiki-rerank",xe=30,se=900;function Se(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Ne(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function ke(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as _,renameSync as oe,statSync as Q}from"fs";import{resolve as P,dirname as X}from"path";import{createHash as ae}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),_(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
1
+ import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{v as R,y as E,z as W}from"./chunk-A35RTVMM.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-2PJKGZWP.js";V();var be="wiki-rerank",xe=30,se=900;function Se(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Ne(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function ke(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as _,renameSync as oe,statSync as Q}from"fs";import{resolve as P,dirname as X}from"path";import{createHash as ae}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),_(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
2
2
  `,n=this.classificationsPath();return S(n)||_(X(n),{recursive:!0}),ie(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
3
3
  `).filter(Boolean),n=new Map;for(let o of r)try{let i=$.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
4
4
  `).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=$.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[ce(e.text),e.channel??""].join("");return ae("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=U.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function Y(a,e){_(X(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;M(t,JSON.stringify(e,null,2)),oe(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of G)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of G)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function ce(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}re();te();W();import{createHash as ve}from"crypto";V();W();var A="intent-path",de=.5,le=.3,pe=.45;function ge(a){return{message:me(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function Z(a,e){let t={};for(let r of a)t[r.id]=fe(r);return C(t,e)}function ue(a){return{category:Z(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function he(a){return{verb:Z(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function D(a,e,t={}){if(R(A)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await E(A,n,ue(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=de,b=[c.choice],g=e.filter(m=>m.parentId===c.choice);if(g.length>=2){let m=t.incumbent?.[0]===c.choice,d=await E(A,{...n,category:c.choice},he(g),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=le,(f.pMax>=pe||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else g.length===1&&b.push(g[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function fe(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function me(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=J(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:q(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},g=new Set(o.map(u=>u.id)),m=s.map((u,p)=>g.has(u)?-1:p).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=m.length===0,p=m.length===1&&m[0]===s.length-1;d=u||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:q(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(A),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await D(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&D(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
5
5
  `),i=await this.callProvider(o),s=B(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=ee(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??ee(d);if(!v)continue;let u={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(u[p]=y);!u.name&&d!==v&&(u.name=d.trim()),b[v]=u}let g={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(g.input=s.leaf.input),typeof s.leaf.output=="string"&&(g.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:g}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function ee(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ve("sha1").update(a.join("")).digest("hex").slice(0,16)}function q(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function ye(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{be as a,xe as b,Se as c,Ne as d,ke as e,x as f,F as g,L as h,q as i,ye as j};
6
- //# sourceMappingURL=chunk-JBE4H7PL.js.map
6
+ //# sourceMappingURL=chunk-ILGLEA3I.js.map
@@ -1,4 +1,4 @@
1
- import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-4QCYSKPD.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{y as Ce,z as hn}from"./chunk-74CQWVHE.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{f as ie,n as gn}from"./chunk-UIBUZ2N3.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(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){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(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(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
1
+ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-VGI4EZTP.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{y as Ce,z as hn}from"./chunk-A35RTVMM.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{f as ie,n as gn}from"./chunk-UIBUZ2N3.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(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){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(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(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
2
2
  `)}var ft=200,Pn=7,gt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=U(e,".agentx/memory"),this.ledger=new Ke(U(e,".agentx/wiki")),pt(this.memoryDir)||$n(this.memoryDir,{recursive:!0})}filePath(e){return U(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||oe(t.content))return!1;let n=t.source.trust??_e(t.source.channel),i=t.review??Le(n),o={...t,source:{...t.source,trust:n},...i?{review:i}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Rn(this.filePath(e),JSON.stringify(o)+`
3
3
  `),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!pt(t))return[];try{let{mtimeMs:n,size:i}=xn(t),o=this.parsedCache.get(t);if(o&&o.mtimeMs===n&&o.size===i)return o.facts.slice();let a=ut(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:n,size:i,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,n=8){let i=this.getAll(t).filter(ae);if(i.length===0)return[];let o=i.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=U(this.memoryDir,`${t}_bm25_cache.json`),a=je(o,s),d=We(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=i.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 i.slice(-n);let f=p.sort((g,h)=>h.score-g.score).slice(0,n).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return lt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return ct(e,t)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),i=new Set(t),o=!1;for(let s of n)if(i.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(),o=!0}o&&le(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
@@ -25,4 +25,4 @@ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7
25
25
  `).filter(Boolean),i=[];for(let o=n.length-1;o>=0&&i.length<t;o--)try{let s=JSON.parse(n[o]);(!e||s.person===e)&&i.push(s)}catch{}return i}load(){if(Oe(this.file))try{let e=JSON.parse(Ne(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Gt(Qt(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${en(4).toString("hex")}.tmp`;Zt(t,JSON.stringify(e,null,2)+`
26
26
  `,{encoding:"utf-8",mode:384}),Vt(t,this.file)}};import{extname as ui}from"path";var nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,rn=/<agentx-artifact>[\s\S]*$/i;function Ps(r,e=1/0,t=!1){let n=[],i=String(r??"");if(!/<agentx-artifact>/i.test(i))return{text:i,artifacts:n};let o=i.replace(nn,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&n.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";n.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?o.replace(rn,""):o).trim(),artifacts:n}}function Ts(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let i=t.replace(nn,(o,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?i.replace(rn,""):i).trim()}return n.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(i,o,s)=>o===void 0||s===void 0?i:`[${o||s}](${s})`)}var pi={".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"}},Os={bytes:20*1024*1024,perMessage:20,pathChars:512};function Ns(r){return pi[ui(r).toLowerCase()]??null}var fi=["[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 ![what it shows](https://...)."].join(`
27
27
  `);function Ds(r,e,t){return r==="app"&&e&&t!==!1?fi:void 0}import{lstatSync as Ee,mkdirSync as gi,readdirSync as mi,realpathSync as De,unlinkSync as hi}from"fs";import{join as ne,resolve as on}from"path";var sn=".agentx/outbox",yi=7*24*60*60*1e3;function wi(r,e){try{let t=De(on(e,r)),n=ne(t,sn);return De(n)===n&&Ee(n).isDirectory()?n:null}catch{return null}}function js(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let i=De(on(t,r));Ee(ne(i,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||gi(ne(i,sn),{recursive:!0})}catch{return 0}let n=wi(r,t);return n?an(n,(e.now??Date.now())-(e.maxAgeMs??yi)):0}function an(r,e){let t=0;for(let n of mi(r)){let i=ne(r,n);try{let o=Ee(i);o.isDirectory()?t+=an(i,e):Math.max(o.mtimeMs,o.ctimeMs)<e&&(hi(i),t++)}catch{}}return t}export{st as a,gt as b,mt as c,Fi as d,Nn as e,Wi as f,$ as g,pe as h,v as i,B as j,Bn as k,he as l,we as m,be as n,xe as o,Hr as p,qr as q,Te as r,ar as s,ai as t,tn as u,Ps as v,Ts as w,Os as x,Ns as y,Ds as z,sn as A,js as B};
28
- //# sourceMappingURL=chunk-THRWE4Y3.js.map
28
+ //# sourceMappingURL=chunk-J3GXZQXY.js.map