agentix-cli 0.212.0 → 0.213.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-WS5BTNNP.js → App-5CLRBC3C.js} +2 -2
- package/dist/{ChatApp-DRMZZ3RJ.js → ChatApp-LDNQVD2C.js} +2 -2
- package/dist/{absorb-eval-IZOPUQE7.js → absorb-eval-JWQPGUJS.js} +2 -2
- package/dist/{adapter-3JMPFQ25.js → adapter-AOKK2LFM.js} +2 -2
- package/dist/{agent-YA2EBSW4.js → agent-6VEMBVRN.js} +2 -2
- package/dist/{board-dashboard-KFEVHD3Z.js → board-dashboard-LDMIS7MM.js} +4 -4
- package/dist/{chunk-4FL6B3B7.js → chunk-2V43GUET.js} +106 -105
- package/dist/chunk-2V43GUET.js.map +1 -0
- package/dist/{chunk-EJXHHFZJ.js → chunk-4W5KRZTT.js} +2 -2
- package/dist/{chunk-MVDB76JV.js → chunk-6PBYRK7J.js} +2 -2
- package/dist/{chunk-ZD2DD7I2.js → chunk-BERSMN6Y.js} +2 -2
- package/dist/{chunk-5E6JVFHV.js → chunk-BU6V75KD.js} +2 -2
- package/dist/{chunk-UZEH2A2F.js → chunk-CUCIMPFI.js} +2 -2
- package/dist/{chunk-DD4YKQGF.js → chunk-D3FIIEDR.js} +2 -2
- package/dist/{chunk-XUOFCIAE.js → chunk-D6H4DH32.js} +2 -2
- package/dist/{chunk-6LOXNAZD.js → chunk-DGCYMSXU.js} +2 -2
- package/dist/{chunk-BITJXYHB.js → chunk-DNPPPUDP.js} +2 -2
- package/dist/{chunk-27DVJFFR.js → chunk-DPA3IOMU.js} +2 -2
- package/dist/{chunk-EGKAE6VD.js → chunk-DSUL5L3T.js} +2 -2
- package/dist/{chunk-PJHJFZJ4.js → chunk-DYH6KS3X.js} +270 -270
- package/dist/chunk-DYH6KS3X.js.map +1 -0
- package/dist/{chunk-SYEC2RCV.js → chunk-EE5RZDQE.js} +2 -2
- package/dist/{chunk-KUB5F67E.js → chunk-ERKK22QV.js} +2 -2
- package/dist/{chunk-ETDYJ52Z.js → chunk-FCF47R4W.js} +3 -3
- package/dist/{chunk-RFMBLJN3.js → chunk-G3GFE3GK.js} +2 -2
- package/dist/{chunk-W7D2N55Y.js → chunk-I722PWJE.js} +2 -2
- package/dist/{chunk-QDZWSALI.js → chunk-IXV3BPUZ.js} +2 -2
- package/dist/{chunk-2PYRRBLW.js → chunk-KU3ZF3WO.js} +2 -2
- package/dist/{chunk-6UVU47FA.js → chunk-MOATCFT5.js} +2 -2
- package/dist/{chunk-6KAP6IHP.js → chunk-N7IX77SL.js} +2 -2
- package/dist/chunk-NERO7F3J.js +115 -0
- package/dist/chunk-NERO7F3J.js.map +1 -0
- package/dist/{chunk-YXGYLWD5.js → chunk-NWE3B245.js} +2 -2
- package/dist/{chunk-VZFFEGVQ.js → chunk-O4WFPH6H.js} +2 -2
- package/dist/{chunk-X5UWEMFI.js → chunk-UWDDVDU6.js} +2 -2
- package/dist/{chunk-X5UWEMFI.js.map → chunk-UWDDVDU6.js.map} +1 -1
- package/dist/{chunk-DZ3Z3ZAK.js → chunk-VKLTCUD7.js} +2 -2
- package/dist/{chunk-OHZ2ETAY.js → chunk-WKBGQGVL.js} +2 -2
- package/dist/{chunk-UODNQNDK.js → chunk-XBFXSSHA.js} +2 -2
- package/dist/{chunk-PAOXBAYJ.js → chunk-Z6N7POAU.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-NSZL7HQZ.js → client-2TFSAO3Y.js} +2 -2
- package/dist/{config-LE57YRFQ.js → config-LTXRWDRK.js} +2 -2
- package/dist/{config-mutate-XWOE7TCY.js → config-mutate-UFVJUJQO.js} +2 -2
- package/dist/{config-mutator-RZB5O7ES.js → config-mutator-RRKU33OL.js} +2 -2
- package/dist/{contributions-REWGLEPA.js → contributions-5XUEOSLT.js} +2 -2
- package/dist/{doctor-JNQHNUSO.js → doctor-L675OBBF.js} +2 -2
- package/dist/{follow-up-tool-WJ5MHV3O.js → follow-up-tool-2OEZMPPQ.js} +2 -2
- package/dist/{hub-LWUTWLBA.js → hub-VJZYQXKB.js} +2 -2
- package/dist/index.d.ts +262 -208
- package/dist/index.js +1 -1
- package/dist/{org-tool-R6U5LUUB.js → org-tool-QBLKCMY3.js} +2 -2
- package/dist/{program-OT7WYMVD.js → program-3QOBRNT4.js} +27 -27
- package/dist/{promote-DYDETYJ4.js → promote-Z6KL6GOL.js} +2 -2
- package/dist/{query-JF3BQNUR.js → query-SZA6UMHA.js} +2 -2
- package/dist/{query-settings-2FPH2NQ7.js → query-settings-BALRO5J4.js} +2 -2
- package/dist/{registry-FX4C6RHG.js → registry-J3Y3DDFT.js} +2 -2
- package/dist/{request-planner-NKP7YFUN.js → request-planner-Y5HG5DQ4.js} +2 -2
- package/dist/{review-candidates-YL7QGFP2.js → review-candidates-BZJOFMFO.js} +2 -2
- package/dist/{routing-KW42OGIW.js → routing-3JDN3Z6L.js} +2 -2
- package/dist/schedule-tool-VM5OJ7XB.js +2 -0
- package/dist/{scheduler-LYSUXKAB.js → scheduler-JJOO2ODF.js} +2 -2
- package/dist/{seat-HCXOUS5H.js → seat-5FTOWN5J.js} +2 -2
- package/dist/{select-KTQNUTOG.js → select-BRQQP7OP.js} +2 -2
- package/dist/{set-enabled-PAQ7ZXFL.js → set-enabled-EZLQFASM.js} +2 -2
- package/dist/{sprint-tool-YGOAJSZQ.js → sprint-tool-YJ4WT3AD.js} +2 -2
- package/dist/{tool-7FFPIOO5.js → tool-BFKCGAD6.js} +2 -2
- package/dist/{tool-IJIYPMOA.js → tool-CXJHLIHJ.js} +2 -2
- package/dist/{tool-OWGDFDVG.js → tool-MT5YQ7F3.js} +2 -2
- package/dist/{tool-UNSJJ4MO.js → tool-RCEOKPES.js} +2 -2
- package/dist/{wiki-PYWKCJ2Y.js → wiki-F3LZSBN3.js} +2 -2
- package/dist/wiki-enrich-KIONW7SB.js +2 -0
- package/dist/workspace-setup-PIPGUMLG.js +2 -0
- package/package.json +1 -1
- package/dist/chunk-3AHYZLGE.js +0 -115
- package/dist/chunk-3AHYZLGE.js.map +0 -1
- package/dist/chunk-4FL6B3B7.js.map +0 -1
- package/dist/chunk-PJHJFZJ4.js.map +0 -1
- package/dist/schedule-tool-B3PPRW6J.js +0 -2
- package/dist/wiki-enrich-JFVS7NYY.js +0 -2
- package/dist/workspace-setup-GTSXWYU4.js +0 -2
- /package/dist/{App-WS5BTNNP.js.map → App-5CLRBC3C.js.map} +0 -0
- /package/dist/{ChatApp-DRMZZ3RJ.js.map → ChatApp-LDNQVD2C.js.map} +0 -0
- /package/dist/{absorb-eval-IZOPUQE7.js.map → absorb-eval-JWQPGUJS.js.map} +0 -0
- /package/dist/{adapter-3JMPFQ25.js.map → adapter-AOKK2LFM.js.map} +0 -0
- /package/dist/{agent-YA2EBSW4.js.map → agent-6VEMBVRN.js.map} +0 -0
- /package/dist/{board-dashboard-KFEVHD3Z.js.map → board-dashboard-LDMIS7MM.js.map} +0 -0
- /package/dist/{chunk-EJXHHFZJ.js.map → chunk-4W5KRZTT.js.map} +0 -0
- /package/dist/{chunk-MVDB76JV.js.map → chunk-6PBYRK7J.js.map} +0 -0
- /package/dist/{chunk-ZD2DD7I2.js.map → chunk-BERSMN6Y.js.map} +0 -0
- /package/dist/{chunk-5E6JVFHV.js.map → chunk-BU6V75KD.js.map} +0 -0
- /package/dist/{chunk-UZEH2A2F.js.map → chunk-CUCIMPFI.js.map} +0 -0
- /package/dist/{chunk-DD4YKQGF.js.map → chunk-D3FIIEDR.js.map} +0 -0
- /package/dist/{chunk-XUOFCIAE.js.map → chunk-D6H4DH32.js.map} +0 -0
- /package/dist/{chunk-6LOXNAZD.js.map → chunk-DGCYMSXU.js.map} +0 -0
- /package/dist/{chunk-BITJXYHB.js.map → chunk-DNPPPUDP.js.map} +0 -0
- /package/dist/{chunk-27DVJFFR.js.map → chunk-DPA3IOMU.js.map} +0 -0
- /package/dist/{chunk-EGKAE6VD.js.map → chunk-DSUL5L3T.js.map} +0 -0
- /package/dist/{chunk-SYEC2RCV.js.map → chunk-EE5RZDQE.js.map} +0 -0
- /package/dist/{chunk-KUB5F67E.js.map → chunk-ERKK22QV.js.map} +0 -0
- /package/dist/{chunk-ETDYJ52Z.js.map → chunk-FCF47R4W.js.map} +0 -0
- /package/dist/{chunk-RFMBLJN3.js.map → chunk-G3GFE3GK.js.map} +0 -0
- /package/dist/{chunk-W7D2N55Y.js.map → chunk-I722PWJE.js.map} +0 -0
- /package/dist/{chunk-QDZWSALI.js.map → chunk-IXV3BPUZ.js.map} +0 -0
- /package/dist/{chunk-2PYRRBLW.js.map → chunk-KU3ZF3WO.js.map} +0 -0
- /package/dist/{chunk-6UVU47FA.js.map → chunk-MOATCFT5.js.map} +0 -0
- /package/dist/{chunk-6KAP6IHP.js.map → chunk-N7IX77SL.js.map} +0 -0
- /package/dist/{chunk-YXGYLWD5.js.map → chunk-NWE3B245.js.map} +0 -0
- /package/dist/{chunk-VZFFEGVQ.js.map → chunk-O4WFPH6H.js.map} +0 -0
- /package/dist/{chunk-DZ3Z3ZAK.js.map → chunk-VKLTCUD7.js.map} +0 -0
- /package/dist/{chunk-OHZ2ETAY.js.map → chunk-WKBGQGVL.js.map} +0 -0
- /package/dist/{chunk-UODNQNDK.js.map → chunk-XBFXSSHA.js.map} +0 -0
- /package/dist/{chunk-PAOXBAYJ.js.map → chunk-Z6N7POAU.js.map} +0 -0
- /package/dist/{client-NSZL7HQZ.js.map → client-2TFSAO3Y.js.map} +0 -0
- /package/dist/{config-LE57YRFQ.js.map → config-LTXRWDRK.js.map} +0 -0
- /package/dist/{config-mutate-XWOE7TCY.js.map → config-mutate-UFVJUJQO.js.map} +0 -0
- /package/dist/{config-mutator-RZB5O7ES.js.map → config-mutator-RRKU33OL.js.map} +0 -0
- /package/dist/{contributions-REWGLEPA.js.map → contributions-5XUEOSLT.js.map} +0 -0
- /package/dist/{doctor-JNQHNUSO.js.map → doctor-L675OBBF.js.map} +0 -0
- /package/dist/{follow-up-tool-WJ5MHV3O.js.map → follow-up-tool-2OEZMPPQ.js.map} +0 -0
- /package/dist/{hub-LWUTWLBA.js.map → hub-VJZYQXKB.js.map} +0 -0
- /package/dist/{org-tool-R6U5LUUB.js.map → org-tool-QBLKCMY3.js.map} +0 -0
- /package/dist/{program-OT7WYMVD.js.map → program-3QOBRNT4.js.map} +0 -0
- /package/dist/{promote-DYDETYJ4.js.map → promote-Z6KL6GOL.js.map} +0 -0
- /package/dist/{query-JF3BQNUR.js.map → query-SZA6UMHA.js.map} +0 -0
- /package/dist/{query-settings-2FPH2NQ7.js.map → query-settings-BALRO5J4.js.map} +0 -0
- /package/dist/{registry-FX4C6RHG.js.map → registry-J3Y3DDFT.js.map} +0 -0
- /package/dist/{request-planner-NKP7YFUN.js.map → request-planner-Y5HG5DQ4.js.map} +0 -0
- /package/dist/{review-candidates-YL7QGFP2.js.map → review-candidates-BZJOFMFO.js.map} +0 -0
- /package/dist/{routing-KW42OGIW.js.map → routing-3JDN3Z6L.js.map} +0 -0
- /package/dist/{schedule-tool-B3PPRW6J.js.map → schedule-tool-VM5OJ7XB.js.map} +0 -0
- /package/dist/{scheduler-LYSUXKAB.js.map → scheduler-JJOO2ODF.js.map} +0 -0
- /package/dist/{seat-HCXOUS5H.js.map → seat-5FTOWN5J.js.map} +0 -0
- /package/dist/{select-KTQNUTOG.js.map → select-BRQQP7OP.js.map} +0 -0
- /package/dist/{set-enabled-PAQ7ZXFL.js.map → set-enabled-EZLQFASM.js.map} +0 -0
- /package/dist/{sprint-tool-YGOAJSZQ.js.map → sprint-tool-YJ4WT3AD.js.map} +0 -0
- /package/dist/{tool-7FFPIOO5.js.map → tool-BFKCGAD6.js.map} +0 -0
- /package/dist/{tool-IJIYPMOA.js.map → tool-CXJHLIHJ.js.map} +0 -0
- /package/dist/{tool-OWGDFDVG.js.map → tool-MT5YQ7F3.js.map} +0 -0
- /package/dist/{tool-UNSJJ4MO.js.map → tool-RCEOKPES.js.map} +0 -0
- /package/dist/{wiki-PYWKCJ2Y.js.map → wiki-F3LZSBN3.js.map} +0 -0
- /package/dist/{wiki-enrich-JFVS7NYY.js.map → wiki-enrich-KIONW7SB.js.map} +0 -0
- /package/dist/{workspace-setup-GTSXWYU4.js.map → workspace-setup-PIPGUMLG.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-XL7UWG36.js";import{Aa as I,Fa as Je,pa as ne,qa as re,sa as oe,ta as ie}from"./chunk-
|
|
1
|
+
import{a as E}from"./chunk-IMLAPB7G.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{n as x}from"./chunk-XL7UWG36.js";import{Aa as I,Fa as Je,pa as ne,qa as re,sa as oe,ta as ie}from"./chunk-UWDDVDU6.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
3
|
<plist version="1.0"><dict>
|
|
4
4
|
<key>Label</key><string>${t(e.label??X)}</string>
|
|
@@ -35,4 +35,4 @@ function run(argv) {
|
|
|
35
35
|
`),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
|
|
36
36
|
`),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
|
|
37
37
|
`),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
|
|
38
|
-
//# sourceMappingURL=chunk-
|
|
38
|
+
//# sourceMappingURL=chunk-EE5RZDQE.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as W,c as K}from"./chunk-
|
|
1
|
+
import{b as W,c as K}from"./chunk-G3GFE3GK.js";import{h as z,j as Z}from"./chunk-3UOTLMXD.js";import{a as I,b as V}from"./chunk-FCPTN6NF.js";import{a as H,b as De}from"./chunk-7I7IEX4S.js";import{d as Y}from"./chunk-QIJLFPWE.js";import{execFile as tt}from"child_process";import{writeFileSync as Ee,mkdirSync as P,existsSync as D,readFileSync as nt}from"fs";import{resolve as _}from"path";var Ne=["off","shadow","authoritative"],xe={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},Se="INTENT_LEDGER_MODE";function q(n,e=process.env){let t=Q(e[xe[n]]);if(t)return t;let r=Q(e[Se]);return r||"off"}function Q(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return Ne.includes(e)?e:null}V();import we from"better-sqlite3";import{existsSync as ut,mkdirSync as $e}from"fs";import{dirname as Oe,resolve as Le}from"path";var T=class{db;path;constructor(e={}){this.path=Le(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),$e(Oe(this.path),{recursive:!0}),this.db=new we(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ce(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let r=this.findEventBySourceId(e.source,e.sourceEventId);if(r)return r}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
|
|
2
2
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let r=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
3
3
|
FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return r?j(r):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
4
4
|
FROM intent_events WHERE id = ?`).get(e);return t?j(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
|
|
@@ -142,4 +142,4 @@ ${k(O(ye(c.block,F(o.brief,i.prompt)),i.report),i.expectExitZero)}`,i.maxOutputT
|
|
|
142
142
|
`);return t.length<=e?t.join(`
|
|
143
143
|
`):t.slice(-e).join(`
|
|
144
144
|
`)}function st(n,e,t){return new Promise((r,i)=>{tt("/bin/sh",["-c",n],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(o,s,a)=>{if(o&&o.killed){i(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}r({stdout:String(s??""),stderr:String(a??""),code:o?typeof o.code=="number"?o.code:1:0})})})}export{T as a,te as b,St as c,wt as d,Ye as e,$t as f,Ot as g,w as h,de as i,q as j,pt as k,re as l,se as m,At as n,et as o,it as p,Ie as q,Te as r,Re as s,B as t,U as u};
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
145
|
+
//# sourceMappingURL=chunk-ERKK22QV.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-
|
|
1
|
+
import{a as _,b as F,c as K,d as z,e as J}from"./chunk-JTFCU5LH.js";import{a as H}from"./chunk-LUOW2YHY.js";import{a as j,b as I,c as Y,d as V,e as B,j as G}from"./chunk-I722PWJE.js";import{b as E,c as L}from"./chunk-AHWWJ7AF.js";import{y as N,z as ot}from"./chunk-IXV3BPUZ.js";import{h as Q}from"./chunk-QUFIUXMQ.js";import{readFileSync as lt,existsSync as X}from"fs";ot();import{resolve as R}from"path";import{execSync as ct}from"child_process";var ht="haiku",dt="sonnet",pt=.8;function mt(e,r,o,t){if(t.size===0)return 0;let c=e.listArticles(r||"").map(l=>l.path).filter(l=>!l.includes("/_versions/"));return c.length===0&&(c=o.sharedPool.map(l=>l.path)),c.length===0?0:c.filter(l=>t.has(l)).length/c.length}async function _t(e,r,o,t={}){let c=t.selectorModel??ht,l=t.synthModel??dt,m=t.maxCandidates??3,g=t.maxHops??2,d=t.maxArticles??8,i=t.timeoutMs??6e4,s=t.log??console.error.bind(console,"[wiki-query]"),h=t.messagePath?.length?t.messagePath:void 0,n=t.graphWeight??W,a=R(r.baseDir,"_index.md"),p=tt(r,o,t.shared),b=t.method??"catalog";if(b!=="catalog"){let u=z(r,t.shared);if(b==="summaries"||mt(r,o,p,u)>=pt){let f=t.summaries??K,P=t.notes&&o&&t.notes.owner===o?F(t.notes):void 0,y=await J(e,P?gt(p,P):p,P?new Map([...u,...P.summaries]):u,{...f,navigatorModel:t.selectorModel??f.navigatorModel,answerModel:t.synthModel??f.answerModel},{call:t.call??H,fetch:t.fetch,timeoutMs:i,log:s}),$=y.picked.map(w=>({title:w.meta.title,path:w.path,type:_(w.path)?"note":w.meta.type,hop:w.hop}));return{answer:y.answer,citations:y.status==="ok"?$.map(({hop:w,...v})=>v):[],candidates:$.filter(w=>w.hop===0).map(({title:w,path:v})=>({title:w,path:v})),walked:$,status:y.status,method:"summaries",basis:y.basis,live:y.live,liveAsked:y.liveAsked,trace:y.trace,...y.error?{error:y.error}:{}}}}if(!X(a)&&p.sharedPool.length===0)return M("no-catalog",e,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let it=(X(a)?lt(a,"utf-8"):"")+yt(e,p.sharedPool,h,n),T=Date.now(),A=[],S="";try{let u=await nt(e,p.pool,o,m,h,n);u?(A=u,S=`[wiki-rerank seat] ${u.map(f=>f.title).join(" | ")}`):(S=await Z(wt(e,it,m,h),c,i),A=bt(S))}catch(u){return s("selector failed:",u?.message),{...M("error",e,`Selector: ${u?.message||"unknown"}`),trace:{selectorMs:Date.now()-T,synthesisMs:0,selectorOutput:S}}}let x=Date.now()-T;if(A.length===0)return{...M("no-candidates",e,"Selector returned no candidates."),trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let C=rt(A,p,g,d);if(C.length===0)return{...M("no-candidates",e,"Candidates did not resolve to readable articles."),candidates:A,trace:{selectorMs:x,synthesisMs:0,selectorOutput:S}};let D=Date.now(),U="";try{U=await Z(kt(e,C),l,i*2)}catch(u){return s("synthesis failed:",u?.message),{...M("error",e,`Synthesis: ${u?.message||"unknown"}`),candidates:A,walked:C.map(f=>({title:f.meta.title,path:f.path,type:f.meta.type,hop:f.hop??0})),trace:{selectorMs:x,synthesisMs:Date.now()-D,selectorOutput:S}}}let st=Date.now()-D;return{answer:U.trim(),citations:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type})),candidates:A,walked:C.map(u=>({title:u.meta.title,path:u.path,type:u.meta.type,hop:u.hop??0})),status:"ok",trace:{selectorMs:x,synthesisMs:st,selectorOutput:S}}}async function Rt(e,r,o,t={}){let c=t.maxCandidates??3,l=t.graphWeight??W,m=t.messagePath?.length?t.messagePath:void 0,g=t.pool??q(r);if(g.length===0||!e.trim())return[];let d=await nt(e,g,o,c,m,l,t.stage??"retrieve");if(!d){let i=new Set(L(e,E(g.map(at))).map(s=>s.docIndex));d=O(e,g,m,l).filter(s=>i.has(s)).slice(0,c).map(s=>({title:g[s].title,path:g[s].path}))}return d.length===0?[]:rt(d,tt(r,o),t.maxHops??1,t.maxArticles??6)}function q(e){try{return(e.rebuildIndex().articles??[]).filter(r=>r.path&&!r.path.includes("/_versions/"))}catch{return[]}}function M(e,r,o){return{answer:"",citations:[],candidates:[],walked:[],status:e,error:o}}function tt(e,r,o=[]){let t=new Map,c=[];for(let i of e.listArticles(r||""))t.set(i.meta.title.toLowerCase(),i.path),c.push({path:i.path,related:i.meta.related??[],lastUpdated:i.meta.lastUpdated??""});let l=[],m=new Map;for(let i of o)if(i.store.baseDir!==e.baseDir){m.set(i.id,i);for(let s of i.store.listArticles(r||"")){if(s.path.includes("/_versions/")||i.skip?.(s.path))continue;let h=`@${i.id}/${s.path}`;l.push(ut(s,h)),c.push({path:h,related:s.meta.related??[],lastUpdated:s.meta.lastUpdated??""});let n=s.meta.title.toLowerCase();t.has(n)||t.set(n,h)}}let g=new Map;if(m.size>0)for(let i of[...c].sort((s,h)=>h.lastUpdated.localeCompare(s.lastUpdated)))for(let s of i.related){let h=s.toLowerCase(),n=g.get(h)??[];n.includes(i.path)||n.push(i.path),g.set(h,n)}let d;return{backlinks:g,readable:new Set(c.map(i=>i.path)),get pool(){return d??=[...q(e),...l]},sharedPool:l,titleIndex:t,read(i){let s=i.match(/^@([^/]+)\/(.+)$/),h=s?m.get(s[1]):void 0;if(s&&!h)return null;let n=h?.store??e,a=s?s[2]:i,p=r?n.readArticleAs(a,r):n.readArticle(a);return p?{...p,path:i}:null},links(i){let s=(i.meta.related??[]).map(a=>t.get(a.toLowerCase())).filter(a=>!!a),h=[i.meta.title,...i.meta.aliases??[]].map(a=>a.toLowerCase()),n=[...new Set(h.flatMap(a=>g.get(a)??[]))].filter(a=>a!==i.path).slice(0,et);return[...new Set([...s,...n])].filter(a=>a!==i.path)}}}function gt(e,r){return{...e,pool:[...e.pool,...r.pool],readable:new Set([...e.readable,...r.pool.map(o=>o.path)]),read:o=>_(o)?r.read(o):e.read(o)}}function ut(e,r){return{path:r,title:e.meta.title,type:e.meta.type,related:e.meta.related,tags:e.meta.tags||[],owner:e.meta.owner,access:e.meta.access,sharedWith:e.meta.sharedWith,aliases:[e.meta.title.toLowerCase(),...(e.meta.aliases??[]).map(o=>o.toLowerCase())],backlinks:0,sources:e.meta.sources,lastUpdated:e.meta.lastUpdated,graphPath:e.meta.graphPath}}var ft=150;function yt(e,r,o,t){return r.length===0?"":`
|
|
2
2
|
|
|
3
3
|
## Shared wiki (other agents' articles)
|
|
4
4
|
|
|
@@ -51,5 +51,5 @@ ${o}
|
|
|
51
51
|
|
|
52
52
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. When two articles disagree, prefer the one updated more recently, and say which agent's page and date the answer comes from. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
53
53
|
|
|
54
|
-
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-
|
|
55
|
-
//# sourceMappingURL=chunk-
|
|
54
|
+
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function bt(e){let r=e.match(/\[[\s\S]*?\]/);if(!r)return[];try{let o=JSON.parse(r[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Z(e,r,o){let{writeFileSync:t,mkdirSync:c,rmSync:l}=await import("fs"),{tmpdir:m}=await import("os"),g=R(m(),`agentx-wiki-query-${process.pid}`);c(g,{recursive:!0});let d=R(g,`prompt-${Date.now()}.txt`);t(d,e);try{let i=`cat '${d}' | claude -p - --output-format json --max-turns 1 --model ${r} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,s=ct(i,{env:Q(),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let h=JSON.parse(s);return String(h.result||h.content||"")}catch{return s}}finally{try{l(d,{force:!0})}catch{}}}async function Ot(e){try{let{loadDaemonConfig:r}=await import("./config-LTXRWDRK.js");return r(e).wiki.query.shared}catch{return!0}}export{ht as a,dt as b,pt as c,_t as d,Rt as e,q as f,ft as g,W as h,O as i,Ot as j};
|
|
55
|
+
//# sourceMappingURL=chunk-FCF47R4W.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{Ob as b,Pb as k,Sb as x,_b as S}from"./chunk-
|
|
1
|
+
import{Ob as b,Pb as k,Sb as x,_b as S}from"./chunk-UWDDVDU6.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(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 N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
|
|
4
4
|
${m.map(f=>` ${f}`).join(`
|
|
5
5
|
`)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
|
|
6
6
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(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 A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(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{O as a,N as b,A as c,F as d,U as e};
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
7
|
+
//# sourceMappingURL=chunk-G3GFE3GK.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-QDZWSALI.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(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 ie(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)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{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 _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(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=T.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{_(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{_(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=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(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=j.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=j.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),X(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 u=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){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;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,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, 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 g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}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=E.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 T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-IXV3BPUZ.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-DCIYOPJF.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(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 ie(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)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{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 _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(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=T.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{_(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{_(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=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(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=j.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=j.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),X(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 u=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){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;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,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, 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 g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}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=E.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)||D(Z(n),{recursive:!0}),oe(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=E.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=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.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=G.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=Y.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 X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)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 de(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)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(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 q(a,e,t={}){if(R(P)==="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 O(P,n,he(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>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{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>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(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 ve(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=z(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:J(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)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||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(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(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&&q(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=W(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=te(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)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.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:u}}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 te(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 ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(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 we(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{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-I722PWJE.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 ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Zb as tt,_b as nt}from"./chunk-
|
|
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 ne,b as et}from"./chunk-FCPTN6NF.js";import{a as Te,b as ht}from"./chunk-MCI3DIWW.js";import{o as we,p as Ze}from"./chunk-DCIYOPJF.js";import{Zb as tt,_b as nt}from"./chunk-UWDDVDU6.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-
|
|
114
|
+
//# sourceMappingURL=chunk-IXV3BPUZ.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-
|
|
1
|
+
import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-CUCIMPFI.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-G3GFE3GK.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(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 j(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&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
|
|
2
2
|
`)}async function L(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(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function ae(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,p;try{p=Y(t.configPath)}catch(a){return`Error: ${a.message}`}let h=p.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(h).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>ee(i,f,d)).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(!p.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),I=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=_(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!p.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||R;if(!b(g))return`Error: unknown timezone "${g}".`;let u=o||q(i.matched,f);if(!B(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(h[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=j(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let y=s(n.report);if(y&&y!=="always"&&y!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let G={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},H=k({parsed:i,agent:f,prompt:l,timezone:g,notify:$,report:y,enabled:!1,createdBy:e.agentId,approval:G}),N=await I(F=>E(F,`crons.${u}`,H));if(!N.success)return`Error: ${N.error}`;let T=S(w(i.cron,g,d),g),U=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${T}`,`Agent: ${f}`,$?`${y==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),X=await L(p,t,U);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${T}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=h[o];if(!c)return`Error: schedule "${o}" not found.`;if(!K(p,c,e))return Q(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&m(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 I(i=>E(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(m(c)&&c.approval.requestedBy===e.agentId){let u=await I($=>D($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(m(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:d.toISOString()},l=await I(u=>{if(!P(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);E(u,`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: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?S(w(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await L(p,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 ie(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)),d=s(r?e.AGENTX_CHANNEL:n.channel),p=s(r?e.AGENTX_CHAT_ID:n.chatId),h=s(n.accountId);return{agentId:t,channel:d,chatId:p,...h?{accountId:h}:{}}}export{ae as a,ie as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-KU3ZF3WO.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-
|
|
1
|
+
import t from"chalk";import{spawn as S}from"child_process";import{resolve as j}from"path";var E=l=>l||j(process.cwd(),".agentx/wiki");function N(l){return async d=>{let{claudeCliEnv:e}=await import("./workspace-env-UOK5MMKD.js"),h=["-p","-","--output-format","json","--max-turns","1","--model",l,"--tools","","--strict-mcp-config","--mcp-config",'{"mcpServers":{}}',"--settings",'{"disableAllHooks":true}',"--setting-sources","","--no-session-persistence"],y=await new Promise(($,a)=>{let s=S("claude",h,{env:e(),stdio:["pipe","pipe","pipe"]}),p="",g="",i=setTimeout(()=>s.kill("SIGTERM"),24e4);s.stdout.on("data",r=>{p+=r}),s.stderr.on("data",r=>{g+=r}),s.on("error",r=>{clearTimeout(i),a(r)}),s.on("close",r=>{clearTimeout(i),r===0?$(p):a(new Error(`claude exited ${r}: ${g.trim().slice(0,200)}`))}),s.stdin.end(d)}),c=JSON.parse(y);if(c.is_error)throw new Error(`model error: ${String(c.result).slice(0,200)}`);return{text:String(c.result??""),costUsd:Number(c.total_cost_usd)||0}}}function I(l){l.command("enrich [entities...]").description("write a full overview, sourced typed facts and linked history on entity pages (person, organization, project, place, assets)").option("--dir <path>","wiki directory (default .agentx/wiki)").option("--types <list>","comma-separated entity types","person,organization,project,place,device,server,app,domain,account").option("--max <n>","most entities per run","10").option("--max-cost <usd>","stop before the next call once the run spent this much","1").option("--model <m>","model","sonnet").option("--force","redo entities whose sources did not change").option("--dry-run","show what would be written, write nothing").option("--create <title>","first create a page for a thing other pages only name, then enrich it (needs --as and --owner)").option("--as <type>","type of the page --create makes, e.g. organization").option("--owner <agent>","agent whose wiki gets the page --create makes").option("--json","print the run as JSON").action(async(d,e)=>{let{WikiHub:h}=await import("./hub-VJZYQXKB.js"),{GraphCache:y}=await import("./graph-ZVKV3JBD.js"),{loadOntology:c}=await import("./load-Q3HCFXDT.js"),{loadRoster:$}=await import("./roster-BZGKG2ZA.js"),{ENRICH_TYPES:a,loadEnrichState:s,runEnrich:p,saveEnrichState:g}=await import("./enrich-MZMIQ3SV.js"),i=E(e.dir),r=e.types.split(",").map(o=>o.trim()).filter(Boolean),b=r.filter(o=>!a.includes(o));if(b.length){console.error(t.red(` not an entity type this job handles: ${b.join(", ")} (use ${a.join(", ")})`)),process.exitCode=1;return}let x=Number(e.max);if(!Number.isInteger(x)||x<1){console.error(t.red(" --max must be a whole number of entities, 1 or more")),process.exitCode=1;return}let w=Number(e.maxCost);if(!Number.isFinite(w)||w<=0){console.error(t.red(" --max-cost must be a positive number of dollars")),process.exitCode=1;return}let m=new h(i,()=>{});if(e.create){let{createEntityPage:o}=await import("./enrich-MZMIQ3SV.js");if(!e.as||!a.includes(e.as)||!e.owner){console.error(t.red(` --create needs --as <${a.join("|")}> and --owner <agent>`)),process.exitCode=1;return}if(m.syncedFrom(e.owner)){console.error(t.red(` ${e.owner}'s pages are copied from another node; pick an agent that runs here`)),process.exitCode=1;return}if(e.dryRun)console.log(t.dim(` --dry-run: would create "${e.create}" (${e.as}) in ${e.owner}'s wiki`));else{let f=o(m,e.create,e.as,e.owner,new Date().toISOString().slice(0,10));console.log(f?t.green(` created ${e.owner}/${f}`):t.dim(` ${e.owner} already has a page titled "${e.create}"`))}d=[...d,e.create],r.includes(e.as)||r.push(e.as)}let{ontology:v}=c(i),k=new y().get(m,v,$(i,m.listAgents([]),v.agent_names)),C=s(i),u=await p(m,k,N(e.model),{types:r,only:d,max:x,maxCostUsd:w,dryRun:!!e.dryRun,force:!!e.force,today:new Date().toISOString().slice(0,10),save:o=>g(i,o)},C);if(e.json){console.log(JSON.stringify(u,null,2));return}for(let o of u.outcomes){let f=o.status==="written"?t.green("\u2713"):o.status==="dry-run"?t.cyan("~"):t.yellow("\xB7");console.log(` ${f} ${o.title} ${t.dim(`${o.status} \xB7 ${o.page??"no page"} \xB7 overview ${o.overview?"yes":"no"} \xB7 ${o.statements} facts \xB7 ${o.links} links \xB7 $${o.costUsd.toFixed(3)}`)}`);for(let n of o.facts??[])console.log(t.dim(` fact: ${n.property} \u2192 ${n.value}${n.role?` (${n.role})`:""} \xB7 source ${n.source}`));for(let n of o.dropped.slice(0,6))console.log(t.dim(` dropped: ${n}`));o.preview&&console.log(t.dim(o.preview.split(`
|
|
2
2
|
`).slice(0,12).map(n=>` | ${n}`).join(`
|
|
3
3
|
`)))}u.outcomes.length===0&&console.log(t.dim(" nothing to do: no entity of these types changed since the last run (--force redoes them)")),console.log(t.dim(` spent $${u.costUsd.toFixed(3)} of $${w}${u.capped?" \xB7 stopped at the cap":""}`))})}export{N as a,I as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-MOATCFT5.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-IH65GDJR.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-
|
|
1
|
+
import{a as fe}from"./chunk-7AB3QUGH.js";import{b as Ue}from"./chunk-AFRHKA7B.js";import{b as Bt,c as Kt}from"./chunk-IH65GDJR.js";import{b as Et,f as jt,g as Ct,j as Lt,l as Ut,m as Ht,s as qt}from"./chunk-ERKK22QV.js";import{a as Ft}from"./chunk-GV7S5BAX.js";import{c as _t}from"./chunk-SZDACK6O.js";import{b as Ot,d as Dt,e as Mt}from"./chunk-5ONH4ITT.js";import{e as Tt,g as Wt,h as Nt,i as Le}from"./chunk-JRAG37V5.js";import{a as Rt,b as Ce,d as Fe,e as xt,f as _e}from"./chunk-BERWTVG2.js";import{a as ne,b as Pt}from"./chunk-A7JSRDJL.js";import{c as vt,d as $t}from"./chunk-AHWWJ7AF.js";import{y as At,z as $r}from"./chunk-IXV3BPUZ.js";import{b as St,f as vr}from"./chunk-72SZI2UW.js";import{Fa as Ir,ta as je}from"./chunk-UWDDVDU6.js";import{j as Ee,r as br}from"./chunk-N47Y5ADQ.js";import{existsSync as Sr,mkdirSync as Jt,readFileSync as Ar,writeFileSync as Rr,renameSync as xr}from"fs";import{resolve as zt,dirname as Pr}from"path";var Yt=class{filePath;log;constructor(e={}){let t=e.baseDir??zt(process.cwd(),".agentx");this.filePath=zt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Jt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!Sr(this.filePath))return{version:1,overrides:{}};try{let e=Ar(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){Jt(Pr(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Rr(t,JSON.stringify(e,null,2)),xr(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Xt,writeFileSync as He,appendFileSync as Or,mkdirSync as Dr,existsSync as en,statSync as Mr}from"fs";import{resolve as ge}from"path";var Gt="[Agent Memory \u2014 persistent facts from past conversations]",Tr=2400;function Vt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Wr(n,e=Date.now()){let t=Dt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Vt(t,Tt(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Nr(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId;if(ne(n.content))return{line:`- [${n.category}] ${Pt}${n.content} (${r}, ${n.source.date})`,unverified:!0};let o=Nt(n,e);return{line:`- [${n.category}] ${Vt(o,Wt(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Qt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Gt.length,a=!1;for(let i of n){let d=e.length>0?Mt(i.content,e):null,u,c,p=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(o.has(d.id))continue;o.add(d.id),u=Wr(d,t),c=d.id}else u=Nr(i,t),d&&(u.line+=` [differs from wiki ${d.id}]`);let f=u.unverified&&!a?Le.length:0;if(s+f+u.line.length>Tr)break;r.push({fact:i,...u,...c?{wikiRef:c}:{}}),s+=f+u.line.length,f&&(a=!0)}return r}function Zt(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Le]:[];return[Gt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var tn=200,Er=7,nn=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ge(e,".agentx/memory"),this.ledger=new Ot(ge(e,".agentx/wiki")),en(this.memoryDir)||Dr(this.memoryDir,{recursive:!0})}filePath(e){return ge(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||Ce(t.content)||ne(t.content))return!1;let r=t.source.trust??Rt(t.source.channel),o=t.review??xt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Or(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!en(t))return[];try{let{mtimeMs:r,size:o}=Mr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Xt(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(_e);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ge(this.memoryDir,`${t}_bm25_cache.json`),i=$t(s,a),d=vt(e,i),u=new Map(d.map(g=>[g.docIndex,g.score])),p=o.map((g,m)=>{let y=u.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(p.length===0)return o.slice(-r);let f=p.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Zt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Qt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&He(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -39,4 +39,4 @@ ${n.text}`}async function Pe(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
39
39
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(wt(this.file))try{let e=JSON.parse(yt(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){nr(sr(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${ar(4).toString("hex")}.tmp`;or(t,JSON.stringify(e,null,2)+`
|
|
40
40
|
`,{encoding:"utf-8",mode:384}),rr(t,this.file)}};import{extname as li}from"path";var ur=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,lr=/<agentx-artifact>[\s\S]*$/i;function zu(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(ur,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let u=d.mime,c=u.startsWith("image/")?"image":u==="application/pdf"?"pdf":u.startsWith("text/")?"text":"file";r.push({type:c,filename:d.filename,mime:u})}}catch{}return""});return{text:(t?s.replace(lr,""):s).trim(),artifacts:r}}function Yu(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(ur,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(lr,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ci={".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"}},Gu={bytes:20*1024*1024,perMessage:20,pathChars:512};function Vu(n){return ci[li(n).toLowerCase()]??null}var pi=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
41
41
|
`);function Qu(n,e,t){return n==="app"&&e&&t!==!1?pi:void 0}import{lstatSync as bt,mkdirSync as fi,readdirSync as gi,realpathSync as kt,unlinkSync as mi}from"fs";import{join as De,resolve as cr}from"path";var pr=".agentx/outbox",hi=7*24*60*60*1e3;function wi(n,e){try{let t=kt(cr(e,n)),r=De(t,pr);return kt(r)===r&&bt(r).isDirectory()?r:null}catch{return null}}function tl(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=kt(cr(t,n));bt(De(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||fi(De(o,pr),{recursive:!0})}catch{return 0}let r=wi(n,t);return r?fr(r,(e.now??Date.now())-(e.maxAgeMs??hi)):0}function fr(n,e){let t=0;for(let r of gi(n)){let o=De(n,r);try{let s=bt(o);s.isDirectory()?t+=fr(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(mi(o),t++)}catch{}}return t}export{Yt as a,nn as b,rn as c,Ei as d,Fr as e,ji as f,Lr as g,_i as h,Li as i,Ui as j,Hi as k,Bi as l,Ki as m,qi as n,Br as o,Ji as p,zi as q,Qi as r,Je as s,Qr as t,Zi as u,Xi as v,Zr as w,ea as x,cn as y,ra as z,oa as A,fn as B,gn as C,ro as D,ua as E,la as F,fa as G,ga as H,x as I,re as J,S as K,Ye as L,bo as M,Qe as N,U as O,et as P,nt as Q,ft as R,Ts as S,Es as T,mt as U,Lo as V,Gs as W,mu as X,hu as Y,wu as Z,yu as _,ku as $,Qs as aa,Zs as ba,bu as ca,Iu as da,vu as ea,$u as fa,Ru as ga,xu as ha,Pu as ia,Tu as ja,Wu as ka,Nu as la,Ou as ma,Du as na,Mu as oa,Eu as pa,ju as qa,oi as ra,Cu as sa,Fu as ta,_u as ua,Lu as va,dr as wa,zu as xa,Yu as ya,Gu as za,Vu as Aa,Qu as Ba,pr as Ca,tl as Da};
|
|
42
|
-
//# sourceMappingURL=chunk-
|
|
42
|
+
//# sourceMappingURL=chunk-N7IX77SL.js.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import{q as j,r as R,t as F}from"./chunk-XL7UWG36.js";import{f as L,g as G}from"./chunk-LY4G7PCW.js";import{existsSync as y,mkdirSync as ae,writeFileSync as S,readFileSync as A}from"fs";import{resolve as m}from"path";import{createHash as Ye}from"crypto";import{readFileSync as me,existsSync as fe,unlinkSync as ye,readdirSync as mt}from"fs";import{resolve as H}from"path";function yt(e,n){let r={},s=t=>{let o=H(e,t);if(fe(o))try{return me(o,"utf-8").trim()||void 0}catch{return}};if(n){let t=s(`SOUL.${n}.md`);t?(r.soul=t,r.soulProfile=n):r.soul=s("SOUL.md")}else r.soul=s("SOUL.md");if(r.identity=s("IDENTITY.md"),r.user=s("USER.md"),r.agents=s("AGENTS.md"),r.bootstrap=s("BOOTSTRAP.md"),r.bootstrap)try{ye(H(e,"BOOTSTRAP.md"))}catch{}return r}function bt(e){let n=[];return e.identity&&n.push(`[Identity]
|
|
2
|
+
${e.identity}`),e.soul&&n.push(`[Personality & Boundaries]
|
|
3
|
+
${e.soul}`),e.user&&n.push(`[User Profile]
|
|
4
|
+
${e.user}`),e.bootstrap&&n.push(`[First-Run Instructions \u2014 one time only]
|
|
5
|
+
${e.bootstrap}`),n.length===0?"":n.join(`
|
|
6
|
+
|
|
7
|
+
`)}function W(e){return`# ${e.name}
|
|
8
|
+
|
|
9
|
+
> Agent ID: \`${e.id}\` | Tier: ${e.tier||"claude-code"}
|
|
10
|
+
|
|
11
|
+
## Role
|
|
12
|
+
|
|
13
|
+
${e.role||"AI agent managed by AgentX orchestrator."}
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
This workspace is managed by AgentX. The agent runs via:
|
|
18
|
+
\`\`\`bash
|
|
19
|
+
# Direct execution
|
|
20
|
+
agentx daemon send ${e.id} "your task here"
|
|
21
|
+
|
|
22
|
+
# Or via any connected channel (Telegram, WhatsApp, GitLab)
|
|
23
|
+
\`\`\`
|
|
24
|
+
|
|
25
|
+
## Code Style
|
|
26
|
+
|
|
27
|
+
- Follow existing patterns in the codebase
|
|
28
|
+
- Use the language and framework conventions already present
|
|
29
|
+
- Keep changes minimal and focused
|
|
30
|
+
|
|
31
|
+
## Testing
|
|
32
|
+
|
|
33
|
+
Run tests before committing:
|
|
34
|
+
\`\`\`bash
|
|
35
|
+
npm test # or the project's test command
|
|
36
|
+
\`\`\`
|
|
37
|
+
|
|
38
|
+
## PR Guidelines
|
|
39
|
+
|
|
40
|
+
- One logical change per commit
|
|
41
|
+
- Reference issue numbers when applicable
|
|
42
|
+
- Keep PR descriptions concise
|
|
43
|
+
|
|
44
|
+
## AgentX Integration
|
|
45
|
+
|
|
46
|
+
This agent is part of an AgentX mesh. It can:
|
|
47
|
+
- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)
|
|
48
|
+
- Respond to GitLab @mentions on issues and MRs
|
|
49
|
+
- Delegate to other agents by mentioning their handles
|
|
50
|
+
- Send cross-channel messages via the /send API
|
|
51
|
+
- Access its wiki knowledge base for context
|
|
52
|
+
`}function kt(e){let n=e.match(/\/soul\s+(\w+)/i);return n?n[1].toLowerCase():/\/soul\s*$/i.test(e)?"default":null}import{execFile as be}from"child_process";import{existsSync as q}from"fs";import{resolve as ke}from"path";var K=["mcp__codegraph__codegraph_search","mcp__codegraph__codegraph_context","mcp__codegraph__codegraph_callers","mcp__codegraph__codegraph_callees","mcp__codegraph__codegraph_impact","mcp__codegraph__codegraph_node","mcp__codegraph__codegraph_status","mcp__codegraph__codegraph_files"],J={command:"codegraph",args:["serve","--mcp"]};function Y(){return["## CodeGraph","","This workspace has CodeGraph initialized \u2014 a semantic code-knowledge-graph indexed via tree-sitter. Use it instead of grep/find/Read for exploration.","","**ALWAYS spawn an Explore subagent for `codegraph_explore` / `codegraph_context`** \u2014 those tools return large source sections that would otherwise bloat the main session. Include this in the Explore prompt:","","> Use `codegraph_explore` as your PRIMARY tool \u2014 one call returns full source from all relevant files. Do not re-Read files codegraph_explore already returned. Fall back to grep/glob/Read only if codegraph returned no results.","","**In the main session, use these lightweight codegraph tools directly:**","","| Tool | Use for |","|---|---|","| `codegraph_search` | Find symbols by name across the codebase |","| `codegraph_callers` / `codegraph_callees` | Trace call flow |","| `codegraph_impact` | Check what's affected before editing a symbol |","| `codegraph_node` | Get a single symbol's details |","| `codegraph_files` | Indexed file structure (faster than ls) |","| `codegraph_status` | Index health |",""].join(`
|
|
53
|
+
`)}function St(e){let n=e.mcp??{};return!e.codegraph||n.codegraph?n:{...n,codegraph:{command:J.command,args:[...J.args]}}}var xe=".codegraph",we=10*60*1e3,X=2;function $e(e){let n=Date.now();return new Promise((r,s)=>{be("codegraph",["init","--index","--quiet",e],{timeout:we,maxBuffer:4*1024*1024},t=>{t?s(t):r(Date.now()-n)})})}async function At(e,n=console.error){let r=[];for(let[o,i]of Object.entries(e))i.codegraph&&(i.tier!=="claude-code"&&i.tier!=="codex-cli"||q(i.workspace)&&(q(ke(i.workspace,xe))||r.push({agentId:o,workspace:i.workspace})));if(r.length===0)return;n(`codegraph: indexing ${r.length} workspace(s) in background (max ${X} parallel)`);let s=0,t=[];for(let o=0;o<Math.min(X,r.length);o++)t.push((async()=>{for(;;){let i=s++;if(i>=r.length)return;let{agentId:a,workspace:l}=r[i];try{let u=await $e(l);n(` codegraph: indexed ${a} in ${(u/1e3).toFixed(1)}s`)}catch(u){let h=u?.code==="ENOENT"?" (codegraph CLI not on PATH; install with `npm i -g @colbymchenry/codegraph`)":"";n(` codegraph: ${a} index failed: ${u?.message??u}${h}`)}}})());await Promise.allSettled(t)}import{appendFileSync as _e,existsSync as z,mkdirSync as Z,readdirSync as Q,realpathSync as Se,statSync as Ae,unlinkSync as Oe,utimesSync as Re,writeFileSync as Te}from"fs";import{createHash as ee}from"crypto";import{resolve as $,sep as Pe}from"path";var D="/observation/pack";function Et(e=process.cwd()){return $(e,".agentx/observations")}function te(e,n){return $(e,encodeURIComponent(n).replace(/\./g,"%2E"))}function ne(e){return e==="bypassPermissions"}function V(e){try{return Se(e)}catch{return $(e)}}function Ee(e,n){return n.some(r=>{try{return new RegExp(`^(?:${r})$`).test(e)}catch{return r===e}})}var ve=2e3;function T(e,n,r){return e.subarray(n,r).toString("utf-8").replace(/^�+|�+$/g,"")}function De(e,n,r){let s=Buffer.from(e,"utf-8"),t=T(s,0,r.headBytes),o=r.tailBytes>0?T(s,s.length-r.tailBytes,s.length):"",i=s.length-r.headBytes-r.tailBytes,a=e.split(`
|
|
54
|
+
`).length,u=s.length/a>ve?"Its lines are very long, so read it by byte range (for example head -c or tail -c, or jq for JSON) for the part you need.":"Read that file with offset and limit (line numbers), or grep it, for the part you need. Do not cat it whole: that is packed again.";return[`[ObservationPack: this result is ${s.length} bytes (${a} lines). Only its first ${r.headBytes} and last ${r.tailBytes} bytes are shown.`,`The exact original is saved at ${n}`,`${u} Do not guess at what is not shown.]`,t,`[... ${i} bytes not shown ...]`,o].join(`
|
|
55
|
+
`)}function Ce(e){let n=e;return!!n&&typeof n=="object"&&n.type==="text"&&typeof n.file?.content=="string"}function v(e){if(e==="")return 0;let n=1;for(let r=e.indexOf(`
|
|
56
|
+
`);r!==-1;r=e.indexOf(`
|
|
57
|
+
`,r+1))n++;return e.endsWith(`
|
|
58
|
+
`)&&n--,n}function Ue(e,n,r){let s=Buffer.from(e,"utf-8"),t=v(e),o=T(s,0,r.headBytes),i=o.lastIndexOf(`
|
|
59
|
+
`);o=i===-1?o:o.slice(0,i+1);let a=r.tailBytes>0?T(s,s.length-r.tailBytes,s.length):"",l=a.indexOf(`
|
|
60
|
+
`);a=l===-1?a:a.slice(l+1);let u=i===-1?0:v(o),h=l===-1?0:v(a),c=n.startLine,p=c+t-1,g=c+u,d=p-h,f=s.length-Buffer.byteLength(o,"utf-8")-Buffer.byteLength(a,"utf-8"),x=typeof n.totalLines=="number"&&n.totalLines>t?` (${n.totalLines} lines in all)`:"",O=g===d?`Line ${g} (${f} bytes) is`:`Lines ${g} to ${d} (${f} bytes) are`,w=[u===0&&o!==""?c:null,h===0&&a!==""?p:null].filter(E=>E!==null),he=w.length===0?"":w.length===1||w[0]===w[1]?` (line ${w[0]} only in part)`:` (lines ${w[0]} and ${w[1]} only in part)`,ge=h>0?` Lines ${d+1} to ${p} follow; the numbers beside them are not the file's.`:"";return[o,`[ObservationPack: this read is ${s.length} bytes, lines ${c} to ${p} of ${n.path}${x}.`,`${O} not shown${he}.${ge}`,"Read the file again with offset and limit for the lines you need, or Grep it. Do not guess at what is not shown.]",a].filter(E=>E!=="").join(`
|
|
61
|
+
`)}function Be(e,n){let r=ee("sha256").update(n).digest("hex"),s=$(e,`${r}.txt`);if(z(s)){let t=new Date;Re(s,t,t)}else Z(e,{recursive:!0,mode:448}),Te(s,n,{mode:384});return{sha:r,path:s}}function Me(e,n,r){if(!n.enabled)return null;let s=e.tool_name;if(!s||!Ee(s,n.tools))return null;let t=e.tool_input?.file_path;if(typeof t=="string"&&V(t).startsWith(V(r)+Pe)||n.limitBytes<=n.headBytes+n.tailBytes)return null;if(s==="Read"){let a=e.tool_response;if(!Ce(a))return null;let l=a.file.content,u=Buffer.byteLength(l,"utf-8");if(u<=n.limitBytes)return null;let h=typeof t=="string"?t:a.file.filePath??"the file you read",c=e.tool_input?.offset,p=typeof a.file.startLine=="number"&&a.file.startLine>=1?a.file.startLine:typeof c=="number"&&c>=1?c:1,g=Ue(l,{path:h,startLine:p,totalLines:a.file.totalLines},n),d=ee("sha256").update(l).digest("hex");return{updated:{...a,file:{...a.file,content:g}},packs:[{sha:d,path:h,bytes:u,keptBytes:Buffer.byteLength(g,"utf-8")}]}}let o=[],i=a=>{if(typeof a=="string"){let l=Buffer.byteLength(a,"utf-8");if(l<=n.limitBytes)return a;let{sha:u,path:h}=Be(r,a),c=De(a,h,n);return o.push({sha:u,path:h,bytes:l,keptBytes:Buffer.byteLength(c,"utf-8")}),c}if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){let l=a;return l.type==="image"||l.type==="audio"||l.isImage===!0||typeof l.persistedOutputPath=="string"?a:Object.fromEntries(Object.entries(l).map(([u,h])=>[u,u==="blob"?h:i(h)]))}return a};try{let a=i(e.tool_response);return o.length>0?{updated:a,packs:o}:null}catch{return null}}function vt(e,n,r){let s=e&&typeof e=="object"?Me(e,n,r.dir):null;if(!s)return"";try{let t=new Date().toISOString(),o=s.packs.map(i=>JSON.stringify({at:t,agent:r.agentId,session:e.session_id,tool:e.tool_name,sha:i.sha,bytes:i.bytes,keptBytes:i.keptBytes}));Z(r.dir,{recursive:!0,mode:448}),_e($(r.dir,"index.jsonl"),o.join(`
|
|
62
|
+
`)+`
|
|
63
|
+
`,{mode:384})}catch{}return JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",updatedToolOutput:s.updated}})}function Dt(e,n,r=Date.now()){if(n<=0||!z(e))return 0;let s=r-n*864e5,t=0;for(let o of Q(e,{withFileTypes:!0})){if(!o.isDirectory())continue;let i=$(e,o.name);for(let a of Q(i)){if(!a.endsWith(".txt"))continue;let l=$(i,a);try{Ae(l).mtimeMs<s&&(Oe(l),t++)}catch{}}}return t}var U=180,Ie=600;function Ne(e){let n;try{n=JSON.stringify(e??{})}catch{n=String(e)}n=n.replace(/\s+/g," ").trim();let r="Input: ",s=Ie-r.length;return r+(n.length>s?n.slice(0,s-1)+"\u2026":n)}function se(e,n){return e.length>n?e.slice(0,n-1)+"\u2026":e}function b(e,n,r){return`[agentx-mcp] "${n}" on MCP server "${e}" writes data and was not run: ${r}. Do not retry it or work around it. Say what you were trying to do and wait for instructions.`}function C(e,n,r){return e.verdict==="yes"?null:b(n,r,`the owner said no on card ${e.id}`)}async function Mt(e,n,r,s){let t=G(e,r);if(!t)return null;let{server:o,tool:i}=t,a=s.now??Date.now,l=s.sleep??(p=>new Promise(g=>setTimeout(g,p))),u=s.waitMs??U*1e3,h=s.pollMs??1e3,c=Math.max(1,Math.round(u/6e4));try{let p=a(),g=F(s.root,{title:se(`${s.agentId} wants to write with ${o}: ${i}`,120),ask:se(`Let ${s.agentId} run the "${i}" tool on ${o}? It changes data in that service.`,300),recommend:`Yes only if you asked for this. No, or no answer within ${c} min, and it does not run.`,context:Ne(n),if_silent:"discard",expires:new Date(p+u).toISOString(),raised_by:s.agentId},{now:p,settings:s.settings,origin:{kind:"mcp-write",server:o,tool:i}});if(!g.ok)return b(o,i,`the confirmation card could not be raised (${g.error})`);let d=g.card.id;try{s.onCard?.(g.card)}catch{}for(;;){let f=R(s.root,d);if(!f)return b(o,i,"the confirmation card is gone");if(f.status==="decided")return C(f,o,i);if(f.status!=="pending")return b(o,i,`card ${d} was not answered in time`);if(a()-p>=u){let x=R(s.root,d);if(!x)return b(o,i,"the confirmation card is gone");if(x.status==="decided")return C(x,o,i);if(x.status!=="pending")return b(o,i,`card ${d} was not answered in time`);j(s.root,{...x,status:"expired",outcome:"discard",decided_by:"expiry",decided_at:new Date(a()).toISOString()});let O=R(s.root,d);return O?.status==="decided"?C(O,o,i):b(o,i,`card ${d} was not answered within ${c} min`)}await l(h)}}catch(p){return b(o,i,`the confirmation step failed (${p?.message??p})`)}}import{mkdirSync as Le,renameSync as Ge,writeFileSync as je}from"fs";import{dirname as Fe,resolve as He}from"path";var We="AGENTX_GUARD_ERROR",M=75,qe={connectS:1,maxTimeS:55,deadlineMs:3e3};function oe(e){return He(e,".agentx/bin/agentx-guard")}function Gt(e,n,r){let s=oe(e);Le(Fe(s),{recursive:!0});let t=`#!/bin/sh
|
|
64
|
+
[ -f ${k(r)} ] || exit 127
|
|
65
|
+
exec ${k(n)} ${k(r)} "$@"
|
|
66
|
+
`,o=`${s}.${process.pid}.tmp`;return je(o,t,{mode:493}),Ge(o,s),s}function k(e){return`'${e.replace(/'/g,"'\\''")}'`}var _="[A-Za-z0-9_./~@:=-]+",B=`(start|restart|status)( +(-d|--detach|--when-idle|(-c|--config|--port)( +|=)${_}))*`,re="([0-9]+|\\$\\(id -u\\)|\\$UID)",Je=[`agentx +daemon +${B}`,`(node +)?(${_}/)?cli\\.js +daemon +${B}`,`npx +tsx +(${_}/)?cli\\.ts +daemon +${B}`,`launchctl +kickstart( +-k)? +gui/${re}/${_}`,`launchctl +(bootstrap|bootout) +gui/${re} +${_}`,`systemctl +--user +(start|restart|status) +${_}`,`sudo +systemctl +(start|restart|status) +${_}`].map(e=>`(${e})`).join("|");function Xe(e){return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})}var Ke="[agentx-guard] Refused: the AgentX guard could not check this call (the daemon is not answering and the local check failed). Only `agentx daemon start|restart|status` and the launchctl/systemctl forms that start the daemon run until it answers.";function ie(e){let n=e.budget??qe,r=e.agentId?`?agent=${encodeURIComponent(e.agentId)}`:"",s=`http://127.0.0.1:${e.port}/guard/check${r}`,t=`guard check --rules-only --deadline-ms ${n.deadlineMs} --root ${k(e.root)}${e.agentId?` --agent ${k(e.agentId)}`:""}`,o=["p=$(cat)",`out=$(printf '%s' "$p" | curl -sf --connect-timeout ${n.connectS} --max-time ${n.maxTimeS} -H 'Content-Type: application/json' --data-binary @- '${s}' 2>/dev/null) && { printf '%s' "$out"; exit 0; }`,`out=$(printf '%s' "$p" | ${k(e.cliPath??oe(e.root))} ${t} 2>/dev/null) || out=$(printf '%s' "$p" | agentx ${t} 2>/dev/null)`,`[ $? -eq 0 ] && [ "$out" != ${We} ] && { printf '%s' "$out"; exit 0; }`];return e.required&&o.push('[ "$AGENTX_GUARD" = required ] || exit 0',`c=$(printf '%s' "$p" | grep -o '"command" *: *"[^"\\\\]*"')`,`if printf '%s' "$p" | grep -q '"tool_name" *: *"Bash"' && [ "$(printf '%s\\n' "$c" | grep -c .)" = 1 ] && printf '%s\\n' "$c" | sed 's/^"command" *: *"//; s/"$//; s/^ *//; s/ *$//' | grep -Eqx ${k(Je)}; then exit 0; fi`,`printf '%s' ${k(Xe(Ke))}`),o.push("exit 0"),o.join(`
|
|
67
|
+
`)}var I="<!-- agentx-managed: hash=",N=" -->";function ce(e){return Ye("sha256").update(e.systemPrompt??"").update("\0").update(e.codegraph?"cg:1":"cg:0").digest("hex").slice(0,16)}function Qe(e){return`${I}${ce(e)}${N}`}function Ve(e){let n=e.split(`
|
|
68
|
+
`,1)[0]??"";return!n.startsWith(I)||!n.endsWith(N)?null:n.slice(I.length,n.length-N.length)}function ue(e,n){let r=`${e} ${n.systemPrompt||""} ${n.name}`.toLowerCase();return/cod(e|ing|er)|develop|engineer|program/.test(r)?"coding":/pm|project.?manag|product|scrum/.test(r)?"pm":/devops|deploy|infra|ops|sre|ci.?cd/.test(r)?"devops":/qa|test|quality|forensic/.test(r)?"qa":"general"}function ze(e,n,r){let s=ue(e,n),t=[];switch(t.push(Qe(n)),t.push(`# ${n.name}`),t.push(""),t.push("@AGENTS.md"),t.push(""),n.systemPrompt&&n.systemPrompt.trim().length>0&&(t.push("## Role"),t.push(""),t.push(n.systemPrompt.trimEnd()),t.push("")),t.push("## Commands"),t.push(""),y(m(n.workspace,"package.json"))?(t.push("```bash"),t.push("npm install # install dependencies"),t.push("npm test # run tests"),t.push("npm run build # build project"),t.push("```")):y(m(n.workspace,"requirements.txt"))&&(t.push("```bash"),t.push("pip install -r requirements.txt"),t.push("pytest"),t.push("```")),t.push(""),t.push("## Conventions"),t.push(""),s){case"coding":t.push("- Write tests for new code before committing"),t.push("- Keep functions small and focused"),t.push("- Follow existing patterns in the codebase"),t.push("- Run tests before pushing");break;case"pm":t.push("- Keep responses concise (3-5 lines main message)"),t.push("- Reference issues with #IID and MRs with !IID"),t.push("- Update issue labels and milestones when relevant"),t.push("- Summarize decisions, don't narrate process");break;case"devops":t.push("- Always check service status before making changes"),t.push("- Never run destructive commands without confirmation"),t.push("- Log all deployment actions"),t.push("- Verify changes in staging before production");break;case"qa":t.push("- Document reproduction steps for every bug"),t.push("- Include expected vs actual behavior"),t.push("- Check both happy path and edge cases"),t.push("- Attach screenshots when reporting UI issues");break;default:t.push("- Be concise \u2014 lead with the answer, skip preamble"),t.push("- Follow existing patterns in the codebase")}return t.push(""),t.push("## Cross-Channel Messaging"),t.push(""),t.push("You can send messages to any channel proactively:"),t.push("```bash"),t.push(`curl -X POST http://localhost:${r}/send \\`),t.push(' -H "Content-Type: application/json" \\'),t.push(` -d '{"channel":"telegram","chatId":"<id>","text":"<message>","agentId":"${e}"}'`),t.push("```"),t.push("Channels: telegram, whatsapp, gitlab, discord"),t.push(""),t.push("## Typed actions \u2014 prefer these over free-form Bash"),t.push(""),t.push("Daemon-shipped typed actions cover the common needs. Each call appears in `/traces` as a structured step (input + output schema), unlike opaque `Bash`/`curl`/`Read` calls."),t.push(""),t.push("```bash"),t.push("# List available actions + their schemas"),t.push("agentx actions builtin # \u2192 catalog"),t.push("agentx actions builtin <name> --schema # \u2192 input/output schema"),t.push(""),t.push("# Invoke an action with typed JSON input"),t.push(`agentx actions builtin http.fetch --input '{"url":"https://example.com/data"}'`),t.push(`agentx actions builtin http.post --input '{"url":"https://x.tld/hook","body":{"k":"v"}}'`),t.push(`agentx actions builtin file.read_lines --input '{"path":"data/prices.json"}'`),t.push(`agentx actions builtin file.write_jsonl --input '{"path":"leads.jsonl","record":{"name":"\u2026","email":"\u2026"}}'`),t.push(`agentx actions builtin extract.structured --input '{"prompt":"<text>","schema":{"type":"object",\u2026}}'`),t.push(`agentx actions builtin rag.lexical --input '{"agentId":"${e}","query":"\u2026","limit":5}'`),t.push(`agentx actions builtin agent.call --input '{"agentId":"<local-agent>","message":"\u2026"}'`),t.push(`agentx actions builtin mesh.delegate --input '{"peer":"<peer-name>","agent":"<peer-agent>","message":"\u2026"}'`),t.push("```"),t.push(""),t.push("Rule of thumb:"),t.push("- HTTP fetch/POST \u2192 `http.fetch` / `http.post` (not `Bash curl`)"),t.push("- Reading a file you'll parse \u2192 `file.read_lines` (not `Bash cat`)"),t.push("- Appending a structured record \u2192 `file.write_jsonl` (not `Bash echo >>` or `Write` with model-formatted JSON)"),t.push("- Extracting fields from text into a typed object \u2192 `extract.structured` (not asking the model to format JSON in its reply)"),t.push("- Searching a doc corpus \u2192 `rag.lexical` (not `Read` over every file)"),t.push("- Calling another agent on this daemon \u2192 `agent.call` (fresh session by default; not composing `Bash curl` to /task)"),t.push("- Calling an agent on a peer mesh node \u2192 `mesh.delegate` (cross-machine; same fresh-session default)"),t.push(""),n.codegraph&&t.push(Y()),t.join(`
|
|
69
|
+
`)}var P=["Bash(npx prisma migrate reset*)","Bash(prisma migrate reset*)","Bash(npx prisma db push*)","Bash(prisma db push*)","Bash(dropdb*)"];function Ze(e,n,r=process.cwd()){return ie({port:n,root:r,agentId:e,required:!0})}var le=U+15,et=le+15;function tt(e,n){let r=`http://127.0.0.1:${n}/guard/check?agent=${encodeURIComponent(e)}`,s=JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"AgentX guard did not answer; tools of an MCP server with an allow list are refused until it does."}});return`out=$(curl -sf --max-time ${le} -H 'Content-Type: application/json' --data-binary @- '${r}' 2>/dev/null) && printf '%s' "$out" || printf '%s' '${s}'`}function pe(e,n,r){let s=Ze(e,n),t=[{matcher:"Bash",hooks:[{type:"command",command:s,timeout:M}]},{matcher:"Write|Edit",hooks:[{type:"command",command:s,timeout:M}]}],o=L(r);return o&&t.push({matcher:o,hooks:[{type:"command",command:tt(e,n),timeout:et}]}),t}function nt(e){return`[ -n "$AGENTX_AGENT_ID" ] && [ -n "$AGENTX_QUEUE_CHAT" ] && in=$(cat) && ! printf '%s' "$in" | sed 's/\\\\"//g' | grep -q '"agent_id"' && curl -sf --max-time 2 -G --data-urlencode "agent=$AGENTX_AGENT_ID" --data-urlencode "channel=$AGENTX_QUEUE_CHANNEL" --data-urlencode "chat=$AGENTX_QUEUE_CHAT" '${`http://127.0.0.1:${e}/runs/inbox`}' 2>/dev/null; true`}var st=5;function de(e){return{matcher:"",hooks:[{type:"command",command:nt(e),timeout:st}]}}function rt(e){return Array.isArray(e?.hooks)&&e.hooks.some(n=>typeof n?.command=="string"&&n.command.includes("/runs/inbox"))}function ot(e){return Array.isArray(e?.hooks)&&e.hooks.some(n=>typeof n?.command=="string"&&(n.command.includes("/guard/check")||n.command.includes("guard check")))}function it(e,n,r="19900"){let s={autoMemoryEnabled:!0,env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}};if(n.permissionMode==="bypassPermissions"?s.permissions={deny:[...P]}:n.permissionMode==="plan"?s.permissions={deny:[...P,"Bash(rm -rf *)","Bash(drop *)","Bash(DELETE *)"]}:s.permissions={deny:[...P,"Bash(rm -rf /)","Bash(> /dev/sda*)","Bash(mkfs*)"]},n.codegraph){let o=s.permissions||{},i=Array.isArray(o.allow)?o.allow:[];o.allow=[...new Set([...i,...K])],s.permissions=o}let t={};return t.PreToolUse=pe(e,r,n.mcp),t.Notification=[{matcher:"",hooks:[{type:"command",command:`echo "[${e}] notification: $(jq -r '.type // "unknown"')" >> /tmp/agentx-${e}.log`}]}],t.PostToolUse=[{matcher:"Bash",hooks:[{type:"command",command:`jq -r '.tool_input.command // empty' >> /tmp/agentx-${e}-commands.log`}]},de(r)],t.SessionStart=[{matcher:"compact",hooks:[{type:"command",command:`echo "Reminder: You are ${n.name} (${e}). Follow the conventions in CLAUDE.md."`}]}],s.hooks=t,s}var at=`# Code Quality
|
|
70
|
+
|
|
71
|
+
- No console.log in production code (use a logger)
|
|
72
|
+
- Handle errors explicitly \u2014 no empty catch blocks
|
|
73
|
+
- Keep files under 300 lines
|
|
74
|
+
- Extract repeated logic into shared utilities
|
|
75
|
+
`;function ct(e,n){let r=ue(e,n),s=[];switch(r){case"coding":s.push({name:"testing.md",content:`---
|
|
76
|
+
paths:
|
|
77
|
+
- "**/*.test.{ts,tsx,js,jsx}"
|
|
78
|
+
- "**/*.spec.{ts,tsx,js,jsx}"
|
|
79
|
+
- "test/**/*"
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
# Testing Rules
|
|
83
|
+
|
|
84
|
+
- Every new function should have a corresponding test
|
|
85
|
+
- Test both happy path and error cases
|
|
86
|
+
- Use descriptive test names that explain what's being tested
|
|
87
|
+
- Mock external dependencies, not internal modules
|
|
88
|
+
`}),s.push({name:"code-quality.md",content:`# Code Quality
|
|
89
|
+
|
|
90
|
+
- No console.log in production code (use a logger)
|
|
91
|
+
- Handle errors explicitly \u2014 no empty catch blocks
|
|
92
|
+
- Extract repeated logic into shared utilities
|
|
93
|
+
`,replaces:[at]});break;case"devops":s.push({name:"deployment-safety.md",content:`# Deployment Safety
|
|
94
|
+
|
|
95
|
+
- Always verify staging before production
|
|
96
|
+
- Check disk space and memory before deploying
|
|
97
|
+
- Never expose secrets in logs or commits
|
|
98
|
+
- Use rollback-safe deployment strategies
|
|
99
|
+
`});break;case"pm":s.push({name:"communication.md",content:`# Communication Rules
|
|
100
|
+
|
|
101
|
+
- Keep GitLab comments under 5 lines for the main message
|
|
102
|
+
- Use <details> for verbose output (logs, commands, steps)
|
|
103
|
+
- Reference issues with #IID, merge requests with !IID
|
|
104
|
+
- Never mention Telegram handles on GitLab
|
|
105
|
+
`});break;case"qa":s.push({name:"bug-reports.md",content:`# Bug Report Format
|
|
106
|
+
|
|
107
|
+
Always include:
|
|
108
|
+
1. Steps to reproduce
|
|
109
|
+
2. Expected behavior
|
|
110
|
+
3. Actual behavior
|
|
111
|
+
4. Environment (browser, OS, version)
|
|
112
|
+
5. Screenshots if applicable
|
|
113
|
+
`});break}return s}function ut(e,n,r="19900",s=console.error){let t=[],o=[],i=n.workspace;if(!y(i))return s(`Workspace not found: ${i}`),{created:t,skipped:o};if(n.tier!=="claude-code"&&n.tier!=="codex-cli")return{created:t,skipped:o};let a=(c,p)=>{y(c)?o.push(c):(ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c))},l=(c,p,g)=>{if(!y(c)){ae(m(c,".."),{recursive:!0}),S(c,p),t.push(c);return}let d;try{d=A(c,"utf8")}catch{o.push(c);return}let f=Ve(d);if(f===null){o.push(c);return}if(f===g){o.push(c);return}S(c,p),t.push(`${c} (refreshed)`)};if(a(m(i,"AGENTS.md"),W({name:n.name,id:e,role:n.systemPrompt?.split(`
|
|
114
|
+
`)[0],workspace:i,tier:n.tier})),n.tier==="codex-cli")return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o};l(m(i,"CLAUDE.md"),ze(e,n,r),ce(n));let u=m(i,".claude/settings.json");a(u,JSON.stringify(it(e,n,r),null,2));let h=ct(e,n);for(let c of h){let p=m(i,".claude/rules",c.name);c.replaces&&y(p)&&c.replaces.includes(A(p,"utf8"))?(S(p,c.content),t.push(p)):a(p,c.content)}return t.length>0&&s(`[${e}] workspace setup: created ${t.length} file(s)`),{created:t,skipped:o}}function lt(e,n){let r=m(e,".claude/settings.json");if(!y(r))return!1;try{let s=JSON.parse(A(r,"utf-8")),t=!1;for(let[o,i]of Object.entries(n))if(typeof i=="object"&&i!==null&&!Array.isArray(i)){s[o]||(s[o]={});for(let[a,l]of Object.entries(i))s[o][a]===void 0&&(s[o][a]=l,t=!0)}else s[o]===void 0&&(s[o]=i,t=!0);return t&&S(r,JSON.stringify(s,null,2)),t}catch{return!1}}function pt(e,n,r="19900",s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=!1,a=o.permissions??={},l=Array.isArray(a.deny)?a.deny:a.deny=[];for(let d of P)l.includes(d)||(l.push(d),i=!0);let u=o.hooks??={},c=[...Array.isArray(u.PreToolUse)?u.PreToolUse.filter(d=>!ot(d)):[],...pe(n,r,s)];JSON.stringify(u.PreToolUse??null)!==JSON.stringify(c)&&(u.PreToolUse=c,i=!0);let g=[...Array.isArray(u.PostToolUse)?u.PostToolUse.filter(d=>!rt(d)):[],de(r)];return JSON.stringify(u.PostToolUse??null)!==JSON.stringify(g)&&(u.PostToolUse=g,i=!0),i&&S(t,JSON.stringify(o,null,2)),i}catch{return!1}}function dt(e){return Array.isArray(e?.hooks)&&e.hooks.some(n=>typeof n?.command=="string"&&n.command.includes(D))}function ht(e,n,r,s){let t=m(e,".claude/settings.json");if(!y(t))return!1;try{let o=JSON.parse(A(t,"utf-8")),i=JSON.stringify(o),a=s.enabled&&s.tools.length>0,l=`Read(/${te(s.dir,n)}/**)`,u=Array.isArray(o.hooks?.PostToolUse)?o.hooks.PostToolUse:[],h=u.filter(g=>!dt(g)),c=Array.isArray(o.permissions?.allow)?o.permissions.allow:[],p=c.filter(g=>g!==l);if(a){let d=`curl -s --max-time 5 -H 'Content-Type: application/json' --data-binary @- '${`http://127.0.0.1:${r}${D}?agent=${encodeURIComponent(n)}`}' 2>/dev/null || true`;h.push({matcher:s.tools.join("|"),hooks:[{type:"command",command:d,timeout:10}]}),p.push(l)}return(a||u.length>0)&&((o.hooks??={}).PostToolUse=h),(a||c.length>0)&&((o.permissions??={}).allow=p),JSON.stringify(o)===i?!1:(S(t,JSON.stringify(o,null,2)),!0)}catch{return!1}}function Vt(e,n="19900",r=console.error,s){let t=0,o=0,i=0,a=0,l=0,u=0;for(let[h,c]of Object.entries(e)){if(c.tier!=="claude-code"&&c.tier!=="codex-cli")continue;let p=ut(h,c,n,r);if(t+=p.created.length,c.tier==="claude-code"&<(c.workspace,{env:{CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1"}})&&o++,c.tier==="claude-code"&&pt(c.workspace,h,n,c.mcp)&&i++,c.tier==="claude-code"&&s){let g=ne(c.permissionMode);s.enabled&&!g&&u++;let d=s.enabled&&g;ht(c.workspace,h,n,{...s,enabled:d})&&(d?a++:l++)}}t>0&&r(`Workspace setup: ${t} file(s) created across agent workspaces`),o>0&&r(`Workspace patch: ${o} workspace(s) updated with agent teams support`),i>0&&r(`Guardrails: ${i} workspace(s) backfilled with deny list + PreToolUse guard hook`),a>0&&r(`ObservationPack: PostToolUse hook written to ${a} workspace(s)`),l>0&&r(`ObservationPack: PostToolUse hook removed from ${l} workspace(s)`),u>0&&r(`ObservationPack: ${u} agent(s) not packed: permissionMode is not "bypassPermissions", so they could not read a saved original back`)}export{yt as a,bt as b,kt as c,St as d,At as e,D as f,Et as g,te as h,ne as i,vt as j,Dt as k,Mt as l,We as m,M as n,Gt as o,ie as p,Ve as q,ze as r,le as s,et as t,tt as u,nt as v,ut as w,pt as x,ht as y,Vt as z};
|
|
115
|
+
//# sourceMappingURL=chunk-NERO7F3J.js.map
|