agentix-cli 0.196.0 → 0.197.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{App-HBM52GXI.js → App-GF6MCNH6.js} +2 -2
- package/dist/{App-HBM52GXI.js.map → App-GF6MCNH6.js.map} +1 -1
- package/dist/ChatApp-FO2JNLWI.js +7 -0
- package/dist/{ChatApp-N4P7M2TD.js.map → ChatApp-FO2JNLWI.js.map} +1 -1
- package/dist/absorb-eval-7KMQJ5BR.js +2 -0
- package/dist/{adapter-X6T3YBUB.js → adapter-V7DQXCII.js} +2 -2
- package/dist/{adapter-X6T3YBUB.js.map → adapter-V7DQXCII.js.map} +1 -1
- package/dist/{agent-3B4RMEDI.js → agent-PJBGUZMR.js} +2 -2
- package/dist/{board-dashboard-Y2X7GNAS.js → board-dashboard-M3RVQM7K.js} +717 -380
- package/dist/board-dashboard-M3RVQM7K.js.map +1 -0
- package/dist/{chunk-YWAJNF2A.js → chunk-27ICCQVL.js} +54 -54
- package/dist/chunk-27ICCQVL.js.map +1 -0
- package/dist/{chunk-PMSL4A5Y.js → chunk-35GSB7SK.js} +3 -3
- package/dist/{chunk-XH36J3Z2.js → chunk-3K3IBV5K.js} +2 -2
- package/dist/{chunk-ZALVAXQ4.js → chunk-3LMBT5LK.js} +2 -2
- package/dist/{chunk-MB5CBY2C.js → chunk-424CABZF.js} +7 -7
- package/dist/chunk-424CABZF.js.map +1 -0
- package/dist/{chunk-F2FJXKDG.js → chunk-425HPUKF.js} +2 -2
- package/dist/{chunk-PX7PWXBI.js → chunk-4O6ZFYWT.js} +2 -2
- package/dist/chunk-7AB3QUGH.js +2 -0
- package/dist/{chunk-3FZ6WHKX.js.map → chunk-7AB3QUGH.js.map} +1 -1
- package/dist/chunk-7MW44Y5O.js +145 -0
- package/dist/chunk-7MW44Y5O.js.map +1 -0
- package/dist/chunk-B3JQ5J47.js +2 -0
- package/dist/chunk-B3JQ5J47.js.map +1 -0
- package/dist/chunk-BMNDAEF4.js +2 -0
- package/dist/chunk-BMNDAEF4.js.map +1 -0
- package/dist/{chunk-2GCPSAXQ.js → chunk-BN5JVELZ.js} +2 -2
- package/dist/{chunk-LQIF2OHS.js → chunk-BY5CN7C7.js} +2 -2
- package/dist/{chunk-HOZZUN47.js → chunk-DHD4KUTW.js} +2 -2
- package/dist/{chunk-KE6BF4ZJ.js → chunk-GMP2IB4E.js} +2 -2
- package/dist/{chunk-K2BEV3BD.js → chunk-HIHROVHC.js} +2 -2
- package/dist/{chunk-KXJRXRSD.js → chunk-HOL645BZ.js} +2 -2
- package/dist/{chunk-7L54Z4EH.js → chunk-HUOR3FGJ.js} +2 -2
- package/dist/chunk-I22ZKW7Q.js +4 -0
- package/dist/chunk-I22ZKW7Q.js.map +1 -0
- package/dist/chunk-IFUAP7UD.js +11 -0
- package/dist/chunk-IFUAP7UD.js.map +1 -0
- package/dist/{chunk-V7FZBETJ.js → chunk-IOCULCCJ.js} +2 -2
- package/dist/{chunk-NT3DGEBE.js → chunk-IQQ3I6R7.js} +312 -311
- package/dist/chunk-IQQ3I6R7.js.map +1 -0
- package/dist/{chunk-6V5JBHUN.js → chunk-J7PZJRYO.js} +2 -2
- package/dist/{chunk-F3CMNSON.js → chunk-K3623S4U.js} +2 -2
- package/dist/{chunk-2KYGPVTX.js → chunk-KB5JMDGS.js} +2 -2
- package/dist/{chunk-HNZEXUNM.js → chunk-OVB3LW6L.js} +2 -2
- package/dist/{chunk-6NQ7KYJH.js → chunk-OXTFAV2A.js} +2 -2
- package/dist/{chunk-VX4PSOKU.js → chunk-QABY3WEM.js} +2 -2
- package/dist/{chunk-M2E3CNFS.js → chunk-R3TH2OG7.js} +2 -2
- package/dist/chunk-RC3QYH2J.js +20 -0
- package/dist/chunk-RC3QYH2J.js.map +1 -0
- package/dist/{chunk-UOIWIVU3.js → chunk-RLI32DLG.js} +2 -2
- package/dist/{chunk-RW5FKJRE.js → chunk-SK7M6PS6.js} +2 -2
- package/dist/chunk-SNYAM7YB.js +116 -0
- package/dist/chunk-SNYAM7YB.js.map +1 -0
- package/dist/{chunk-BOCLWYWL.js → chunk-TBS7OVMI.js} +2 -2
- package/dist/{chunk-FO762MEC.js → chunk-TKXZHRV3.js} +2 -2
- package/dist/{chunk-PO2SORKY.js → chunk-WFPLZLCF.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-ZHE4B2DD.js +2 -0
- package/dist/config-THBWCNN7.js +2 -0
- package/dist/config-mutate-FBX6TFCY.js +2 -0
- package/dist/config-mutator-33RBNPV4.js +2 -0
- package/dist/{contributions-6VZ4OXJ5.js → contributions-2HR5ZGMK.js} +2 -2
- package/dist/{contributions-6VZ4OXJ5.js.map → contributions-2HR5ZGMK.js.map} +1 -1
- package/dist/doctor-VMWX6GKN.js +2 -0
- package/dist/{follow-up-tool-NVP56W7E.js → follow-up-tool-BCSCBKVL.js} +2 -2
- package/dist/{follow-up-tool-NVP56W7E.js.map → follow-up-tool-BCSCBKVL.js.map} +1 -1
- package/dist/hub-WPC6MTZY.js +2 -0
- package/dist/index.d.ts +131 -6
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{note-tool-ANQWBBZE.js → note-tool-KVH3YBTX.js} +2 -2
- package/dist/ntfy-73UW6GHN.js +2 -0
- package/dist/{program-W7ZO7UDB.js → program-MOVUJBAA.js} +246 -246
- package/dist/program-MOVUJBAA.js.map +1 -0
- package/dist/promote-WWPXP5Z4.js +2 -0
- package/dist/push-E5YKRFAW.js +2 -0
- package/dist/push-bridge-RV3CBTYO.js +2 -0
- package/dist/query-F7HRTCWI.js +2 -0
- package/dist/{query-settings-C5UBKJMN.js → query-settings-Z32LXLJI.js} +2 -2
- package/dist/registry-D5HHCFCC.js +2 -0
- package/dist/request-planner-4FSNZJVQ.js +6 -0
- package/dist/{request-planner-G6IAUMSE.js.map → request-planner-4FSNZJVQ.js.map} +1 -1
- package/dist/review-candidates-U2DOD5Z3.js +4 -0
- package/dist/{review-candidates-ZL2SJXWC.js.map → review-candidates-U2DOD5Z3.js.map} +1 -1
- package/dist/routing-USMMBJYT.js +2 -0
- package/dist/schedule-tool-IRTB23XL.js +2 -0
- package/dist/scheduler-L4ERAOMG.js +2 -0
- package/dist/seat-3LW672DM.js +2 -0
- package/dist/select-MPMJSYKX.js +2 -0
- package/dist/{select-MU52ACKG.js.map → select-MPMJSYKX.js.map} +1 -1
- package/dist/self-HICJTWYO.js +2 -0
- package/dist/set-enabled-TQXG3MSQ.js +2 -0
- package/dist/{set-enabled-XRNSYEI3.js.map → set-enabled-TQXG3MSQ.js.map} +1 -1
- package/dist/{sprint-tool-E4MABD2N.js → sprint-tool-JQ5KCJDP.js} +2 -2
- package/dist/{sprint-tool-E4MABD2N.js.map → sprint-tool-JQ5KCJDP.js.map} +1 -1
- package/dist/{tool-ZYVT4VUU.js → tool-D4DHXF4Z.js} +2 -2
- package/dist/{tool-ZYVT4VUU.js.map → tool-D4DHXF4Z.js.map} +1 -1
- package/dist/tool-DHCKG3SK.js +10 -0
- package/dist/tool-DHCKG3SK.js.map +1 -0
- package/dist/{tool-V5Z4KWK7.js → tool-ZP3SZKYR.js} +2 -2
- package/dist/{tool-V5Z4KWK7.js.map → tool-ZP3SZKYR.js.map} +1 -1
- package/dist/wiki-CRH6XAXE.js +2 -0
- package/dist/wiki-enrich-YZEW6RZT.js +2 -0
- package/package.json +1 -1
- package/dist/ChatApp-N4P7M2TD.js +0 -7
- package/dist/absorb-eval-HRWWPKT3.js +0 -2
- package/dist/board-dashboard-Y2X7GNAS.js.map +0 -1
- package/dist/chunk-3FZ6WHKX.js +0 -2
- package/dist/chunk-5HLD66CW.js +0 -2
- package/dist/chunk-5HLD66CW.js.map +0 -1
- package/dist/chunk-AJ5HMDRW.js +0 -11
- package/dist/chunk-AJ5HMDRW.js.map +0 -1
- package/dist/chunk-IS2IWRP7.js +0 -4
- package/dist/chunk-IS2IWRP7.js.map +0 -1
- package/dist/chunk-MB5CBY2C.js.map +0 -1
- package/dist/chunk-MC3ZZA5G.js +0 -143
- package/dist/chunk-MC3ZZA5G.js.map +0 -1
- package/dist/chunk-NT3DGEBE.js.map +0 -1
- package/dist/chunk-P6WSD2UR.js +0 -116
- package/dist/chunk-P6WSD2UR.js.map +0 -1
- package/dist/chunk-UOYIC7XN.js +0 -3
- package/dist/chunk-UOYIC7XN.js.map +0 -1
- package/dist/chunk-YWAJNF2A.js.map +0 -1
- package/dist/client-YN3T56NM.js +0 -2
- package/dist/config-G7T3TMWE.js +0 -2
- package/dist/config-mutate-6CRKZQVQ.js +0 -2
- package/dist/config-mutator-7VS3J5BY.js +0 -2
- package/dist/doctor-GFZZTK7C.js +0 -2
- package/dist/hub-B434CABZ.js +0 -2
- package/dist/ntfy-Q4YHFKWW.js +0 -2
- package/dist/program-W7ZO7UDB.js.map +0 -1
- package/dist/promote-3P6PGJOW.js +0 -2
- package/dist/push-PRFZMCIK.js +0 -2
- package/dist/push-bridge-NR7SLHGX.js +0 -2
- package/dist/query-E4V7TS5S.js +0 -2
- package/dist/registry-IG324PR3.js +0 -2
- package/dist/request-planner-G6IAUMSE.js +0 -6
- package/dist/review-candidates-ZL2SJXWC.js +0 -4
- package/dist/routing-2IBIZYQU.js +0 -2
- package/dist/schedule-tool-QCTT2R3B.js +0 -2
- package/dist/scheduler-ZGB7IKZQ.js +0 -2
- package/dist/seat-CFY7LMPS.js +0 -2
- package/dist/select-MU52ACKG.js +0 -2
- package/dist/self-ELWZIMVY.js +0 -2
- package/dist/set-enabled-XRNSYEI3.js +0 -2
- package/dist/tool-W6M7GYRZ.js +0 -8
- package/dist/tool-W6M7GYRZ.js.map +0 -1
- package/dist/wiki-VP6XRWIS.js +0 -2
- package/dist/wiki-enrich-LUFXPUYY.js +0 -2
- /package/dist/{absorb-eval-HRWWPKT3.js.map → absorb-eval-7KMQJ5BR.js.map} +0 -0
- /package/dist/{agent-3B4RMEDI.js.map → agent-PJBGUZMR.js.map} +0 -0
- /package/dist/{chunk-PMSL4A5Y.js.map → chunk-35GSB7SK.js.map} +0 -0
- /package/dist/{chunk-XH36J3Z2.js.map → chunk-3K3IBV5K.js.map} +0 -0
- /package/dist/{chunk-ZALVAXQ4.js.map → chunk-3LMBT5LK.js.map} +0 -0
- /package/dist/{chunk-F2FJXKDG.js.map → chunk-425HPUKF.js.map} +0 -0
- /package/dist/{chunk-PX7PWXBI.js.map → chunk-4O6ZFYWT.js.map} +0 -0
- /package/dist/{chunk-2GCPSAXQ.js.map → chunk-BN5JVELZ.js.map} +0 -0
- /package/dist/{chunk-LQIF2OHS.js.map → chunk-BY5CN7C7.js.map} +0 -0
- /package/dist/{chunk-HOZZUN47.js.map → chunk-DHD4KUTW.js.map} +0 -0
- /package/dist/{chunk-KE6BF4ZJ.js.map → chunk-GMP2IB4E.js.map} +0 -0
- /package/dist/{chunk-K2BEV3BD.js.map → chunk-HIHROVHC.js.map} +0 -0
- /package/dist/{chunk-KXJRXRSD.js.map → chunk-HOL645BZ.js.map} +0 -0
- /package/dist/{chunk-7L54Z4EH.js.map → chunk-HUOR3FGJ.js.map} +0 -0
- /package/dist/{chunk-V7FZBETJ.js.map → chunk-IOCULCCJ.js.map} +0 -0
- /package/dist/{chunk-6V5JBHUN.js.map → chunk-J7PZJRYO.js.map} +0 -0
- /package/dist/{chunk-F3CMNSON.js.map → chunk-K3623S4U.js.map} +0 -0
- /package/dist/{chunk-2KYGPVTX.js.map → chunk-KB5JMDGS.js.map} +0 -0
- /package/dist/{chunk-HNZEXUNM.js.map → chunk-OVB3LW6L.js.map} +0 -0
- /package/dist/{chunk-6NQ7KYJH.js.map → chunk-OXTFAV2A.js.map} +0 -0
- /package/dist/{chunk-VX4PSOKU.js.map → chunk-QABY3WEM.js.map} +0 -0
- /package/dist/{chunk-M2E3CNFS.js.map → chunk-R3TH2OG7.js.map} +0 -0
- /package/dist/{chunk-UOIWIVU3.js.map → chunk-RLI32DLG.js.map} +0 -0
- /package/dist/{chunk-RW5FKJRE.js.map → chunk-SK7M6PS6.js.map} +0 -0
- /package/dist/{chunk-BOCLWYWL.js.map → chunk-TBS7OVMI.js.map} +0 -0
- /package/dist/{chunk-FO762MEC.js.map → chunk-TKXZHRV3.js.map} +0 -0
- /package/dist/{chunk-PO2SORKY.js.map → chunk-WFPLZLCF.js.map} +0 -0
- /package/dist/{client-YN3T56NM.js.map → client-ZHE4B2DD.js.map} +0 -0
- /package/dist/{config-G7T3TMWE.js.map → config-THBWCNN7.js.map} +0 -0
- /package/dist/{config-mutate-6CRKZQVQ.js.map → config-mutate-FBX6TFCY.js.map} +0 -0
- /package/dist/{config-mutator-7VS3J5BY.js.map → config-mutator-33RBNPV4.js.map} +0 -0
- /package/dist/{doctor-GFZZTK7C.js.map → doctor-VMWX6GKN.js.map} +0 -0
- /package/dist/{hub-B434CABZ.js.map → hub-WPC6MTZY.js.map} +0 -0
- /package/dist/{note-tool-ANQWBBZE.js.map → note-tool-KVH3YBTX.js.map} +0 -0
- /package/dist/{ntfy-Q4YHFKWW.js.map → ntfy-73UW6GHN.js.map} +0 -0
- /package/dist/{promote-3P6PGJOW.js.map → promote-WWPXP5Z4.js.map} +0 -0
- /package/dist/{push-PRFZMCIK.js.map → push-E5YKRFAW.js.map} +0 -0
- /package/dist/{push-bridge-NR7SLHGX.js.map → push-bridge-RV3CBTYO.js.map} +0 -0
- /package/dist/{query-E4V7TS5S.js.map → query-F7HRTCWI.js.map} +0 -0
- /package/dist/{query-settings-C5UBKJMN.js.map → query-settings-Z32LXLJI.js.map} +0 -0
- /package/dist/{registry-IG324PR3.js.map → registry-D5HHCFCC.js.map} +0 -0
- /package/dist/{routing-2IBIZYQU.js.map → routing-USMMBJYT.js.map} +0 -0
- /package/dist/{schedule-tool-QCTT2R3B.js.map → schedule-tool-IRTB23XL.js.map} +0 -0
- /package/dist/{scheduler-ZGB7IKZQ.js.map → scheduler-L4ERAOMG.js.map} +0 -0
- /package/dist/{seat-CFY7LMPS.js.map → seat-3LW672DM.js.map} +0 -0
- /package/dist/{self-ELWZIMVY.js.map → self-HICJTWYO.js.map} +0 -0
- /package/dist/{wiki-VP6XRWIS.js.map → wiki-CRH6XAXE.js.map} +0 -0
- /package/dist/{wiki-enrich-LUFXPUYY.js.map → wiki-enrich-YZEW6RZT.js.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as d,g}from"./chunk-2VDO2HEK.js";import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as d,g}from"./chunk-2VDO2HEK.js";import{b as f}from"./chunk-B3JQ5J47.js";var k=/^[A-Za-z0-9._-]{1,64}$/,m=/^[A-Za-z0-9_-]{1,64}$/,A=100,w=1e3,E=6e4,P=15*6e4;function p(r){return(r.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"node").slice(0,64)}function _(r,t,n){let i=/^bearer /i.test(r)?r.slice(7).trim():"",e="Phones paired with another computer need that computer's own peer token: give it a token in mesh.peers on both computers.";if(!i||n&&i===n)return{error:e};let a=new Set(t.filter(s=>s.token===i).map(s=>p(s.name)));if(a.size===0)return{error:e};if(a.size>1)return{error:`Several mesh.peers entries share this token (${[...a].join(", ")}). Give each computer its own token.`};let[o]=a,u=t.filter(s=>s.token!==i&&p(s.name)===o).map(s=>s.name);return u.length?{error:`mesh.peers names ${u.map(s=>`"${s}"`).join(", ")} too close to this computer's name: rename one so they differ in letters or digits.`}:{origin:o}}function C(r,t){let n=r.indexOf(":");return n<0?{ok:!0}:"error"in t?{error:t.error}:r.slice(0,n)!==t.origin?{error:`${r} is a phone paired with another computer; only that computer can send to it.`}:{ok:!0}}function x(r,t,n){let i=r.toLowerCase(),e=t.find(a=>a.name.toLowerCase()===i);return e?e.token?n&&e.token===n?`mesh.peers "${e.name}" uses the shared MESH_TOKEN, so phones paired here can't turn notifications on. Give this pair a token of its own on both computers.`:null:`mesh.peers "${e.name}" has no token, so phones paired here can't turn notifications on. Give it a token of its own on both computers.`:null}function O(r){return new Set(r.map(t=>p(t.name)))}function j(r,t,n,i){let e=r&&typeof r=="object"?r:{};if("error"in t)return{status:403,body:{error:t.error}};let a=t.origin;if(!k.test(a))return{status:403,body:{error:"this peer's name can't be used as a notification origin"}};if(!n)return{status:503,body:{error:i??"Notifications are not set up on the computer that sends them."}};if(e.op==="roster"){if(!Array.isArray(e.active)||e.active.length>w||!e.active.every(l=>typeof l=="string"&&m.test(l)))return{status:400,body:{error:"active must be a list of device ids"}};let h=n.store();return h?{status:200,body:{ok:!0,removed:h.pruneOrigin(a,e.active)}}:{status:503,body:{error:n.reason??"the database is unavailable"}}}if(e.op!=="app")return{status:400,body:{error:"op must be app or roster"}};let o=e.call&&typeof e.call=="object"?e.call:{},u=o.device&&typeof o.device=="object"?o.device:{},s=typeof o.path=="string"?o.path:"",c=o.method==="GET"||o.method==="POST"?o.method:"";if(!d(s)||!c)return{status:404,body:{error:"not found"}};if(typeof u.id!="string"||!m.test(u.id))return{status:400,body:{error:"device.id is required"}};let b=typeof u.name=="string"&&u.name.trim()?u.name.trim():u.id,v=o.body&&typeof o.body=="object"&&!Array.isArray(o.body)?o.body:{};return g({path:s,method:c,body:v,device:{id:f(a,u.id),name:S(`${b} (${a})`,A)}},n)}var y=class{constructor(t){this.deps=t}lastKey=null;lastSentAt=0;failing=!1;async tick(){let t=(this.deps.now??Date.now)(),n;try{n=[...new Set(this.deps.active())].sort()}catch(e){return this.deps.log?.(`push: phone list not read, not sent this time: ${e?.message??e}`),!1}let i=n.join(",");if(i===this.lastKey&&t-this.lastSentAt<P)return!1;try{let e=await this.deps.send(n);if(e&&typeof e=="object"&&typeof e.status=="number"&&e.status!==200)throw new Error(`${e.status} ${typeof e.body?.error=="string"?e.body.error:"refused"}`);return this.lastKey=i,this.lastSentAt=t,this.failing&&this.deps.log?.("push: phone list sent to the push host again"),this.failing=!1,!0}catch(e){return this.failing||this.deps.log?.(`push: phone list not sent to the push host, retrying every minute: ${e?.message??e}`),this.failing=!0,!1}}};function S(r,t){let n=[...r];return n.length>t?n.slice(0,t-1).join("")+"\u2026":r}export{E as a,P as b,p as c,_ as d,C as e,x as f,O as g,j as h,y as i};
|
|
2
|
+
//# sourceMappingURL=chunk-J7PZJRYO.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as g}from"./chunk-
|
|
1
|
+
import{e as g}from"./chunk-35GSB7SK.js";async function $(e,i,r,n,o={}){let a=o.retrieve??g,c=o.perEntry??2,s=o.maxArticles??8,f=o.queryChars??1500,h=new Map;for(let t of e){let l=[];try{l=await a(t.content.slice(0,f),i,r,{pool:n,maxCandidates:c,maxHops:1,maxArticles:c*2,stage:"absorb-covering"})}catch{}for(let u of l){let p=h.get(u.path);p?(p.hop=Math.min(p.hop,u.hop),p.entries.includes(t.id)||p.entries.push(t.id)):h.set(u.path,{...u,entries:[t.id]})}}return[...h.values()].sort((t,l)=>t.hop-l.hop||l.entries.length-t.entries.length||t.path.localeCompare(l.path)).slice(0,s)}function x(e){if(e.length===0)return"";let i=e.map(r=>{let n=`### ${r.meta.title} \u2014 ${r.meta.type||"untyped"} (${r.path})`,o=`Found for entries: ${r.entries.join(", ")}${r.hop>0?" (linked from a match)":""}`,a=r.meta.related?.length?`Related: ${r.meta.related.join(", ")}`:"";return[n,o,a,"",r.content].filter(c=>c!=="").join(`
|
|
2
2
|
`)}).join(`
|
|
3
3
|
|
|
4
4
|
---
|
|
@@ -14,4 +14,4 @@ These ${e.length} articles were found by searching the wiki for each entry below
|
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
16
|
`}var d=/\bhttps?:\/\/[^\s<>"'`)\]]+/gi,y=/\[\[([^\]|]+)(?:\|[^\]]*)?\]\]/g,w=/(?<![\w-])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}(?![\w-])/gi,k=/(?<![\w.,:/-])\d+(?:[.,:\-/]\d+)*(?![\w])/g,C=/^\s*\d+[.)]\s/gm;function A(e){let i=[...e.matchAll(d)].map(s=>s[0].replace(/[.,;:!?'"]+$/,"")),r=[...e.matchAll(y)].map(s=>s[1].trim()),n=e.replace(d," ").replace(y," ").replace(C," "),o=[...n.matchAll(w)].map(s=>s[0].toLowerCase()),c=[...n.replace(w," ").matchAll(k)].map(s=>v(s[0]));return{commits:m(o),urls:m(i),wikilinks:m(r),numbers:m(c)}}function R(e,i){let r=A(e),n=A(i),o=i.toLowerCase(),a=[];for(let t of r.commits)!o.includes(t)&&!n.commits.some(l=>l.startsWith(t)||t.startsWith(l))&&a.push(`commit ${t}`);let c=t=>t.toLowerCase().replace(/\/+$/,""),s=new Set(n.urls.map(c));for(let t of r.urls)s.has(c(t))||a.push(`link ${t}`);let f=new Set(n.wikilinks.map(t=>t.toLowerCase()));for(let t of r.wikilinks)f.has(t.toLowerCase())||a.push(`link [[${t}]]`);let h=new Set(n.numbers);for(let t of r.numbers)h.has(t)||a.push(`number ${t}`);return a}function v(e){return/^\d{1,3}(,\d{3})+$/.test(e)?e.replace(/,/g,""):e}function m(e){return[...new Set(e)]}function L(e,i){if(i.some(n=>n.path===e.path))return e.path;let r=b(e.title);return r?i.find(n=>b(n.title)===r)?.path??e.path:e.path}function b(e){return(e||"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()}export{$ as a,x as b,A as c,R as d,L as e};
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-K3623S4U.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{
|
|
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{Lb as tt,Mb as nt}from"./chunk-SNYAM7YB.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-KB5JMDGS.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-KB5JMDGS.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-OVB3LW6L.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-2KYGPVTX.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-KB5JMDGS.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-OXTFAV2A.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-K3623S4U.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-QABY3WEM.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{
|
|
1
|
+
import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{fa as ne,ga as re,ia as oe,ja as ie,pa as I,ua as Je}from"./chunk-SNYAM7YB.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-R3TH2OG7.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{X as y,Z as v,da as w,ea as C,ga as E,ha as R,ia as I}from"./chunk-SNYAM7YB.js";I();v();var L=1e4,T=["issues","prs","all"],W=/^[\w.-]+(?:\/[\w.-]+)+$/,m=e=>typeof e=="string"?e.trim():"";function f(e){let t=m(e.provider).toLowerCase();if(t!=="github"&&t!=="gitlab")return"count.provider must be github or gitlab";let r=m(e.project),n=r.split("/");if(!W.test(r)||n.some(o=>o==="."||o==="..")||t==="github"&&n.length!==2)return t==="github"?'count.project must be "owner/repo"':'count.project must be "group/project"';let s=(m(e.what)||"issues").toLowerCase();if(!T.includes(s))return`count.what must be one of ${T.join(", ")}`;let i=e.max===void 0||e.max===null||e.max===""?0:Number(e.max);return!Number.isInteger(i)||i<0?"count.max must be a whole number, 0 or more":{provider:t,project:r,what:s,max:i}}function S(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let r=f(t);return typeof r=="string"?null:r}catch{return null}}var _=e=>e==="issues"?"open issues":e==="prs"?"open pull requests":"open issues and pull requests";function $(e){return`${_(e.what)} in ${e.provider} ${e.project} \u2264 ${e.max}`}async function Y(e,t){if(!t)return{verdict:"unverifiable",detail:`no ${e.provider} connector on this node`};try{let r=e.what==="all"?["issues","prs"]:[e.what],n=0;for(let i of r){let o=await t(e.provider,e.project,i);if(typeof o!="number")return{verdict:"unverifiable",detail:`${e.project}: ${o.error}`};n+=o}let s=`${n} ${_(e.what)} in ${e.project}`;return{verdict:n<=e.max?"met":"not_met",detail:s,count:n}}catch(r){return{verdict:"unverifiable",detail:`the count check failed: ${String(r?.message??r).slice(0,200)}`}}}function B(e,t=fetch){return async(r,n,s)=>{let i;if(r==="github"){let a=e.github;if(!a)return{error:"no github connector on this node (channels.github or requests.checkers.github)"};let d=encodeURIComponent(`repo:${n} is:open is:${s==="prs"?"pr":"issue"}`);i=`${a.apiUrl.replace(/\/$/,"")}/search/issues?q=${d}&per_page=1`}else{let a=e.gitlab;if(!a)return{error:"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)"};i=`${a.url.replace(/\/$/,"")}/api/v4/projects/${encodeURIComponent(n)}/${s==="prs"?"merge_requests":"issues"}?state=opened&per_page=1`}let o;try{o=await t(i,{headers:y(r,e),signal:AbortSignal.timeout(L)})}catch(a){return{error:`could not be reached: ${String(a?.message??a).slice(0,200)}`}}if(!o.ok)return{error:o.status===404?"not found (or not visible to the connector)":`HTTP ${o.status}`};if(r==="gitlab"){let a=Number(o.headers.get("x-total"));return Number.isInteger(a)&&a>=0?a:{error:"no X-Total in the answer"}}let c=await o.json().catch(()=>null),l=Number(c?.total_count);return Number.isInteger(l)&&l>=0?l:{error:"no total_count in the answer"}}}var F=["active","done","dropped"],Q=300,A=500;function ee(e,t=w,r=Date.now()){if(e&&typeof e=="object"&&!Array.isArray(e)&&String(e.kind).trim().toLowerCase()==="count"){let s=f(e);return typeof s=="string"?s:{kind:"count",...s}}let n=C(e,t,r);return typeof n!="string"?n:/^closeWhen(\.kind)? must be/.test(n)?"check must be an object with a kind: url, issue, git-ancestor, reply or count":n.replace(/^closeWhen/,"check")}function U(e){if(!e)return null;try{if(JSON.parse(e)?.kind==="count"){let t=S(e);return t?{kind:"count",...t}:null}}catch{return null}return R(e)}function j(e){return e.kind==="count"?$(e):E(e)}function k(e){return{id:e.id,title:e.title,ownerAgent:e.owner_agent??null,state:e.state,doneWhen:e.done_when??null,check:U(e.check_spec),evidence:e.evidence??null,lastCheck:e.last_check??null,lastCheckAt:e.last_check_at??null,createdAt:e.created_at,updatedAt:e.updated_at,closedAt:e.closed_at??null}}var N=class{constructor(t){this.db=t;t.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS goals (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
title TEXT NOT NULL,
|
|
5
|
+
owner_agent TEXT,
|
|
6
|
+
state TEXT NOT NULL DEFAULT 'active',
|
|
7
|
+
done_when TEXT,
|
|
8
|
+
check_spec TEXT,
|
|
9
|
+
evidence TEXT,
|
|
10
|
+
last_check TEXT,
|
|
11
|
+
last_check_at INTEGER,
|
|
12
|
+
created_at INTEGER NOT NULL,
|
|
13
|
+
updated_at INTEGER NOT NULL,
|
|
14
|
+
closed_at INTEGER
|
|
15
|
+
);
|
|
16
|
+
CREATE INDEX IF NOT EXISTS idx_goals_state ON goals(state);
|
|
17
|
+
`)}get(t){let r=this.db.prepare("SELECT * FROM goals WHERE id = ?").get(t);return r?k(r):null}list(t=F,r=200){let n=t.map(()=>"?").join(", ");return this.db.prepare(`SELECT * FROM goals WHERE state IN (${n}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...t,r).map(k)}ensure(t,r,n){return this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING").run(t.id,t.title,r,n,n),this.get(t.id)}upsert(t,r){let n=this.get(t.id);return n?this.db.prepare("UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?").run(t.title||n.title,t.ownerAgent!==void 0?t.ownerAgent:n.ownerAgent,t.doneWhen!==void 0?t.doneWhen:n.doneWhen,t.check!==void 0?t.check?JSON.stringify(t.check):null:n.check?JSON.stringify(n.check):null,r,t.id):this.db.prepare("INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)").run(t.id,t.title,t.ownerAgent??null,t.doneWhen??null,t.check?JSON.stringify(t.check):null,r,r),this.get(t.id)}close(t,r,n,s){return this.db.prepare("UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'").run(r,n?n.slice(0,A):null,s,s,t).changes>0}markChecked(t,r,n){this.db.prepare("UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?").run(r.slice(0,A),n,t)}dueChecks(t){return this.db.prepare("SELECT * FROM goals WHERE state = 'active' AND check_spec IS NOT NULL AND (last_check_at IS NULL OR last_check_at <= ?) ORDER BY last_check_at ASC LIMIT 50").all(t).map(k)}};async function te(e,t,r,n,s=()=>{}){let i=[];for(let o of e.dueChecks(n-r*6e4)){let c;try{c=await t(o.check)}catch(l){c={verdict:"unverifiable",detail:String(l?.message??l)}}e.markChecked(o.id,c.detail,n),c.verdict==="met"&&e.close(o.id,"done",`check: ${c.detail}`,n)?(i.push(o.id),s(`[goals] ${o.id} done: ${c.detail}`)):c.verdict==="unverifiable"&&s(`[goals] ${o.id}: check failed: ${c.detail}`)}return i}function ne(e,t){let r=[`[Goal] ${e.title} (${e.id}): ${e.state}${e.ownerAgent?`, owner ${e.ownerAgent}`:""}.`];return e.doneWhen&&r.push(`Done when: ${e.doneWhen}`),e.check&&r.push(`Check: ${j(e.check)}${e.lastCheck?`; last seen: ${e.lastCheck}${e.lastCheckAt?` (${new Date(e.lastCheckAt).toISOString().slice(0,16).replace("T"," ")} UTC)`:""}`:""}`),t&&r.push(`Requests under it: ${t.open} open, ${t.done} done.`),r.join(`
|
|
18
|
+
`)}var g="Africa/Tunis";function b(e,t=g){let r=Object.fromEntries(new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(new Date(e)).map(s=>[s.type,s.value])),n=(Number(r.hour)%24*3600+Number(r.minute)*60+Number(r.second))*1e3+e%1e3;return e-n}var M=(e,t)=>new Intl.DateTimeFormat("en-GB",{timeZone:t,hour12:!1,hour:"2-digit",minute:"2-digit"}).format(new Date(e));function q(e,t=10){let r=e.replace(/\s+/g," ").trim().split(" ");return r.slice(0,t).join(" ")+(r.length>t?" \u2026":"")}var H=new Set(["issue","idea","approval","erp","card"]);function oe(e,t={}){let r=e.map(n=>{let s=[],i=(o,c)=>{s.some(l=>l.kind===o&&l.ref===c)||s.push({kind:o,ref:c})};for(let o of n.links??[])H.has(o.kind)&&i(o.kind,o.ref);return n.home&&i(n.home.kind,n.home.link),t.hasPlan?.(n.id)&&i("plan",n.id),n.evidence&&i("evidence",n.evidence),{id:n.id,time:M(n.createdAt,t.zone??g),words:q(n.text),state:n.state,owner:n.agentId,landed:s,noHome:s.length===0&&n.state!=="declined"&&n.state!=="dropped"}});return[...r.filter(n=>n.noHome),...r.filter(n=>!n.noHome)]}var x={timeZone:g,days:7},X=90,D=5,G=120,P=(e,t)=>new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e));function Z(e,t){return{day:P(e,t),start:e,asked:0,done:0,dropped:0,moving:0,waiting:0,stuck:0,rate:null,dropReasons:[],moreReasons:0,resent:0,resentDone:0}}function ie(e,t={}){let r=t.zone??x.timeZone,n=Math.min(Math.max(Math.floor(t.days??x.days),1),X),s=t.now??Date.now(),i=[b(s,r)];for(;i.length<n;)i.unshift(b(i[0]-1,r));let o=i.map(a=>Z(a,r)),c=o.map(()=>new Map),l=0;for(let a of e.flowRows(i[0])){for(;l+1<o.length&&a.createdAt>=o[l+1].start;)l++;let d=o[l];if(d.asked++,a.state==="done")d.done++;else if(a.state==="declined"||a.state==="dropped"){d.dropped++;let p=(a.closeReason??"").replace(/\s+/g," ").trim(),u=p.length>G?`${p.slice(0,G-1)}\u2026`:p||"no reason given";c[l].set(u,(c[l].get(u)??0)+1)}else a.state==="in_progress"||a.state==="waiting_other"?d.moving++:a.state==="waiting_owner"?d.waiting++:a.state==="needs_attention"&&d.stuck++;a.resentAt!==null&&(d.resent++,a.state==="done"&&d.resentDone++)}return o.forEach((a,d)=>{a.rate=a.asked?(a.done+a.dropped)/a.asked:null;let p=[...c[d]].sort((u,h)=>h[1]-u[1]);a.dropReasons=p.slice(0,D).map(([u,h])=>({reason:u,count:h})),a.moreReasons=p.slice(D).reduce((u,[,h])=>u+h,0)}),{zone:r,days:o,today:o[o.length-1]}}var O=e=>e===null?"\u2013":`${Math.round(e*100)}%`;function ce(e){let t=e.today,r=[`Today (${t.day}, ${e.zone}): ${t.asked?`${t.done+t.dropped} of ${t.asked} closed, ${O(t.rate)}`:"nothing asked yet"}.`,` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.`+(t.resent?` ${t.resent} resent once on its own, ${t.resentDone} of them done.`:"")];if(t.dropReasons.length){r.push(" Dropped because:");for(let n of t.dropReasons)r.push(` ${n.count} \xD7 ${n.reason}`);t.moreReasons&&r.push(` ${t.moreReasons} more`)}if(e.days.length>1){r.push("","Day asked done dropped moving waiting stuck rate");for(let n of e.days){let s=[n.asked,n.done,n.dropped,n.moving,n.waiting,n.stuck].map(String);r.push(`${n.day} ${s[0].padStart(5)} ${s[1].padStart(4)} ${s[2].padStart(7)} ${s[3].padStart(6)} ${s[4].padStart(7)} ${s[5].padStart(5)} ${O(n.rate).padStart(4)}`)}}return r.join(`
|
|
19
|
+
`)}export{f as a,S as b,$ as c,Y as d,B as e,Q as f,A as g,ee as h,j as i,N as j,te as k,ne as l,b as m,oe as n,x as o,X as p,ie as q,ce as r};
|
|
20
|
+
//# sourceMappingURL=chunk-RC3QYH2J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/requests/goal-store.ts","../src/requests/checkers/count.ts","../src/requests/today.ts","../src/requests/flow.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { DEFAULT_CHECKER_SETTINGS, describeCloseWhen, parseCloseWhen, readCloseWhen, type CheckerSettings, type CheckResult, type CloseWhen } from \"./checkers\"\nimport { describeCount, parseCountSpec, readCountSpec, type CountSpec } from \"./checkers/count\"\nimport type { RequestGoal } from \"./goals\"\n\n// --- A goal as its own record (#1568 part 3) ---\n//\n// Until now a goal was a label on a request: it existed while a request\n// named it (#1168). Crons need something lasting to point at, so a goal is\n// now a row of its own: a title, an owner agent, a state (active, done or\n// dropped), what \"done\" means in words, and optionally a check the daemon\n// runs itself (any loop checker, or an open count). Requests keep their\n// goal_id; accepting a request with a goal makes the record when it is\n// new. A goal is done when its check is met, or when its owner closes it.\n// A closed goal stays closed: a new goal needs a new id.\n\nexport const GOAL_STATES = [\"active\", \"done\", \"dropped\"] as const\nexport type GoalState = (typeof GOAL_STATES)[number]\n\nexport const DONE_WHEN_MAX = 300\nexport const GOAL_EVIDENCE_MAX = 500\n\n/** What closes a goal: a loop checker, or an open count (#1568). */\nexport type GoalCheck = CloseWhen | ({ kind: \"count\" } & CountSpec)\n\nexport interface GoalRecord {\n id: string\n title: string\n /** The agent that keeps it moving and may close it. */\n ownerAgent: string | null\n state: GoalState\n doneWhen: string | null\n check: GoalCheck | null\n /** Why it closed: the check's evidence, or the owner's words. */\n evidence: string | null\n /** What the check saw last time, and when. */\n lastCheck: string | null\n lastCheckAt: number | null\n createdAt: number\n updatedAt: number\n closedAt: number | null\n}\n\n/** Check the `check` (or closeWhen) of a goal: a spec, or why it is refused. */\nexport function parseGoalCheck(v: unknown, settings: CheckerSettings = DEFAULT_CHECKER_SETTINGS, now = Date.now()): GoalCheck | string {\n if (v && typeof v === \"object\" && !Array.isArray(v) && String((v as any).kind).trim().toLowerCase() === \"count\") {\n const spec = parseCountSpec(v as Record<string, unknown>)\n return typeof spec === \"string\" ? spec : { kind: \"count\", ...spec }\n }\n const spec = parseCloseWhen(v, settings, now)\n if (typeof spec !== \"string\") return spec\n return /^closeWhen(\\.kind)? must be/.test(spec) ? \"check must be an object with a kind: url, issue, git-ancestor, reply or count\" : spec.replace(/^closeWhen/, \"check\")\n}\n\nfunction readGoalCheck(json: string | null): GoalCheck | null {\n if (!json) return null\n try {\n if (JSON.parse(json)?.kind === \"count\") {\n const spec = readCountSpec(json)\n return spec ? { kind: \"count\", ...spec } : null\n }\n } catch {\n return null\n }\n return readCloseWhen(json)\n}\n\nexport function describeGoalCheck(check: GoalCheck): string {\n return check.kind === \"count\" ? describeCount(check) : describeCloseWhen(check)\n}\n\nfunction toGoal(r: any): GoalRecord {\n return {\n id: r.id, title: r.title, ownerAgent: r.owner_agent ?? null, state: r.state, doneWhen: r.done_when ?? null,\n check: readGoalCheck(r.check_spec), evidence: r.evidence ?? null, lastCheck: r.last_check ?? null, lastCheckAt: r.last_check_at ?? null,\n createdAt: r.created_at, updatedAt: r.updated_at, closedAt: r.closed_at ?? null,\n }\n}\n\nexport interface GoalInput extends RequestGoal {\n ownerAgent?: string | null\n doneWhen?: string | null\n check?: GoalCheck | null\n}\n\nexport class GoalStore {\n constructor(private db: Database.Database) {\n db.exec(`\n CREATE TABLE IF NOT EXISTS goals (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n owner_agent TEXT,\n state TEXT NOT NULL DEFAULT 'active',\n done_when TEXT,\n check_spec TEXT,\n evidence TEXT,\n last_check TEXT,\n last_check_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n closed_at INTEGER\n );\n CREATE INDEX IF NOT EXISTS idx_goals_state ON goals(state);\n `)\n }\n\n get(id: string): GoalRecord | null {\n const row = this.db.prepare(\"SELECT * FROM goals WHERE id = ?\").get(id)\n return row ? toGoal(row) : null\n }\n\n /** Most recently updated first. */\n list(states: readonly GoalState[] = GOAL_STATES, limit = 200): GoalRecord[] {\n const marks = states.map(() => \"?\").join(\", \")\n return (this.db.prepare(`SELECT * FROM goals WHERE state IN (${marks}) ORDER BY updated_at DESC, rowid DESC LIMIT ?`).all(...states, limit) as any[]).map(toGoal)\n }\n\n /** The record of a goal a request names on accept: made when it is new,\n * left as it is otherwise (its title and owner are the record's). */\n ensure(goal: RequestGoal, ownerAgent: string | null, now: number): GoalRecord {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?) ON CONFLICT(id) DO NOTHING\",\n ).run(goal.id, goal.title, ownerAgent, now, now)\n return this.get(goal.id)!\n }\n\n /** Make a goal, or change an active one: only the fields given change. */\n upsert(input: GoalInput, now: number): GoalRecord {\n const had = this.get(input.id)\n if (!had) {\n this.db.prepare(\n \"INSERT INTO goals (id, title, owner_agent, state, done_when, check_spec, created_at, updated_at) VALUES (?, ?, ?, 'active', ?, ?, ?, ?)\",\n ).run(input.id, input.title, input.ownerAgent ?? null, input.doneWhen ?? null, input.check ? JSON.stringify(input.check) : null, now, now)\n } else {\n this.db.prepare(\n \"UPDATE goals SET title = ?, owner_agent = ?, done_when = ?, check_spec = ?, updated_at = ? WHERE id = ?\",\n ).run(\n input.title || had.title,\n input.ownerAgent !== undefined ? input.ownerAgent : had.ownerAgent,\n input.doneWhen !== undefined ? input.doneWhen : had.doneWhen,\n input.check !== undefined ? (input.check ? JSON.stringify(input.check) : null) : (had.check ? JSON.stringify(had.check) : null),\n now, input.id,\n )\n }\n return this.get(input.id)!\n }\n\n /** Close an active goal as done or dropped. False when it was not active. */\n close(id: string, state: Exclude<GoalState, \"active\">, evidence: string | null, now: number): boolean {\n const res = this.db.prepare(\n \"UPDATE goals SET state = ?, evidence = ?, closed_at = ?, updated_at = ? WHERE id = ? AND state = 'active'\",\n ).run(state, evidence ? evidence.slice(0, GOAL_EVIDENCE_MAX) : null, now, now, id)\n return res.changes > 0\n }\n\n /** What the check saw: not a change of the goal, so updated_at stays. */\n markChecked(id: string, detail: string, now: number): void {\n this.db.prepare(\"UPDATE goals SET last_check = ?, last_check_at = ? WHERE id = ?\").run(detail.slice(0, GOAL_EVIDENCE_MAX), now, id)\n }\n\n /** Active goals with a check last run at `before` or earlier (or never). */\n dueChecks(before: number): GoalRecord[] {\n return (this.db.prepare(\n \"SELECT * FROM goals WHERE state = 'active' AND check_spec IS NOT NULL AND (last_check_at IS NULL OR last_check_at <= ?) ORDER BY last_check_at ASC LIMIT 50\",\n ).all(before) as any[]).map(toGoal)\n }\n}\n\nexport type GoalChecker = (check: GoalCheck) => Promise<CheckResult>\n\n/** Run the check of every active goal not checked for `everyMinutes`.\n * Met closes the goal as done with the check's evidence. Returns the ids\n * closed. One goal's failure never stops the others. */\nexport async function checkGoals(store: GoalStore, check: GoalChecker, everyMinutes: number, now: number, log: (msg: string) => void = () => {}): Promise<string[]> {\n const closed: string[] = []\n for (const g of store.dueChecks(now - everyMinutes * 60_000)) {\n let res: CheckResult\n try {\n res = await check(g.check!)\n } catch (e: any) {\n res = { verdict: \"unverifiable\", detail: String(e?.message ?? e) }\n }\n store.markChecked(g.id, res.detail, now)\n if (res.verdict === \"met\" && store.close(g.id, \"done\", `check: ${res.detail}`, now)) {\n closed.push(g.id)\n log(`[goals] ${g.id} done: ${res.detail}`)\n } else if (res.verdict === \"unverifiable\") {\n log(`[goals] ${g.id}: check failed: ${res.detail}`)\n }\n }\n return closed\n}\n\n/** The goal's state for a cron prompt or a plan turn: a few lines. */\nexport function goalBrief(g: GoalRecord, counts?: { open: number; done: number } | null): string {\n const lines = [`[Goal] ${g.title} (${g.id}): ${g.state}${g.ownerAgent ? `, owner ${g.ownerAgent}` : \"\"}.`]\n if (g.doneWhen) lines.push(`Done when: ${g.doneWhen}`)\n if (g.check) lines.push(`Check: ${describeGoalCheck(g.check)}${g.lastCheck ? `; last seen: ${g.lastCheck}${g.lastCheckAt ? ` (${new Date(g.lastCheckAt).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC)` : \"\"}` : \"\"}`)\n if (counts) lines.push(`Requests under it: ${counts.open} open, ${counts.done} done.`)\n return lines.join(\"\\n\")\n}\n","import type { CheckResult } from \"./index\"\nimport { forgeHeaders, type ForgeConnectors } from \"./issue\"\n\n// --- count: how many issues or pull requests a project has open (#1568) ---\n//\n// A plan step can carry a count check (\"open issues in owner/repo = 0\").\n// The plan check reads the count through the GitHub or GitLab connector,\n// marks the step done when it is at or under `max`, and keeps the last\n// count so a turn that brought it down counts as progress. One read per\n// kind: GitHub's search total, GitLab's X-Total header.\n\nexport type CountWhat = \"issues\" | \"prs\" | \"all\"\n\nexport interface CountSpec {\n provider: \"github\" | \"gitlab\"\n /** \"owner/repo\" on GitHub, \"group/project\" on GitLab. */\n project: string\n what: CountWhat\n /** Done at this count or under. */\n max: number\n}\n\n/** Reads one open count, or says why it could not. */\nexport type ForgeCounter = (provider: \"github\" | \"gitlab\", project: string, kind: \"issues\" | \"prs\") => Promise<number | { error: string }>\n\nconst TIMEOUT_MS = 10_000\nconst WHATS: readonly CountWhat[] = [\"issues\", \"prs\", \"all\"]\nconst PROJECT_RE = /^[\\w.-]+(?:\\/[\\w.-]+)+$/\n\nconst str = (v: unknown) => (typeof v === \"string\" ? v.trim() : \"\")\n\nexport function parseCountSpec(raw: Record<string, unknown>): CountSpec | string {\n const provider = str(raw.provider).toLowerCase()\n if (provider !== \"github\" && provider !== \"gitlab\") return \"count.provider must be github or gitlab\"\n const project = str(raw.project)\n const parts = project.split(\"/\")\n if (!PROJECT_RE.test(project) || parts.some((p) => p === \".\" || p === \"..\") || (provider === \"github\" && parts.length !== 2)) {\n return provider === \"github\" ? 'count.project must be \"owner/repo\"' : 'count.project must be \"group/project\"'\n }\n const what = (str(raw.what) || \"issues\").toLowerCase()\n if (!(WHATS as readonly string[]).includes(what)) return `count.what must be one of ${WHATS.join(\", \")}`\n const max = raw.max === undefined || raw.max === null || raw.max === \"\" ? 0 : Number(raw.max)\n if (!Number.isInteger(max) || max < 0) return \"count.max must be a whole number, 0 or more\"\n return { provider, project, what: what as CountWhat, max }\n}\n\n/** A stored spec read back. Null when it is not one. */\nexport function readCountSpec(json: string | null | undefined): CountSpec | null {\n if (!json) return null\n try {\n const v = JSON.parse(json)\n if (!v || typeof v !== \"object\") return null\n const spec = parseCountSpec(v)\n return typeof spec === \"string\" ? null : spec\n } catch {\n return null\n }\n}\n\nconst whatWords = (w: CountWhat) => (w === \"issues\" ? \"open issues\" : w === \"prs\" ? \"open pull requests\" : \"open issues and pull requests\")\n\nexport function describeCount(spec: CountSpec): string {\n return `${whatWords(spec.what)} in ${spec.provider} ${spec.project} ≤ ${spec.max}`\n}\n\n/** The count now, and whether it is at or under max. Never throws. */\nexport async function checkCount(spec: CountSpec, counter: ForgeCounter | undefined): Promise<CheckResult & { count?: number }> {\n if (!counter) return { verdict: \"unverifiable\", detail: `no ${spec.provider} connector on this node` }\n try {\n const kinds: Array<\"issues\" | \"prs\"> = spec.what === \"all\" ? [\"issues\", \"prs\"] : [spec.what]\n let count = 0\n for (const kind of kinds) {\n const n = await counter(spec.provider, spec.project, kind)\n if (typeof n !== \"number\") return { verdict: \"unverifiable\", detail: `${spec.project}: ${n.error}` }\n count += n\n }\n const detail = `${count} ${whatWords(spec.what)} in ${spec.project}`\n return { verdict: count <= spec.max ? \"met\" : \"not_met\", detail, count }\n } catch (e: any) {\n return { verdict: \"unverifiable\", detail: `the count check failed: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n}\n\n/** The counter over the REST APIs of GitHub and GitLab. */\nexport function forgeCounter(connectors: ForgeConnectors, doFetch: typeof fetch = fetch): ForgeCounter {\n return async (provider, project, kind) => {\n let url: string\n if (provider === \"github\") {\n const c = connectors.github\n if (!c) return { error: \"no github connector on this node (channels.github or requests.checkers.github)\" }\n const q = encodeURIComponent(`repo:${project} is:open is:${kind === \"prs\" ? \"pr\" : \"issue\"}`)\n url = `${c.apiUrl.replace(/\\/$/, \"\")}/search/issues?q=${q}&per_page=1`\n } else {\n const c = connectors.gitlab\n if (!c) return { error: \"no gitlab connector on this node (channels.gitlab or requests.checkers.gitlab)\" }\n url = `${c.url.replace(/\\/$/, \"\")}/api/v4/projects/${encodeURIComponent(project)}/${kind === \"prs\" ? \"merge_requests\" : \"issues\"}?state=opened&per_page=1`\n }\n let res: Response\n try {\n res = await doFetch(url, { headers: forgeHeaders(provider, connectors), signal: AbortSignal.timeout(TIMEOUT_MS) })\n } catch (e: any) {\n return { error: `could not be reached: ${String(e?.message ?? e).slice(0, 200)}` }\n }\n if (!res.ok) return { error: res.status === 404 ? \"not found (or not visible to the connector)\" : `HTTP ${res.status}` }\n if (provider === \"gitlab\") {\n const total = Number(res.headers.get(\"x-total\"))\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no X-Total in the answer\" }\n }\n const body: any = await res.json().catch(() => null)\n const total = Number(body?.total_count)\n return Number.isInteger(total) && total >= 0 ? total : { error: \"no total_count in the answer\" }\n }\n}\n","import type { RequestRecord } from \"./store\"\n\n// --- \"What did I ask today, and where did it land\" (#394, 1c C) ---\n//\n// One row per request made since 00:00 Tunis: time, first words, state,\n// owner, and where it landed. A request with nowhere it landed goes red, at\n// the top. No model: the Secretary reads it out, the Desk shows it.\n\nexport const TODAY_ZONE = \"Africa/Tunis\"\n\nexport interface Landed { kind: string; ref: string }\n\nexport interface TodayRow {\n id: string\n /** HH:MM, Tunis time. */\n time: string\n words: string\n state: string\n owner: string\n landed: Landed[]\n noHome: boolean\n}\n\n/** Epoch ms of the last 00:00 in `zone` at or before `now`. */\nexport function startOfDay(now: number, zone = TODAY_ZONE): number {\n const parts = Object.fromEntries(\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\" })\n .formatToParts(new Date(now)).map((p) => [p.type, p.value]),\n )\n const elapsed = ((Number(parts.hour) % 24) * 3600 + Number(parts.minute) * 60 + Number(parts.second)) * 1000 + (now % 1000)\n return now - elapsed\n}\n\nconst clock = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: zone, hour12: false, hour: \"2-digit\", minute: \"2-digit\" }).format(new Date(ms))\n\n/** The first `n` words of a request, on one line. */\nexport function firstWords(text: string, n = 10): string {\n const words = text.replace(/\\s+/g, \" \").trim().split(\" \")\n return words.slice(0, n).join(\" \") + (words.length > n ? \" …\" : \"\")\n}\n\n/** Link kinds that say where the work lives: a home (#394), or an\n * approval card put to the owner. Runs, delegations and workflows do not. */\nconst LANDING_LINKS = new Set([\"issue\", \"idea\", \"approval\", \"erp\", \"card\"])\n\nexport function todayRows(\n items: Array<RequestRecord & { links?: Array<{ kind: string; ref: string }> }>,\n opts: { hasPlan?: (id: string) => boolean; zone?: string } = {},\n): TodayRow[] {\n const rows = items.map((r): TodayRow => {\n const landed: Landed[] = []\n const add = (kind: string, ref: string) => { if (!landed.some((l) => l.kind === kind && l.ref === ref)) landed.push({ kind, ref }) }\n for (const l of r.links ?? []) if (LANDING_LINKS.has(l.kind)) add(l.kind, l.ref)\n if (r.home) add(r.home.kind, r.home.link)\n if (opts.hasPlan?.(r.id)) add(\"plan\", r.id)\n if (r.evidence) add(\"evidence\", r.evidence)\n return {\n id: r.id, time: clock(r.createdAt, opts.zone ?? TODAY_ZONE), words: firstWords(r.text), state: r.state, owner: r.agentId,\n // Declined or dropped: closed on purpose, nothing was to land.\n landed, noHome: landed.length === 0 && r.state !== \"declined\" && r.state !== \"dropped\",\n }\n })\n // Red first; each group in the order asked.\n return [...rows.filter((r) => r.noHome), ...rows.filter((r) => !r.noHome)]\n}\n","import { startOfDay, TODAY_ZONE } from \"./today\"\nimport type { RequestStore } from \"./store\"\n\n// --- The daily flow rate of requests (#1542) ---\n//\n// Every request asked in a day (the owner's day, `requests.flow.timeZone`),\n// and where each one stands now:\n// asked requests made that day (candidates left out)\n// done closed as done\n// dropped declined or dropped: each carries its reason, listed beside\n// the rate so a wrong drop can be seen\n// moving in progress, or waiting on another agent\n// waiting waiting on the owner\n// stuck needs attention\n// rate (done + dropped) / asked; null on a day nothing was asked\n// resent resent once by the requests check (resend.ts), and how many\n// of those are done now\n// Read only, recomputed on every call: a request closed later moves the\n// day it was asked. No model.\n\nexport interface FlowSettings {\n timeZone: string\n days: number\n}\n\nexport const DEFAULT_FLOW: FlowSettings = { timeZone: TODAY_ZONE, days: 7 }\n\n/** Days one report may cover: closed requests age out after retentionDays. */\nexport const FLOW_DAYS_MAX = 90\n\n/** Drop reasons listed per day. */\nconst REASONS_MAX = 5\nconst REASON_WORDS = 120\n\nexport interface FlowDay {\n /** YYYY-MM-DD in the zone. */\n day: string\n /** Epoch ms of the day's 00:00 in the zone. */\n start: number\n asked: number\n done: number\n dropped: number\n moving: number\n waiting: number\n stuck: number\n rate: number | null\n /** Most frequent reasons first; `more` counts the drops not listed. */\n dropReasons: Array<{ reason: string; count: number }>\n moreReasons: number\n resent: number\n resentDone: number\n}\n\nexport interface FlowReport {\n zone: string\n /** Oldest first; the last one is today. */\n days: FlowDay[]\n today: FlowDay\n}\n\nconst dayKey = (ms: number, zone: string) =>\n new Intl.DateTimeFormat(\"en-CA\", { timeZone: zone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).format(new Date(ms))\n\nfunction emptyDay(start: number, zone: string): FlowDay {\n return { day: dayKey(start, zone), start, asked: 0, done: 0, dropped: 0, moving: 0, waiting: 0, stuck: 0, rate: null, dropReasons: [], moreReasons: 0, resent: 0, resentDone: 0 }\n}\n\nexport function flowReport(store: RequestStore, opts: { days?: number; zone?: string; now?: number } = {}): FlowReport {\n const zone = opts.zone ?? DEFAULT_FLOW.timeZone\n const count = Math.min(Math.max(Math.floor(opts.days ?? DEFAULT_FLOW.days), 1), FLOW_DAYS_MAX)\n const now = opts.now ?? Date.now()\n // Walked back one 00:00 at a time: a day across a clock change is 23 or 25 h.\n const starts = [startOfDay(now, zone)]\n while (starts.length < count) starts.unshift(startOfDay(starts[0] - 1, zone))\n const days = starts.map((s) => emptyDay(s, zone))\n const reasons = days.map(() => new Map<string, number>())\n let i = 0\n for (const r of store.flowRows(starts[0])) {\n while (i + 1 < days.length && r.createdAt >= days[i + 1].start) i++\n const d = days[i]\n d.asked++\n if (r.state === \"done\") d.done++\n else if (r.state === \"declined\" || r.state === \"dropped\") {\n d.dropped++\n const why = (r.closeReason ?? \"\").replace(/\\s+/g, \" \").trim()\n const key = why.length > REASON_WORDS ? `${why.slice(0, REASON_WORDS - 1)}…` : why || \"no reason given\"\n reasons[i].set(key, (reasons[i].get(key) ?? 0) + 1)\n } else if (r.state === \"in_progress\" || r.state === \"waiting_other\") d.moving++\n else if (r.state === \"waiting_owner\") d.waiting++\n else if (r.state === \"needs_attention\") d.stuck++\n if (r.resentAt !== null) {\n d.resent++\n if (r.state === \"done\") d.resentDone++\n }\n }\n days.forEach((d, n) => {\n d.rate = d.asked ? (d.done + d.dropped) / d.asked : null\n const sorted = [...reasons[n]].sort((a, b) => b[1] - a[1])\n d.dropReasons = sorted.slice(0, REASONS_MAX).map(([reason, c]) => ({ reason, count: c }))\n d.moreReasons = sorted.slice(REASONS_MAX).reduce((sum, [, c]) => sum + c, 0)\n })\n return { zone, days, today: days[days.length - 1] }\n}\n\nconst pct = (rate: number | null) => (rate === null ? \"–\" : `${Math.round(rate * 100)}%`)\n\n/** Today's figure, then one line per day, oldest first: what the CLI\n * prints and the agentx_request tool answers. */\nexport function describeFlow(f: FlowReport): string {\n const t = f.today\n const lines = [\n `Today (${t.day}, ${f.zone}): ${t.asked ? `${t.done + t.dropped} of ${t.asked} closed, ${pct(t.rate)}` : \"nothing asked yet\"}.`,\n ` ${t.done} done, ${t.dropped} dropped, ${t.moving} moving, ${t.waiting} waiting on the owner, ${t.stuck} stuck.` +\n (t.resent ? ` ${t.resent} resent once on its own, ${t.resentDone} of them done.` : \"\"),\n ]\n if (t.dropReasons.length) {\n lines.push(\" Dropped because:\")\n for (const r of t.dropReasons) lines.push(` ${r.count} × ${r.reason}`)\n if (t.moreReasons) lines.push(` ${t.moreReasons} more`)\n }\n if (f.days.length > 1) {\n lines.push(\"\", \"Day asked done dropped moving waiting stuck rate\")\n for (const d of f.days) {\n const cells = [d.asked, d.done, d.dropped, d.moving, d.waiting, d.stuck].map(String)\n lines.push(`${d.day} ${cells[0].padStart(5)} ${cells[1].padStart(4)} ${cells[2].padStart(7)} ${cells[3].padStart(6)} ${cells[4].padStart(7)} ${cells[5].padStart(5)} ${pct(d.rate).padStart(4)}`)\n }\n }\n return lines.join(\"\\n\")\n}\n"],"mappings":"uFACAA,ICAAC,IAwBA,IAAMC,EAAa,IACbC,EAA8B,CAAC,SAAU,MAAO,KAAK,EACrDC,EAAa,0BAEbC,EAAOC,GAAgB,OAAOA,GAAM,SAAWA,EAAE,KAAK,EAAI,GAEzD,SAASC,EAAeC,EAAkD,CAC/E,IAAMC,EAAWJ,EAAIG,EAAI,QAAQ,EAAE,YAAY,EAC/C,GAAIC,IAAa,UAAYA,IAAa,SAAU,MAAO,0CAC3D,IAAMC,EAAUL,EAAIG,EAAI,OAAO,EACzBG,EAAQD,EAAQ,MAAM,GAAG,EAC/B,GAAI,CAACN,EAAW,KAAKM,CAAO,GAAKC,EAAM,KAAMC,GAAMA,IAAM,KAAOA,IAAM,IAAI,GAAMH,IAAa,UAAYE,EAAM,SAAW,EACxH,OAAOF,IAAa,SAAW,qCAAuC,wCAExE,IAAMI,GAAQR,EAAIG,EAAI,IAAI,GAAK,UAAU,YAAY,EACrD,GAAI,CAAEL,EAA4B,SAASU,CAAI,EAAG,MAAO,6BAA6BV,EAAM,KAAK,IAAI,IACrG,IAAMW,EAAMN,EAAI,MAAQ,QAAaA,EAAI,MAAQ,MAAQA,EAAI,MAAQ,GAAK,EAAI,OAAOA,EAAI,GAAG,EAC5F,MAAI,CAAC,OAAO,UAAUM,CAAG,GAAKA,EAAM,EAAU,8CACvC,CAAE,SAAAL,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E,OAAS,IAAI,EAAE,kCAAkC,EAAE,2BAA6B,GACvF,EACA,GAAI,EAAE,YAAY,OAAQ,CACxBI,EAAM,KAAK,oBAAoB,EAC/B,QAAWf,KAAK,EAAE,YAAae,EAAM,KAAK,OAAOf,EAAE,cAAWA,EAAE,QAAQ,EACpE,EAAE,aAAae,EAAM,KAAK,OAAO,EAAE,kBAAkB,EAE3D,GAAID,EAAE,KAAK,OAAS,EAAG,CACrBC,EAAM,KAAK,GAAI,gEAAgE,EAC/E,QAAWZ,KAAKW,EAAE,KAAM,CACtB,IAAME,EAAQ,CAACb,EAAE,MAAOA,EAAE,KAAMA,EAAE,QAASA,EAAE,OAAQA,EAAE,QAASA,EAAE,KAAK,EAAE,IAAI,MAAM,EACnFY,EAAM,KAAK,GAAGZ,EAAE,QAAQa,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAMA,EAAM,CAAC,EAAE,SAAS,CAAC,MAAML,EAAIR,EAAE,IAAI,EAAE,SAAS,CAAC,GAAG,GAG3M,OAAOY,EAAM,KAAK;AAAA,CAAI,CACxB","names":["init_checkers","init_issue","TIMEOUT_MS","WHATS","PROJECT_RE","str","v","parseCountSpec","raw","provider","project","parts","p","what","max","readCountSpec","json","spec","whatWords","w","describeCount","checkCount","counter","kinds","count","kind","n","detail","e","forgeCounter","connectors","doFetch","url","c","q","res","forgeHeaders","total","body","GOAL_STATES","DONE_WHEN_MAX","GOAL_EVIDENCE_MAX","parseGoalCheck","v","settings","DEFAULT_CHECKER_SETTINGS","now","spec","parseCountSpec","parseCloseWhen","readGoalCheck","json","readCountSpec","readCloseWhen","describeGoalCheck","check","describeCount","describeCloseWhen","toGoal","r","GoalStore","db","id","row","states","limit","marks","goal","ownerAgent","input","had","state","evidence","detail","before","checkGoals","store","everyMinutes","log","closed","g","res","e","goalBrief","counts","lines","TODAY_ZONE","startOfDay","now","zone","parts","p","elapsed","clock","ms","firstWords","text","n","words","LANDING_LINKS","todayRows","items","opts","rows","r","landed","add","kind","ref","l","DEFAULT_FLOW","TODAY_ZONE","FLOW_DAYS_MAX","REASONS_MAX","REASON_WORDS","dayKey","ms","zone","emptyDay","start","flowReport","store","opts","count","now","starts","startOfDay","days","s","reasons","i","r","why","key","d","n","sorted","a","b","reason","c","sum","pct","rate","describeFlow","f","lines","cells"]}
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-D5HHCFCC.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-RLI32DLG.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-3LMBT5LK.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-SK7M6PS6.js.map
|