agentix-cli 0.135.0 → 0.136.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-4UVAI5C5.js → App-D6W6IV2L.js} +2 -2
- package/dist/{ChatApp-COO67WIR.js → ChatApp-X7TNCFGW.js} +2 -2
- package/dist/{absorb-eval-WY3YMLS4.js → absorb-eval-COPVH2M2.js} +2 -2
- package/dist/{agent-3R5NY7I3.js → agent-VCGAUBER.js} +2 -2
- package/dist/{board-dashboard-U3ZSCO62.js → board-dashboard-JZM3FQNV.js} +4 -4
- package/dist/{board-dashboard-U3ZSCO62.js.map → board-dashboard-JZM3FQNV.js.map} +1 -1
- package/dist/chunk-4ZWZ42YE.js +5 -0
- package/dist/{chunk-KXR6GVL7.js.map → chunk-4ZWZ42YE.js.map} +1 -1
- package/dist/{chunk-DYGQF3MI.js → chunk-54OORW5I.js} +2 -2
- package/dist/chunk-54OORW5I.js.map +1 -0
- package/dist/{chunk-RVEMX5MJ.js → chunk-5J5USW2O.js} +2 -2
- package/dist/{chunk-3XVST5XX.js → chunk-5X37CXJF.js} +2 -2
- package/dist/{chunk-4XMALK7X.js → chunk-66DPMVUC.js} +2 -2
- package/dist/{chunk-SSQMFHSM.js → chunk-AK3XOA5N.js} +2 -2
- package/dist/chunk-AKWBDCMU.js +4 -0
- package/dist/chunk-AKWBDCMU.js.map +1 -0
- package/dist/{chunk-6WF56ME6.js → chunk-C43E3YFT.js} +2 -2
- package/dist/{chunk-LU7GDHGD.js → chunk-EVTTAM7S.js} +2 -2
- package/dist/{chunk-K445URSN.js → chunk-FQLSV2C4.js} +2 -2
- package/dist/{chunk-FWDRBUMS.js → chunk-GL3H7XMI.js} +2 -2
- package/dist/{chunk-ZGVVYJIK.js → chunk-H2N7DOPT.js} +2 -2
- package/dist/{chunk-BQIWMQNU.js → chunk-H4NSB54D.js} +2 -2
- package/dist/{chunk-XOUO4XNA.js → chunk-HEJTE7OC.js} +2 -2
- package/dist/{chunk-EEBK4F6E.js → chunk-HH7OFAEM.js} +2 -2
- package/dist/{chunk-QDWEM4DG.js → chunk-HZZW35FY.js} +2 -2
- package/dist/{chunk-RRGITX5B.js → chunk-IPMXIPTS.js} +2 -2
- package/dist/{chunk-MI7WOGH6.js → chunk-K75LFQE3.js} +2 -2
- package/dist/{chunk-ZFRXFUP7.js → chunk-KZXQD6ZK.js} +2 -2
- package/dist/{chunk-P3I7AATX.js → chunk-M5AHI2PZ.js} +2 -2
- package/dist/{chunk-5NT44FKL.js → chunk-M5B4QG6J.js} +2 -2
- package/dist/chunk-MTX4UPNB.js +3 -0
- package/dist/chunk-MTX4UPNB.js.map +1 -0
- package/dist/chunk-MWNCS57L.js +2 -0
- package/dist/chunk-MWNCS57L.js.map +1 -0
- package/dist/chunk-OISCRNMW.js +105 -0
- package/dist/chunk-OISCRNMW.js.map +1 -0
- package/dist/{chunk-ERULJ2ZL.js → chunk-OW5EXDVY.js} +2 -2
- package/dist/chunk-OWNQ2FD4.js +3 -0
- package/dist/chunk-OWNQ2FD4.js.map +1 -0
- package/dist/chunk-PE5V2LI7.js +2 -0
- package/dist/chunk-PE5V2LI7.js.map +1 -0
- package/dist/chunk-PV623BLN.js +55 -0
- package/dist/chunk-PV623BLN.js.map +1 -0
- package/dist/{chunk-L5UGH4T4.js → chunk-QCUJTAAZ.js} +6 -6
- package/dist/{chunk-GSKJ57XY.js → chunk-QTDKNJXD.js} +216 -216
- package/dist/chunk-QTDKNJXD.js.map +1 -0
- package/dist/{chunk-RGZARSHV.js → chunk-ROLSSYXE.js} +1 -1
- package/dist/{chunk-RGZARSHV.js.map → chunk-ROLSSYXE.js.map} +1 -1
- package/dist/{chunk-YA3P77LV.js → chunk-SKSYII3K.js} +2 -2
- package/dist/chunk-U6EJ53DA.js +16 -0
- package/dist/chunk-U6EJ53DA.js.map +1 -0
- package/dist/{chunk-WEPON4FP.js → chunk-UNIXYV3U.js} +2 -2
- package/dist/{chunk-SMAI7U6H.js → chunk-VA24JS2S.js} +2 -2
- package/dist/{chunk-LUYN6RAC.js → chunk-WRJFKA43.js} +2 -2
- package/dist/{chunk-H6VWU2HN.js → chunk-ZPJVDX2U.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-NFPBE6L4.js → client-SMOWSRJY.js} +2 -2
- package/dist/{config-GHMRBRDL.js → config-OGUDWYAA.js} +2 -2
- package/dist/{config-mutate-2XV27EFV.js → config-mutate-BH27TMWK.js} +2 -2
- package/dist/config-mutator-Q62AS2TR.js +2 -0
- package/dist/{contributions-KLRJ4ZXV.js → contributions-H6T65TCY.js} +2 -2
- package/dist/{contributions-KLRJ4ZXV.js.map → contributions-H6T65TCY.js.map} +1 -1
- package/dist/{doctor-UBXVMGJG.js → doctor-ZOXHT7ZQ.js} +2 -2
- package/dist/enrich-R2LIDLPZ.js +2 -0
- package/dist/event-levels-WOYYEWSZ.js +3 -0
- package/dist/event-levels-WOYYEWSZ.js.map +1 -0
- package/dist/fact-proposals-X2O4W7VN.js +2 -0
- package/dist/{follow-up-tool-EARVITTS.js → follow-up-tool-GUBBXNEZ.js} +2 -2
- package/dist/{grants-HIFE6L5N.js → grants-CEUGZBQ4.js} +2 -2
- package/dist/hub-IIW2GBO5.js +2 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/ledger-P62U3FHT.js +2 -0
- package/dist/load-LQ2I2PQI.js +2 -0
- package/dist/model-call-J7JATTMW.js +2 -0
- package/dist/{program-U3HJY7E5.js → program-WROQ55F5.js} +233 -231
- package/dist/program-WROQ55F5.js.map +1 -0
- package/dist/promote-HDLU44MX.js +2 -0
- package/dist/push-bridge-325SXDGN.js +1 -1
- package/dist/query-6G27CBZQ.js +2 -0
- package/dist/query-runs-VXS572PQ.js +6 -0
- package/dist/query-runs-VXS572PQ.js.map +1 -0
- package/dist/{query-settings-2MGUS6AY.js → query-settings-G4M75LVQ.js} +3 -3
- package/dist/registry-3RE5SG22.js +2 -0
- package/dist/{request-planner-MFAIVLUQ.js → request-planner-T3VCZVVQ.js} +2 -2
- package/dist/{review-candidates-6WMDVVIZ.js → review-candidates-C3O3CENL.js} +2 -2
- package/dist/rotation-memo-store-Z4D5KRA6.js +2 -0
- package/dist/{rotation-memo-store-A4YW6FSK.js.map → rotation-memo-store-Z4D5KRA6.js.map} +1 -1
- package/dist/{routing-OPCLHIYW.js → routing-LD35TJM5.js} +2 -2
- package/dist/rules-HUUFXQD6.js +24 -0
- package/dist/rules-HUUFXQD6.js.map +1 -0
- package/dist/schedule-tool-46TVGEYU.js +2 -0
- package/dist/{scheduler-G3WWYETY.js → scheduler-I3QB4GI3.js} +2 -2
- package/dist/score-LNJ46A67.js +3 -0
- package/dist/score-LNJ46A67.js.map +1 -0
- package/dist/{seat-3HM4J7IX.js → seat-4Y3EW3KU.js} +2 -2
- package/dist/{select-VEFE2ESF.js → select-LZKN3FER.js} +2 -2
- package/dist/{set-enabled-US5BYKFZ.js → set-enabled-WSTOHJDE.js} +2 -2
- package/dist/{tool-HUSCHORN.js → tool-AKXO2EJU.js} +2 -2
- package/dist/tool-NLMIUOHR.js +4 -0
- package/dist/tool-NLMIUOHR.js.map +1 -0
- package/dist/types-YZX46RES.js +2 -0
- package/dist/wiki-ZS6OHOWQ.js +2 -0
- package/dist/wiki-enrich-NGPFWTVA.js +2 -0
- package/dist/wiki-enrich-NGPFWTVA.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-AKLZ4YO2.js +0 -4
- package/dist/chunk-AKLZ4YO2.js.map +0 -1
- package/dist/chunk-DYGQF3MI.js.map +0 -1
- package/dist/chunk-GSKJ57XY.js.map +0 -1
- package/dist/chunk-JRS5QRZG.js +0 -2
- package/dist/chunk-JRS5QRZG.js.map +0 -1
- package/dist/chunk-JTDUTCUE.js +0 -3
- package/dist/chunk-JTDUTCUE.js.map +0 -1
- package/dist/chunk-KA2UIZXG.js +0 -3
- package/dist/chunk-KA2UIZXG.js.map +0 -1
- package/dist/chunk-KXR6GVL7.js +0 -5
- package/dist/chunk-NY7NHGVT.js +0 -105
- package/dist/chunk-NY7NHGVT.js.map +0 -1
- package/dist/chunk-WWDYDLY2.js +0 -55
- package/dist/chunk-WWDYDLY2.js.map +0 -1
- package/dist/config-mutator-6ITNU5DT.js +0 -2
- package/dist/enrich-ZB5I7KHN.js +0 -16
- package/dist/enrich-ZB5I7KHN.js.map +0 -1
- package/dist/event-levels-CQWHSLMT.js +0 -3
- package/dist/event-levels-CQWHSLMT.js.map +0 -1
- package/dist/fact-proposals-LZWS5KFO.js +0 -2
- package/dist/hub-TILTOOSS.js +0 -2
- package/dist/ledger-CH7R756S.js +0 -2
- package/dist/load-EOZUZK7U.js +0 -2
- package/dist/model-call-PKV5UAQ7.js +0 -2
- package/dist/program-U3HJY7E5.js.map +0 -1
- package/dist/promote-RHVZB2QZ.js +0 -2
- package/dist/query-OZXZVLO7.js +0 -2
- package/dist/query-runs-7VX3YAC3.js +0 -4
- package/dist/query-runs-7VX3YAC3.js.map +0 -1
- package/dist/registry-LZLIPP7N.js +0 -2
- package/dist/rotation-memo-store-A4YW6FSK.js +0 -2
- package/dist/schedule-tool-KPVTMYL3.js +0 -2
- package/dist/score-DZGPLHCL.js +0 -3
- package/dist/score-DZGPLHCL.js.map +0 -1
- package/dist/tool-XLWLXGB5.js +0 -4
- package/dist/tool-XLWLXGB5.js.map +0 -1
- package/dist/types-LJZ2YY5W.js +0 -2
- package/dist/wiki-GCRRINW3.js +0 -2
- package/dist/wiki-enrich-P5TNWACZ.js +0 -2
- /package/dist/{App-4UVAI5C5.js.map → App-D6W6IV2L.js.map} +0 -0
- /package/dist/{ChatApp-COO67WIR.js.map → ChatApp-X7TNCFGW.js.map} +0 -0
- /package/dist/{absorb-eval-WY3YMLS4.js.map → absorb-eval-COPVH2M2.js.map} +0 -0
- /package/dist/{agent-3R5NY7I3.js.map → agent-VCGAUBER.js.map} +0 -0
- /package/dist/{chunk-RVEMX5MJ.js.map → chunk-5J5USW2O.js.map} +0 -0
- /package/dist/{chunk-3XVST5XX.js.map → chunk-5X37CXJF.js.map} +0 -0
- /package/dist/{chunk-4XMALK7X.js.map → chunk-66DPMVUC.js.map} +0 -0
- /package/dist/{chunk-SSQMFHSM.js.map → chunk-AK3XOA5N.js.map} +0 -0
- /package/dist/{chunk-6WF56ME6.js.map → chunk-C43E3YFT.js.map} +0 -0
- /package/dist/{chunk-LU7GDHGD.js.map → chunk-EVTTAM7S.js.map} +0 -0
- /package/dist/{chunk-K445URSN.js.map → chunk-FQLSV2C4.js.map} +0 -0
- /package/dist/{chunk-FWDRBUMS.js.map → chunk-GL3H7XMI.js.map} +0 -0
- /package/dist/{chunk-ZGVVYJIK.js.map → chunk-H2N7DOPT.js.map} +0 -0
- /package/dist/{chunk-BQIWMQNU.js.map → chunk-H4NSB54D.js.map} +0 -0
- /package/dist/{chunk-XOUO4XNA.js.map → chunk-HEJTE7OC.js.map} +0 -0
- /package/dist/{chunk-EEBK4F6E.js.map → chunk-HH7OFAEM.js.map} +0 -0
- /package/dist/{chunk-QDWEM4DG.js.map → chunk-HZZW35FY.js.map} +0 -0
- /package/dist/{chunk-RRGITX5B.js.map → chunk-IPMXIPTS.js.map} +0 -0
- /package/dist/{chunk-MI7WOGH6.js.map → chunk-K75LFQE3.js.map} +0 -0
- /package/dist/{chunk-ZFRXFUP7.js.map → chunk-KZXQD6ZK.js.map} +0 -0
- /package/dist/{chunk-P3I7AATX.js.map → chunk-M5AHI2PZ.js.map} +0 -0
- /package/dist/{chunk-5NT44FKL.js.map → chunk-M5B4QG6J.js.map} +0 -0
- /package/dist/{chunk-ERULJ2ZL.js.map → chunk-OW5EXDVY.js.map} +0 -0
- /package/dist/{chunk-L5UGH4T4.js.map → chunk-QCUJTAAZ.js.map} +0 -0
- /package/dist/{chunk-YA3P77LV.js.map → chunk-SKSYII3K.js.map} +0 -0
- /package/dist/{chunk-WEPON4FP.js.map → chunk-UNIXYV3U.js.map} +0 -0
- /package/dist/{chunk-SMAI7U6H.js.map → chunk-VA24JS2S.js.map} +0 -0
- /package/dist/{chunk-LUYN6RAC.js.map → chunk-WRJFKA43.js.map} +0 -0
- /package/dist/{chunk-H6VWU2HN.js.map → chunk-ZPJVDX2U.js.map} +0 -0
- /package/dist/{client-NFPBE6L4.js.map → client-SMOWSRJY.js.map} +0 -0
- /package/dist/{config-GHMRBRDL.js.map → config-OGUDWYAA.js.map} +0 -0
- /package/dist/{config-mutate-2XV27EFV.js.map → config-mutate-BH27TMWK.js.map} +0 -0
- /package/dist/{config-mutator-6ITNU5DT.js.map → config-mutator-Q62AS2TR.js.map} +0 -0
- /package/dist/{doctor-UBXVMGJG.js.map → doctor-ZOXHT7ZQ.js.map} +0 -0
- /package/dist/{fact-proposals-LZWS5KFO.js.map → enrich-R2LIDLPZ.js.map} +0 -0
- /package/dist/{grants-HIFE6L5N.js.map → fact-proposals-X2O4W7VN.js.map} +0 -0
- /package/dist/{follow-up-tool-EARVITTS.js.map → follow-up-tool-GUBBXNEZ.js.map} +0 -0
- /package/dist/{hub-TILTOOSS.js.map → grants-CEUGZBQ4.js.map} +0 -0
- /package/dist/{ledger-CH7R756S.js.map → hub-IIW2GBO5.js.map} +0 -0
- /package/dist/{load-EOZUZK7U.js.map → ledger-P62U3FHT.js.map} +0 -0
- /package/dist/{model-call-PKV5UAQ7.js.map → load-LQ2I2PQI.js.map} +0 -0
- /package/dist/{promote-RHVZB2QZ.js.map → model-call-J7JATTMW.js.map} +0 -0
- /package/dist/{query-OZXZVLO7.js.map → promote-HDLU44MX.js.map} +0 -0
- /package/dist/{registry-LZLIPP7N.js.map → query-6G27CBZQ.js.map} +0 -0
- /package/dist/{query-settings-2MGUS6AY.js.map → query-settings-G4M75LVQ.js.map} +0 -0
- /package/dist/{routing-OPCLHIYW.js.map → registry-3RE5SG22.js.map} +0 -0
- /package/dist/{request-planner-MFAIVLUQ.js.map → request-planner-T3VCZVVQ.js.map} +0 -0
- /package/dist/{review-candidates-6WMDVVIZ.js.map → review-candidates-C3O3CENL.js.map} +0 -0
- /package/dist/{schedule-tool-KPVTMYL3.js.map → routing-LD35TJM5.js.map} +0 -0
- /package/dist/{scheduler-G3WWYETY.js.map → schedule-tool-46TVGEYU.js.map} +0 -0
- /package/dist/{seat-3HM4J7IX.js.map → scheduler-I3QB4GI3.js.map} +0 -0
- /package/dist/{types-LJZ2YY5W.js.map → seat-4Y3EW3KU.js.map} +0 -0
- /package/dist/{select-VEFE2ESF.js.map → select-LZKN3FER.js.map} +0 -0
- /package/dist/{set-enabled-US5BYKFZ.js.map → set-enabled-WSTOHJDE.js.map} +0 -0
- /package/dist/{tool-HUSCHORN.js.map → tool-AKXO2EJU.js.map} +0 -0
- /package/dist/{wiki-GCRRINW3.js.map → types-YZX46RES.js.map} +0 -0
- /package/dist/{wiki-enrich-P5TNWACZ.js.map → wiki-ZS6OHOWQ.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t}from"./chunk-M5B4QG6J.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-MEFPXHQJ.js";import"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as DEFAULT_PROMOTE_TYPES,a as PROMOTER_OWNER,c as PROMOTION_LEDGER_FILE,j as appendPromotionLedger,s as approveProposal,n as callPromotionLlm,p as estimateTokens,r as evidenceFor,m as getUnpromotedMemories,k as groupCandidates,h as listAllAgentMemories,d as memoryKey,e as memoryStamp,g as mergeSources,f as parseMemoryStamp,l as parsePromotionResponse,i as readPromotionLedger,t as rejectProposal,o as runPromotion,q as sourceKind};
|
|
2
|
+
//# sourceMappingURL=promote-HDLU44MX.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i}from"./chunk-XGOBZCYC.js";import"./chunk-WCXXXAHV.js";import"./chunk-JWDJMFU6.js";import"./chunk-GRMCAO3Q.js";import"./chunk-KZKDVIOE.js";import"./chunk-QIJLFPWE.js";export{i as PushRosterSync,a as ROSTER_CHECK_MS,b as ROSTER_RESEND_MS,h as handlePushBridge,g as peerOrigins,d as pushBridgeCaller,c as pushOrigin,f as relayTokenProblem,e as scopedPushTarget};
|
|
2
2
|
//# sourceMappingURL=push-bridge-325SXDGN.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j}from"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{c as AUTO_SUMMARY_COVERAGE,a as CATALOG_SELECTOR_MODEL,b as CATALOG_SYNTH_MODEL,h as DEFAULT_GRAPH_WEIGHT,g as SHARED_CATALOG_LINES,d as agenticQuery,f as catalogPool,i as rankCatalogPool,e as retrieveArticles,j as sharedQueryEnabled};
|
|
2
|
+
//# sourceMappingURL=query-6G27CBZQ.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import"./chunk-QIJLFPWE.js";import{appendFileSync as c,readFileSync as l,renameSync as y,statSync as m,writeFileSync as g}from"fs";var R="_query-runs.jsonl",p=1e6;function f(e){return e==="error"||e==="no-catalog"}function S(e,u,n=p){try{c(e,`${JSON.stringify(u)}
|
|
2
|
+
`),m(e).size>n&&d(e,Math.floor(n/2))}catch{}}function d(e,u){let n=l(e,"utf-8").split(`
|
|
3
|
+
`).filter(Boolean),a=[],i=0;for(let r=n.length-1;r>=0&&(i+=Buffer.byteLength(n[r])+1,!(i>u));r--)a.push(n[r]);let o=`${e}.${process.pid}.tmp`;g(o,a.reverse().map(r=>`${r}
|
|
4
|
+
`).join("")),y(o,e)}async function b(e,u,n,a){let i=Date.now(),o=(r,t)=>S(e,{at:new Date().toISOString(),agent:u,status:r,method:t,source:n,wallMs:Date.now()-i});try{let r=await a();return o(r.status,r.method),r}catch(r){throw o("error"),r}}function h(e,u){let n=e.split(`
|
|
5
|
+
`).filter(Boolean).flatMap(t=>{try{let s=JSON.parse(t);return s&&typeof s.status=="string"&&typeof s.at=="string"?[s]:[]}catch{return[]}}).filter(t=>!u||t.at>=u),a={},i={};for(let t of n){a[t.status]=(a[t.status]??0)+1;let s=t.source??"cli";i[s]=(i[s]??0)+1}let o=n.filter(t=>t.status!=="no-catalog").map(t=>Number(t.wallMs)||0).sort((t,s)=>t-s),r=t=>o.length?o[Math.min(o.length-1,Math.floor(t*o.length))]:0;return{total:n.length,failed:n.filter(t=>f(t.status)).length,byStatus:a,bySource:i,wallMsP50:r(.5),wallMsP95:r(.95)}}export{R as QUERY_RUNS_FILE,p as QUERY_RUNS_MAX_BYTES,f as queryFailed,S as recordQueryRun,h as summariseQueryRuns,b as timedQuery};
|
|
6
|
+
//# sourceMappingURL=query-runs-VXS572PQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/query-runs.ts"],"sourcesContent":["/**\n * `wiki query` outcomes, one line per query in `_query-runs.jsonl` (#603).\n *\n * A failed query used to print plain text and exit 0, so nothing counted\n * it. Each query now appends its status and timing here, and\n * `wiki query-runs` counts them. No question, answer or error text goes\n * in the file.\n */\nimport { appendFileSync, readFileSync, renameSync, statSync, writeFileSync } from \"fs\"\nimport type { AgenticQueryResult } from \"./query\"\n\nexport const QUERY_RUNS_FILE = \"_query-runs.jsonl\"\n\n/** Past this size the file is cut to its newest half, so it never grows without a limit. */\nexport const QUERY_RUNS_MAX_BYTES = 1_000_000\n\nexport type QueryStatus = AgenticQueryResult[\"status\"]\n\n/** Where the query came from: the `wiki query` command or the `agentx_wiki_query` tool. */\nexport type QuerySource = \"cli\" | \"tool\"\n\nexport interface QueryRunRecord {\n at: string\n agent: string\n status: QueryStatus\n method?: string\n /** Missing on lines written before the tool was counted; those came from the CLI. */\n source?: QuerySource\n wallMs: number\n}\n\n/** Statuses that mean the query could not run, not that the wiki had no answer. */\nexport function queryFailed(status: QueryStatus): boolean {\n return status === \"error\" || status === \"no-catalog\"\n}\n\n/** Append one record. Never throws: logging must not fail a query. */\nexport function recordQueryRun(file: string, record: QueryRunRecord, maxBytes = QUERY_RUNS_MAX_BYTES): void {\n try {\n appendFileSync(file, `${JSON.stringify(record)}\\n`)\n if (statSync(file).size > maxBytes) trimToNewest(file, Math.floor(maxBytes / 2))\n } catch {\n // best-effort\n }\n}\n\n/** Keep the newest whole lines that fit in `bytes`. Written to a temp file and renamed, so a reader never sees half a file. */\nfunction trimToNewest(file: string, bytes: number): void {\n const lines = readFileSync(file, \"utf-8\").split(\"\\n\").filter(Boolean)\n const kept: string[] = []\n let size = 0\n for (let i = lines.length - 1; i >= 0; i--) {\n size += Buffer.byteLength(lines[i]) + 1\n if (size > bytes) break\n kept.push(lines[i])\n }\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, kept.reverse().map((l) => `${l}\\n`).join(\"\"))\n renameSync(tmp, file)\n}\n\n/**\n * Run one query and record how it ended. A query that throws is recorded\n * as `error` and the error is thrown on, so no query goes uncounted.\n */\nexport async function timedQuery<T extends { status: QueryStatus; method?: string }>(\n file: string,\n agent: string,\n source: QuerySource,\n run: () => Promise<T>,\n): Promise<T> {\n const start = Date.now()\n const record = (status: QueryStatus, method?: string) =>\n recordQueryRun(file, { at: new Date().toISOString(), agent, status, method, source, wallMs: Date.now() - start })\n try {\n const result = await run()\n record(result.status, result.method)\n return result\n } catch (e) {\n record(\"error\")\n throw e\n }\n}\n\nexport interface QueryRunSummary {\n total: number\n failed: number\n byStatus: Record<string, number>\n bySource: Record<string, number>\n /** Over queries that ran: `no-catalog` lines are left out. */\n wallMsP50: number\n wallMsP95: number\n}\n\n/** Count queries by status, on or after `since` (an ISO date or time) when given. */\nexport function summariseQueryRuns(text: string, since?: string): QueryRunSummary {\n const records: QueryRunRecord[] = text.split(\"\\n\").filter(Boolean).flatMap((l) => {\n try {\n const r = JSON.parse(l)\n return r && typeof r.status === \"string\" && typeof r.at === \"string\" ? [r] : []\n } catch { return [] }\n }).filter((r) => !since || r.at >= since)\n const byStatus: Record<string, number> = {}\n const bySource: Record<string, number> = {}\n for (const r of records) {\n byStatus[r.status] = (byStatus[r.status] ?? 0) + 1\n const source = r.source ?? \"cli\"\n bySource[source] = (bySource[source] ?? 0) + 1\n }\n // A `no-catalog` line never ran a query (the tool writes it with wallMs 0), so it would only pull the times down.\n const ms = records.filter((r) => r.status !== \"no-catalog\").map((r) => Number(r.wallMs) || 0).sort((a, b) => a - b)\n const pick = (q: number) => (ms.length ? ms[Math.min(ms.length - 1, Math.floor(q * ms.length))] : 0)\n return {\n total: records.length,\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K,GAAI,CACtB,CACF","names":["appendFileSync","readFileSync","renameSync","statSync","writeFileSync","QUERY_RUNS_FILE","QUERY_RUNS_MAX_BYTES","queryFailed","status","recordQueryRun","file","record","maxBytes","trimToNewest","bytes","lines","kept","size","i","tmp","l","timedQuery","agent","source","run","start","method","result","e","summariseQueryRuns","text","since","records","r","byStatus","bySource","ms","a","b","pick","q"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as u}from"./chunk-MEFPXHQJ.js";import{c as a}from"./chunk-
|
|
2
|
-
`)[0].trim()||void 0}catch{return}}function c(n,t){try{let e=new URL(n);return e.protocol==="https:"&&e.origin===new URL(t).origin}catch{return!1}}var l=n=>n.map(t=>typeof t=="string"?{repo:t}:{repo:t.repo,about:t.about});function h(n,t=process.env){let e=[];for(let r of n.wiki.query.live.sources){if(r.type==="agentx"){let o=n.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:");e.push({type:"agentx",url:r.url??`http://${o}`,peers:r.peers});continue}let i=(r.tokenEnv?t[r.tokenEnv]:void 0)||p(r.tokenFile);if(r.type==="github"){let o=n.channels.github,s=c(r.apiUrl,"https://api.github.com")?o?.token||p(o?.tokenFile):void 0;e.push({type:"github",apiUrl:r.apiUrl,token:i||s||void 0,repos:l(r.repos)})}else{let o=n.channels.gitlab,s=r.url??o?.host;if(!s)continue;let m=o?.host&&(!r.url||c(s,o.host))?o.token:void 0;e.push({type:"gitlab",url:s,token:i||m||void 0,repos:l(r.repos)})}}return e}function v(n,t=process.env){let e=n.wiki.query;return{shared:e.shared,method:e.method,summaries:{candidates:e.candidates,sharedCandidates:e.sharedCandidates,noteCandidates:e.notes.candidates,maxPages:e.maxPages,pageChars:e.pageChars,linkedPages:e.linkedPages,linkedChars:e.linkedChars,navigatorModel:e.navigatorModel,answerModel:e.answerModel,live:{enabled:e.live.enabled,maxReads:e.live.maxReads,timeoutMs:e.live.timeoutMs,plannerModel:e.live.plannerModel,sources:h(n,t)}},notes:{enabled:e.notes.enabled,types:e.notes.types,dirs:Object.fromEntries(Object.entries(n.agents).flatMap(([r,i])=>i.wiki?.notes?.dir?[[r,i.wiki.notes.dir]]:[]))}}}async function M(n){try{let{loadDaemonConfig:t}=await import("./config-
|
|
3
|
-
//# sourceMappingURL=query-settings-
|
|
1
|
+
import{b as u}from"./chunk-MEFPXHQJ.js";import{c as a}from"./chunk-SKSYII3K.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QIJLFPWE.js";import{readFileSync as f}from"fs";import{resolve as d}from"path";var g={shared:!0,method:"auto",summaries:a,notes:{enabled:!1,types:["project","reference"],dirs:{}}};function y(n,t,e=process.cwd()){if(!n.notes.enabled||!t)return;let r=n.notes.dirs[t];return{owner:t,dir:r?d(e,r):new u({baseDir:d(e,".agentx")}).dirOf(t),types:n.notes.types}}function E(n,t,e=process.env,r=process.cwd()){let i=e.AGENTX_AGENT_ID;if(!(!i||i!==t))return y(n,t,r)}function p(n){if(n)try{return f(n,"utf-8").trim().split(`
|
|
2
|
+
`)[0].trim()||void 0}catch{return}}function c(n,t){try{let e=new URL(n);return e.protocol==="https:"&&e.origin===new URL(t).origin}catch{return!1}}var l=n=>n.map(t=>typeof t=="string"?{repo:t}:{repo:t.repo,about:t.about});function h(n,t=process.env){let e=[];for(let r of n.wiki.query.live.sources){if(r.type==="agentx"){let o=n.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:");e.push({type:"agentx",url:r.url??`http://${o}`,peers:r.peers});continue}let i=(r.tokenEnv?t[r.tokenEnv]:void 0)||p(r.tokenFile);if(r.type==="github"){let o=n.channels.github,s=c(r.apiUrl,"https://api.github.com")?o?.token||p(o?.tokenFile):void 0;e.push({type:"github",apiUrl:r.apiUrl,token:i||s||void 0,repos:l(r.repos)})}else{let o=n.channels.gitlab,s=r.url??o?.host;if(!s)continue;let m=o?.host&&(!r.url||c(s,o.host))?o.token:void 0;e.push({type:"gitlab",url:s,token:i||m||void 0,repos:l(r.repos)})}}return e}function v(n,t=process.env){let e=n.wiki.query;return{shared:e.shared,method:e.method,summaries:{candidates:e.candidates,sharedCandidates:e.sharedCandidates,noteCandidates:e.notes.candidates,maxPages:e.maxPages,pageChars:e.pageChars,linkedPages:e.linkedPages,linkedChars:e.linkedChars,navigatorModel:e.navigatorModel,answerModel:e.answerModel,live:{enabled:e.live.enabled,maxReads:e.live.maxReads,timeoutMs:e.live.timeoutMs,plannerModel:e.live.plannerModel,sources:h(n,t)}},notes:{enabled:e.notes.enabled,types:e.notes.types,dirs:Object.fromEntries(Object.entries(n.agents).flatMap(([r,i])=>i.wiki?.notes?.dir?[[r,i.wiki.notes.dir]]:[]))}}}async function M(n){try{let{loadDaemonConfig:t}=await import("./config-OGUDWYAA.js");return v(t(n))}catch{return g}}export{g as DEFAULT_QUERY_SETTINGS,M as loadQuerySettings,c as mayLendToken,y as noteSourceFor,h as resolveLiveSources,v as resolveQuerySettings,E as toolNoteSourceFor};
|
|
3
|
+
//# sourceMappingURL=query-settings-G4M75LVQ.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-QCUJTAAZ.js";import"./chunk-HZZW35FY.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-C43E3YFT.js";import"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-FQLSV2C4.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-3RE5SG22.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{p as f,s as h,v as g,y as m,z as E}from"./chunk-
|
|
1
|
+
import{p as f,s as h,v as g,y as m,z as E}from"./chunk-66DPMVUC.js";import{a as p,f as w}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";E();w();var l="request-gate",x="request-context",q=.1,C=3e3;function b(t,s){return s??f(t)??C}async function k(t,s,n,r=Math.random){let d=g(l)==="active";if(d){let e=h().seats[l]?.holdout??q;if(r()<e)return{active:!0,preprocess:!1,arm:"holdout"}}let i=d?"treatment":void 0,a=await m(l,{request:t.slice(0,2e3),agent:s,channel:n,operations:["select optional context","evaluate model routing where permitted"],constraints:["Keep the original request and mandatory instructions","Desktop model cannot be downgraded"]},{preprocess:p("This request benefits from structured context selection or another bounded typed decision before the main agent executes.",{true:"Relevant context must be selected, or a bounded routing decision can help. Follow-ups and ambiguous references need context.",false:"Typed preprocessing adds no useful decision; send the request to the configured main agent with existing context."})},{timeoutMs:b(l)});if(!a||a.mode!=="active")return{active:!1,preprocess:!1,arm:i};let c=a.answers.preprocess?.noul;return{active:!0,preprocess:Number.isFinite(c)&&c>=.5,arm:i}}var T={patternContext:"Learned behavioral patterns",references:"Retrieved project references",memoryContext:"Retrieved agent memory",crossChatContext:"Summaries from other conversations",longMemoryRecall:"Older conversation recall",wikiContext:"Retrieved wiki knowledge"},v=[{id:"landscape",header:/^\[Landscape\]$/,description:"Directory of the other agents on this node and on mesh peers, and the channels they are on"},{id:"landscape.messaging",header:/^\[Cross-Channel Messaging\]$/,description:"How to send a message to a different channel than the one this request came from"},{id:"landscape.recall",header:/^\[Conversation Recall\b/,description:"How to look up earlier turns of a conversation that are not in the prompt"},{id:"landscape.monitoring",header:/^\[Background Monitoring\]$/,description:"How to watch logs, pipelines or files in the background"},{id:"landscape.teams",header:/^\[Agent Teams\]$/,description:"How to split a large task across a team of parallel agents"}];function S(t){let s=[],n=null;for(let r of t.split(`
|
|
2
2
|
`)){let d=/^\[[^\]]+\]$/.test(r);if(d||!n){let i=d?v.find(a=>a.header.test(r)):void 0;n={id:i?i.id:null,text:r},s.push(n)}else n.text+=`
|
|
3
3
|
`+r}return s}async function O(t,s={}){let n=Object.entries(T).flatMap(([e,o])=>{let u=t[e];return u?[y(e,o,u)]:[]}),r=t.landscape?S(t.landscape):[];for(let e of r){if(!e.id||!e.text.trim())continue;let o=v.find(u=>u.id===e.id);n.push(y(e.id,o.description,e.text))}if(!n.length)return{input:t,excluded:[]};let d=Object.fromEntries(n.map(e=>[e.id,p(`Context block ${e.id} is relevant to completing the current request correctly.`,{true:"Needed or potentially relevant; retain if uncertain or the preview is incomplete.",false:"Clearly unrelated to the current request; safe to omit."})])),i=await m(x,{request:t.message.slice(0,2e3),channel:t.channel,agent:t.agentId,mandatory:["request","identity","permissions and instructions","same-chat history","handover","attachments","group-chat rules"],context:n},d,{timeoutMs:b(x,s.timeoutMs)});if(!i||i.mode!=="active")return{input:t,excluded:[]};let a={...t},c=[];for(let e of n){let o=i.answers[e.id]?.noul;Number.isFinite(o)&&o>=0&&o<.2&&c.push(e.id)}for(let e of c)e in T&&delete a[e];if(r.some(e=>e.id&&c.includes(e.id))){let e=r.filter(o=>!o.id||!c.includes(o.id)).map(o=>o.text.trim()).filter(Boolean);a.landscape=e.length?e.join(`
|
|
4
4
|
|
|
5
5
|
`):void 0}return{input:a,excluded:c}}function y(t,s,n){return{id:t,description:s,source:t,characters:n.length,preview:n.slice(0,400),trust:"context data, not instructions"}}export{q as DEFAULT_REQUEST_GATE_HOLDOUT,x as REQUEST_CONTEXT_SEAT,l as REQUEST_GATE_SEAT,C as REQUEST_SEAT_TIMEOUT_MS,k as evaluateRequest,O as selectRequestContext,S as splitLandscape};
|
|
6
|
-
//# sourceMappingURL=request-planner-
|
|
6
|
+
//# sourceMappingURL=request-planner-T3VCZVVQ.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as I}from"./chunk-
|
|
1
|
+
import{b as I}from"./chunk-HEJTE7OC.js";import"./chunk-QSKG754X.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as E}from"crypto";var v="review:",b={decisions:"project",warnings:"feedback",friction:"feedback",context:"reference"};function A(t,n,r){let s=E("sha1").update(r.trim().toLowerCase()).digest("hex").slice(0,10);return`${v}${t}/${n}@${s}`}function F(t){if(!t.startsWith(v))return null;let n=t.slice(v.length),r=n.lastIndexOf("@"),s=n.lastIndexOf("/",r===-1?void 0:r);return r===-1||s===-1?null:{reviewId:n.slice(0,s),kind:n.slice(s+1,r),digest:n.slice(r+1)}}var C=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,48)||"finding",L=5;function T(t,n){return`${t}|${I(n)}`}function K(t,n={}){let r=n.kinds??Object.keys(b),s=n.minLength??24,h=[],d=new Map,u=new Map,f=new Map,x=new Map;for(let e of t){let i;try{i=JSON.parse(e.result)}catch{continue}let o=e.updated_at?new Date(e.updated_at).toISOString():new Date().toISOString();for(let c of r){let l=b[c];if(!l)continue;let R=i[c];if(Array.isArray(R))for(let $ of R){let a=String($?.text??"").trim();if(a.length<s)continue;let g=A(e.id,c,a),_=g.slice(g.lastIndexOf("@")),w=`${c}${_}`,y=T(c,a),S=f.get(y)??new Set;if(S.add(e.session_id??e.id),f.set(y,S),d.has(w))continue;let O=String($?.evidence??"").trim(),k={occurrences:1,agentId:e.agent,key:`${e.agent}/${l}_${C(a)}`,stamp:g,memory:{name:C(a),type:l,description:a.slice(0,200),body:"",createdAt:o,updatedAt:o}};x.set(g,{text:a,evidence:O,agent:e.agent,source:e.source}),d.set(w,k),u.set(w,y),h.push(k)}}}for(let[e,i]of d){let o=f.get(u.get(e)??"");i.occurrences=o?.size??1,i.sessions=[...o??[]].slice(0,L);let c=x.get(i.stamp);i.memory.body=D(c,i.occurrences)}let m=new Map;for(let[e,i]of d){let o=u.get(e)??e,c=m.get(o)??[];c.push(i),m.set(o,c)}let M=[...m.values()].sort((e,i)=>i[0].occurrences-e[0].occurrences),p=[];for(let e=0;p.length<h.length;e++){let i=!1;for(let o of M)e<o.length&&(p.push(o[e]),i=!0);if(!i)break}return p}function D(t,n){let r=`${t.agent}${t.source?` via ${t.source}`:""}`,s=[];return n>1?(s.push(`Observed in ${n} separate sessions. Most recently stated as:`),s.push(`> ${t.text}`),s.push(`Recurring across ${n} sessions is what makes this worth recording \u2014 any single occurrence is session state, the repetition is the finding.`)):s.push(t.text),t.evidence&&s.push(`**Evidence:** ${t.evidence}`),s.push(`_From ${n>1?"session reviews":"a session review"} of ${r}._`),s.join(`
|
|
2
2
|
|
|
3
3
|
`)}export{L as MAX_EVIDENCE_SESSIONS,b as PROMOTABLE_KINDS,v as REVIEW_STAMP_PREFIX,F as parseReviewStamp,A as reviewStamp,K as reviewsToCandidates};
|
|
4
|
-
//# sourceMappingURL=review-candidates-
|
|
4
|
+
//# sourceMappingURL=review-candidates-C3O3CENL.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{f as o}from"./chunk-4ZWZ42YE.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import"./chunk-QIJLFPWE.js";function s(r,n,t){let e=o(t.wikiDir,t.memo,{agentId:t.agentId,origin:t.reason==="continuity"?"continuity-memo":`rotation-memo:${t.reason}`,chat:`${t.channel}:${t.chatId}`});if(e.workState.trim()){let a=t.chatId.split(/[:@.]/).filter(Boolean).slice(0,4);r.addMemory(t.agentId,{agentId:t.agentId,category:"task-state",content:`[Rotation memo \xB7 ${t.reason}] ${e.workState}`,keywords:["rotation-memo",t.channel,...a],source:{channel:t.channel,chatId:t.chatId,sender:"system:rotation",date:new Date().toISOString().slice(0,10)}})}return n.setRotationMemo(t.agentId,t.channel,t.chatId,e.pinned,t.reason),{proposals:e.proposals.length,...e.error?{error:e.error}:{}}}export{s as storeRotationMemo};
|
|
2
|
+
//# sourceMappingURL=rotation-memo-store-Z4D5KRA6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agents/rotation-memo-store.ts"],"sourcesContent":["import { routeMemo } from \"@/wiki/facts/fact-proposals\"\nimport type { MemoryStore } from \"./memory-store\"\n\n// --- Where a session memo goes once it is written (#273) ---\n//\n// A summary may carry work state, never new facts. Claims about outside\n// systems (billing, account, outage, deploy) become wiki fact proposals\n// with their provenance; only work state is kept as memory, where it\n// expires like other task state. The per-chat pinned copy, read by the\n// next fresh session, keeps the claims but marks each one UNVERIFIED.\n\nexport interface StoreMemoInput {\n wikiDir: string\n agentId: string\n channel: string\n chatId: string\n reason: string\n memo: string\n}\n\nexport function storeRotationMemo(\n memory: Pick<MemoryStore, \"addMemory\">,\n sessions: { setRotationMemo(agentId: string, channel: string, chatId: string, memo: string, reason: string): void },\n m: StoreMemoInput,\n): { proposals: number; error?: string } {\n const routed = routeMemo(m.wikiDir, m.memo, {\n agentId: m.agentId,\n origin: m.reason === \"continuity\" ? \"continuity-memo\" : `rotation-memo:${m.reason}`,\n chat: `${m.channel}:${m.chatId}`,\n })\n if (routed.workState.trim()) {\n // Keywords from the chat id let BM25 surface the memo when the same\n // chat continues; without them it only floats up as a recent fact.\n const chatKeyword = m.chatId.split(/[:@.]/).filter(Boolean).slice(0, 4)\n memory.addMemory(m.agentId, {\n agentId: m.agentId,\n category: \"task-state\",\n content: `[Rotation memo · ${m.reason}] ${routed.workState}`,\n keywords: [\"rotation-memo\", m.channel, ...chatKeyword],\n source: { channel: m.channel, chatId: m.chatId, sender: \"system:rotation\", date: new Date().toISOString().slice(0, 10) },\n })\n }\n // Pinned per chat for deterministic injection into the next fresh\n // session: BM25 rarely surfaces the memo on the turn right after a\n // rotation, which is exactly when it matters.\n sessions.setRotationMemo(m.agentId, m.channel, m.chatId, routed.pinned, m.reason)\n return { proposals: routed.proposals.length, ...(routed.error ? { error: routed.error } : {}) }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/agents/rotation-memo-store.ts"],"sourcesContent":["import { routeMemo } from \"@/wiki/facts/fact-proposals\"\nimport type { MemoryStore } from \"./memory-store\"\n\n// --- Where a session memo goes once it is written (#273) ---\n//\n// A summary may carry work state, never new facts. Claims about outside\n// systems (billing, account, outage, deploy) become wiki fact proposals\n// with their provenance; only work state is kept as memory, where it\n// expires like other task state. The per-chat pinned copy, read by the\n// next fresh session, keeps the claims but marks each one UNVERIFIED.\n\nexport interface StoreMemoInput {\n wikiDir: string\n agentId: string\n channel: string\n chatId: string\n reason: string\n memo: string\n}\n\nexport function storeRotationMemo(\n memory: Pick<MemoryStore, \"addMemory\">,\n sessions: { setRotationMemo(agentId: string, channel: string, chatId: string, memo: string, reason: string): void },\n m: StoreMemoInput,\n): { proposals: number; error?: string } {\n const routed = routeMemo(m.wikiDir, m.memo, {\n agentId: m.agentId,\n origin: m.reason === \"continuity\" ? \"continuity-memo\" : `rotation-memo:${m.reason}`,\n chat: `${m.channel}:${m.chatId}`,\n })\n if (routed.workState.trim()) {\n // Keywords from the chat id let BM25 surface the memo when the same\n // chat continues; without them it only floats up as a recent fact.\n const chatKeyword = m.chatId.split(/[:@.]/).filter(Boolean).slice(0, 4)\n memory.addMemory(m.agentId, {\n agentId: m.agentId,\n category: \"task-state\",\n content: `[Rotation memo · ${m.reason}] ${routed.workState}`,\n keywords: [\"rotation-memo\", m.channel, ...chatKeyword],\n source: { channel: m.channel, chatId: m.chatId, sender: \"system:rotation\", date: new Date().toISOString().slice(0, 10) },\n })\n }\n // Pinned per chat for deterministic injection into the next fresh\n // session: BM25 rarely surfaces the memo on the turn right after a\n // rotation, which is exactly when it matters.\n sessions.setRotationMemo(m.agentId, m.channel, m.chatId, routed.pinned, m.reason)\n return { proposals: routed.proposals.length, ...(routed.error ? { error: routed.error } : {}) }\n}\n"],"mappings":"oLAoBO,SAASA,EACdC,EACAC,EACAC,EACuC,CACvC,IAAMC,EAASC,EAAUF,EAAE,QAASA,EAAE,KAAM,CAC1C,QAASA,EAAE,QACX,OAAQA,EAAE,SAAW,aAAe,kBAAoB,iBAAiBA,EAAE,SAC3E,KAAM,GAAGA,EAAE,WAAWA,EAAE,QAC1B,CAAC,EACD,GAAIC,EAAO,UAAU,KAAK,EAAG,CAG3B,IAAME,EAAcH,EAAE,OAAO,MAAM,OAAO,EAAE,OAAO,OAAO,EAAE,MAAM,EAAG,CAAC,EACtEF,EAAO,UAAUE,EAAE,QAAS,CAC1B,QAASA,EAAE,QACX,SAAU,aACV,QAAS,uBAAoBA,EAAE,WAAWC,EAAO,YACjD,SAAU,CAAC,gBAAiBD,EAAE,QAAS,GAAGG,CAAW,EACrD,OAAQ,CAAE,QAASH,EAAE,QAAS,OAAQA,EAAE,OAAQ,OAAQ,kBAAmB,KAAM,IAAI,KAAK,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,CAAE,CACzH,CAAC,EAKH,OAAAD,EAAS,gBAAgBC,EAAE,QAASA,EAAE,QAASA,EAAE,OAAQC,EAAO,OAAQD,EAAE,MAAM,EACzE,CAAE,UAAWC,EAAO,UAAU,OAAQ,GAAIA,EAAO,MAAQ,CAAE,MAAOA,EAAO,KAAM,EAAI,CAAC,CAAG,CAChG","names":["storeRotationMemo","memory","sessions","m","routed","routeMemo","chatKeyword"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=routing-
|
|
1
|
+
import{a,b,c,d,e,f}from"./chunk-FQLSV2C4.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{e as DEFAULT_TRIAGE_ACTIONS,a as DOWNGRADE_BELOW,b as channelKeepsConfiguredModel,c as cheapModelForEngine,d as routeTaskModel,f as triageModelFor};
|
|
2
|
+
//# sourceMappingURL=routing-LD35TJM5.js.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import{d as v,i as V,k as X,m as T}from"./chunk-U6EJ53DA.js";import{k as P}from"./chunk-H4NSB54D.js";import"./chunk-MTX4UPNB.js";import{f as g,g as O}from"./chunk-QAWKN2N4.js";import"./chunk-IMLAPB7G.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-QIJLFPWE.js";import{createHash as ue}from"crypto";import{existsSync as de,mkdirSync as pe,readFileSync as ge,writeFileSync as me}from"fs";import{resolve as B}from"path";var U="wiki-rules",x="wiki-rules",he=["deadline","due date","due by","penalt","late fee","fine of","fined","must file","must pay","must declare","must submit","filing","obligation","compliance","tax return","\xE9ch\xE9ance","date limite","d\xE9lai","p\xE9nalit","amende","majoration","d\xE9claration","obligation","\u063A\u0631\u0627\u0645\u0629","\u0623\u062C\u0644","\u0622\u062C\u0627\u0644","\u062A\u0635\u0631\u064A\u062D","\u062E\u0637\u064A\u0629"],fe=new Set(["event","agent","device","server","app","domain","account","penalty","relief","due_date","person"]),ye=new Set(["person","organization"]),we=6e3,ke=900,W=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e,S=e=>typeof e=="string"?e.replace(/\s+/g," ").trim():"",G=e=>S(e).replace(/["\[\]]/g,"").slice(0,120).trim();function Ne(e=he){let t=e.map(o=>o.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).filter(Boolean);return new RegExp(`(^|[^\\p{L}\\p{N}])(${t.join("|")})`,"iu")}function $e(e,t){return t.test(`${e.article.meta.title}
|
|
2
|
+
${P(e.article.content)}`)}function be(e,t,o=[]){let n=new Set(o.map(g)),r=i=>i.pages.every(d=>(d.article.meta.tags??[]).includes(x)),s=i=>i.type==="legal_source"?0:i.type==="obligation"?1:2;return[...e.entities.values()].filter(i=>!r(i)).filter(i=>n.size?n.has(g(i.id))||n.has(g(i.title)):i.type==="legal_source"||i.type==="obligation"||!fe.has(i.type)&&i.pages.some(d=>$e(d,t))).sort((i,d)=>s(i)-s(d)||d.sources.length-i.sources.length||i.title.localeCompare(d.title))}function Z(e,t,o,n){let r=` ${g(o)} `,s=new Set([...(e.outgoing.get(t.id)??[]).map(i=>i.to),...(e.incoming.get(t.id)??[]).map(i=>i.from)]);return[...e.entities.values()].filter(i=>n.has(i.type)&&i.id!==t.id).filter(i=>s.has(i.id)||g(i.title).length>=3&&r.includes(` ${g(i.title)} `)).slice(0,40)}function Re(e,t,o,n){let r=`${o.article.meta.title}
|
|
3
|
+
${P(o.article.content)}`,s=n(o.article.meta.sources??[]).sort((l,p)=>p.date.localeCompare(l.date)).slice(0,10),i=`${r}
|
|
4
|
+
${s.map(l=>l.content).join(`
|
|
5
|
+
`)}`,d=l=>l.pages.some(p=>v(p.article.meta,o.article.meta)),a=l=>[...e.entities.values()].filter(p=>p.type===l&&p.id!==t.id&&d(p));return{source:t,page:o,entries:s,known:a("obligation").slice(0,60),laws:a("legal_source").slice(0,40),parties:Z(e,t,i,ye).filter(d),authorities:Z(e,t,i,new Set(["organization"])).filter(d)}}function ee(e){let t=[`${e.agentId}/${e.article.path}`,P(e.article.content),...(e.article.meta.sources??[]).slice().sort()];return ue("sha1").update(t.join(`
|
|
6
|
+
`)).digest("hex").slice(0,16)}function Se(e,t){let o=t.statements.filter(n=>["action","due_rule"].includes(n.property)).map(n=>`${n.property}: ${n.value}`);return`- ${t.title}${o.length?` (${o.join("; ")})`:""}`}function We(e,t,o){let n=t.page,r=[`You are writing the rules one wiki page states, so nobody has to research them again. Today is ${o}.`,"",`## The page: ${n.agentId}/${n.article.path}: "${n.article.meta.title}"`,W(P(n.article.content),we),"","## Source entries behind the page (newest first)"];for(let s of t.entries)r.push(`### entry ${s.id} (${s.date}, ${s.agentId})`,W(s.content.trim(),ke),"");return r.push("## Rule pages that already exist",...t.known.map(s=>Se(e,s)),""),r.push("## Legal source pages",...t.laws.map(s=>`- ${s.title}`),""),r.push("## People and organizations it names",...t.parties.map(s=>`- ${s.title} (${s.type})`),""),r.push("## Task","List each rule the page or the entries state: something a person or organization must do, by a deadline or on a schedule, often with a penalty when they do not.","Return one JSON object and nothing else:",'{"rules": [{"title": "\u2026", "action": "\u2026", "bearer": ["\u2026"], "deadline": "\u2026", "amount": "\u2026", "authority": "\u2026", "penalty": "\u2026", "basis": "\u2026", "procedure": "\u2026", "source": "\u2026"}]}',"","Rules:",'- title: a short name for the rule, such as "Monthly payroll tax filing". When it is one of the rule pages that already exist, use that title exactly.',"- action: what must be done, in one sentence. A rule without one is dropped.",'- bearer: who must do it. Use a listed person or organization title when it is one, else a short description such as "every employer".','- deadline: when, as the rule says it ("by the 15th of the following month"), not a computed date.',"- amount: what is paid or declared, if the rule says. authority: who it is filed with or paid to.","- penalty: what happens when it is late or missing, as stated.","- basis: the law, article or document it comes from. Use a listed legal source title when it is one.","- procedure: how it is done, in one sentence, if stated.","- source: the entry id or the page (agent/path) the rule comes from. A rule without one is dropped.","- Leave a field empty when the page and entries do not state it. Never guess a deadline, an amount or a penalty.","- Do not list one-time tasks, reminders or plans; only standing rules.","- Write in the language the page is written in.",'- No rules on the page: return {"rules": []}.'),r.join(`
|
|
7
|
+
`)}function _e(e,t,o){let n=[],r=t.page,s=[...t.entries.map(l=>l.id),`${r.agentId}/${r.article.path}`,r.article.path],i=new Map(t.known.map(l=>[g(l.title),l])),d=[],a=new Set;for(let l of Array.isArray(e.rules)?e.rules:[]){let p=l??{},c=G(S(p.title)),u=W(S(p.action),400),$=S(p.source);if(!c){n.push("a rule with no title");continue}if(!u){n.push(`${c}: no action`);continue}if(!$||!s.some(R=>$.includes(R))){n.push(`${c}: source not among those given`);continue}if(a.has(g(c)))continue;a.add(g(c));let f=i.get(g(c)),w=o.names.get(g(c)),y=!f&&w?o.entities.get(w):void 0;if(y&&y.type!=="obligation"){n.push(`${c}: a page of type ${y.type} already has this title`);continue}let _=(Array.isArray(p.bearer)?p.bearer:[p.bearer]).map(R=>W(S(R),120)).filter(Boolean);d.push({title:f?.title??y?.title??c,existing:f??y,action:u,bearers:[...new Set(_)].slice(0,5),deadline:W(S(p.deadline),200),amount:W(S(p.amount),200),authority:W(S(p.authority),120),penalty:W(S(p.penalty),300),basis:W(S(p.basis),200),procedure:W(S(p.procedure),400),source:W($,200)})}return{rules:d,dropped:n}}function D(e,t){return t.find(n=>g(n.title)===g(e))?.title??e}function j(e,t){let o=r=>r&&/^\d{4}-\d{2}-\d{2}/.test(r)?r.slice(0,10):void 0;return t.entries.filter(r=>e.source.includes(r.id)).map(r=>o(r.date)).filter(Boolean).sort().at(-1)??o(t.entries[0]?.date)??o(t.page.article.meta.created)}function ve(e,t){let o=j(e,t),n=(s,i)=>({property:s,value:i,source:e.source,...o?{checked_at:o}:{},status:"proposed",by:U}),r=[n("action",e.action)];for(let s of e.bearers)r.push(n("bearer",D(s,t.parties)));return e.deadline&&r.push(n("due_rule",e.deadline)),e.amount&&r.push(n("amount_rule",e.amount)),e.authority&&r.push(n("authority",D(e.authority,t.authorities))),r.push(n("created_by",e.basis?D(e.basis,t.laws):t.page.article.meta.title)),e.procedure&&r.push(n("procedure",e.procedure)),r}var re=new Set(["action","due_rule","amount_rule","authority","created_by","procedure"]);function xe(e,t,o){let n=e.filter(i=>i.by===U),r=new Set(t.filter(i=>i.property!=="created_by"||o.basis||!n.some(d=>d.property==="created_by")).map(i=>i.property)),s=t.filter(i=>r.has(i.property));for(let i of n)(re.has(i.property)?!r.has(i.property):!s.some(d=>d.property===i.property&&g(d.value)===g(i.value)))&&s.push(i);return s}function te(e,t,o){let n=(e.statements??[]).filter(a=>a.by!==U||a.status==="confirmed"),r=new Set(n.filter(a=>a.status==="confirmed"&&re.has(a.property)).map(a=>a.property)),s=a=>`${a.property}
|
|
8
|
+
${g(a.value)}`,i=new Set(n.map(s)),d=[...n,...t.filter(a=>!r.has(a.property)&&!i.has(s(a)))];return{...e,statements:d.length?d:void 0,lastUpdated:o}}var Y="not found in the sources yet";function Ee(e,t,o){let n=c=>e.filter(u=>u.property===c),r=c=>e.find(u=>u.property===c),s=r("action"),i=c=>c&&c.source&&c.source!==s?.source?` (from ${c.source}${c.checked_at?`, ${c.checked_at}`:""})`:"",d=(c,u)=>`- **${c}:** ${u?`${u.value}${i(u)}`:Y}`,a=[...new Set([...e,...t?[t]:[]].map(c=>c.source).filter(c=>!!c))],l=[...e.filter(c=>["action","due_rule"].includes(c.property)),...t?[t]:[]].map(c=>c.checked_at).filter(c=>!!c).sort(),p=r("created_by")?.value;return[d("What to do",s),`- **Who:** ${n("bearer").length?n("bearer").map(c=>c.value).join(", "):Y}`,d("Deadline",r("due_rule")),...r("amount_rule")?[d("Amount",r("amount_rule"))]:[],...r("authority")?[d("Filed with",r("authority"))]:[],`- **Penalty:** ${t?`${t.value}${i(t)}`:Y}`,`- **Source:** ${p?`${p}, `:""}last read from [[${o}]]${a.length?` (sources: ${a.join(", ")})`:""}`,`- **Source date:** ${l[0]??"not known"}. Not yet checked with the law or the authority.`].join(`
|
|
9
|
+
`)}var ne="## Rule summary",z="<!-- /rule-summary -->";function Ae(e,t){let o=`${ne}
|
|
10
|
+
|
|
11
|
+
${t.trim()}
|
|
12
|
+
|
|
13
|
+
${z}
|
|
14
|
+
`,n=e.indexOf(`${ne}
|
|
15
|
+
`),r=n<0?-1:e.indexOf(z,n);return n>=0&&r>=0?`${e.slice(0,n)}${o}${e.slice(r+z.length).replace(/^\n/,"")}`:`${o}
|
|
16
|
+
${e.trim()}
|
|
17
|
+
`}function Fe(e){let t=B(e,"_rules","state.json");if(!de(t))return{sources:{}};try{let o=JSON.parse(ge(t,"utf-8"));return o&&typeof o.sources=="object"?o:{sources:{}}}catch{return{sources:{}}}}function Le(e,t){pe(B(e,"_rules"),{recursive:!0}),me(B(e,"_rules","state.json"),JSON.stringify(t,null,2))}function Ie(e,t,o,n,r){let s=o.page,i=n.get(g(t.title));if(i)return v(s.article.meta,i.meta)?i:"the rule page is readable by agents who cannot read the source";if(t.existing){let c=T(e,t.existing);if(!c)return"the rule page was copied from another machine";let u=e.getAgentWiki(c.agentId).readArticle(c.article.path);return u?v(s.article.meta,u.meta)?{agentId:c.agentId,path:c.article.path,meta:u.meta,content:u.content,created:!1}:"the rule page is readable by agents who cannot read the source":"the rule page was moved or removed during the run"}let d=s.article.meta.owner||s.agentId,a=e.getAgentWiki(s.agentId),l=`obligations/${O(t.title)}.md`;for(let c=2;a.readArticle(l);c++)l=`obligations/${O(t.title)}-${c}.md`;let p={title:t.title,class:"obligation",tags:[x],owner:d,access:s.article.meta.access,sharedWith:s.article.meta.sharedWith,created:r,lastUpdated:r,sources:[]};return{agentId:s.agentId,path:l,meta:p,content:`${t.title}.
|
|
18
|
+
`,created:!0}}var se=e=>`penalties/${O(G(`${e} penalty`))}.md`;function Pe(e,t,o,n){let r=i=>{let d=(i??[]).filter(l=>l.property==="amount_rule"&&l.value),a=d.find(l=>l.status==="confirmed")??d[0];return a?{value:a.value,source:a.source,checked_at:a.checked_at,...a.status==="confirmed"?{confirmed:!0}:{}}:void 0},s=e.getAgentWiki(n.agentId).readArticle(se(o));if(s&&(s.meta.tags??[]).includes(x))return r(s.meta.statements);for(let i of t.entities.values()){if(i.type!=="penalty"||!i.statements.some(l=>l.property==="penalty_for"&&g(l.value)===g(o)))continue;let d=i.pages.find(l=>v(n.meta,l.article.meta)),a=d&&r(d.article.meta.statements);if(a)return a}}function Ue(e,t,o,n){let r=G(`${e.title} penalty`),s=j(e,o),i=(a,l)=>({property:a,value:l,source:e.source,...s?{checked_at:s}:{},status:"proposed",by:U}),d=[i("penalty_for",e.title),i("amount_rule",e.penalty),i("created_by",e.basis?D(e.basis,o.laws):o.page.article.meta.title)];return{path:se(e.title),meta:{title:r,class:"penalty",tags:[x],owner:t.meta.owner,access:t.meta.access,sharedWith:t.meta.sharedWith,created:n,lastUpdated:n,sources:t.meta.sources,statements:d,related:[e.title]},content:`## Overview
|
|
19
|
+
|
|
20
|
+
${e.penalty}
|
|
21
|
+
|
|
22
|
+
For [[${e.title}]]. Source: ${e.source}${s?`, dated ${s}`:""}. Not yet checked with the law or the authority.
|
|
23
|
+
`}}function ie(e,t,o,n,r,s){let i=[];for(let d of t.bearers){let a=o.parties.find(y=>g(y.title)===g(d));if(!a)continue;let l=T(e,a);if(!l){s.push(`${t.title} \u2192 ${a.title}: page copied from another machine`);continue}if(!v(n.meta,l.article.meta)){s.push(`${t.title} \u2192 ${a.title}: page readable by agents who cannot read the rule`);continue}let p=y=>(y.statements??[]).some(_=>_.property==="subject_to"&&g(_.value)===g(t.title));if(p(l.article.meta))continue;if(r){i.push(a.title);continue}let c=e.getAgentWiki(l.agentId),u=c.readArticle(l.article.path);if(!u){s.push(`${t.title} \u2192 ${a.title}: page moved or removed during the run`);continue}if(!v(n.meta,u.meta)){s.push(`${t.title} \u2192 ${a.title}: page readable by agents who cannot read the rule`);continue}if(p(u.meta))continue;let $=j(t,o),f=[...u.meta.statements??[],{property:"subject_to",value:t.title,source:t.source,...$?{checked_at:$}:{},status:"proposed",by:U}],w={...u.meta,statements:f};c.writeArticle(l.article.path,w,u.content,u.meta.owner||l.agentId)?(l.article.meta=w,i.push(a.title)):s.push(`${t.title} \u2192 ${a.title}: write refused`)}return i}async function He(e,t,o,n,r){let s=u=>r.sources[u.id]?.failures??0,i=be(t,n.words,n.only).sort((u,$)=>s(u)-s($)),d=u=>e.getSharedStore().readEntries(u),a={outcomes:[],costUsd:0,capped:!1},l=new Map,p=0,c=(u,$,f,w=!1)=>{if(n.dryRun)return;let y=r.sources[u];r.sources[u]=w?{fingerprint:y?.fingerprint??"",at:new Date().toISOString(),costUsd:f,failures:(y?.failures??0)+1}:{fingerprint:$,at:new Date().toISOString(),costUsd:f},n.save?.(r)};for(let u of i){if(p>=n.max)break;let $={source:u.id,title:u.title,rules:[],costUsd:0,dropped:[]},f=T(e,u);if(!f){n.only.length&&a.outcomes.push({...$,status:"no-page"});continue}let w=Re(t,u,f,d),y=ee(f);if(!n.force&&r.sources[u.id]?.fingerprint===y){n.only.length&&a.outcomes.push({...$,status:"unchanged"});continue}if(a.costUsd>=n.maxCostUsd){a.capped=!0;break}p++;let _=`${f.agentId}/${f.article.path}`,R;try{R=await o(We(t,w,n.today))}catch(m){a.outcomes.push({...$,page:_,status:"failed",dropped:[m.message.slice(0,200)]}),c(u.id,y,0,!0);continue}a.costUsd+=R.costUsd;let b={...$,page:_,status:"no-reply",costUsd:R.costUsd},J=V(R.text);if(!J){a.outcomes.push(b),c(u.id,y,R.costUsd);continue}let M=_e(J,w,t);if(b.dropped=M.dropped,M.rules.length===0){b.status="no-rules",a.outcomes.push(b),c(u.id,y,R.costUsd);continue}let N=!1;for(let m of M.rules){let h=Ie(e,m,w,l,n.today);if(typeof h=="string"){b.dropped.push(`${m.title}: ${h}`);continue}let ae=xe(h.meta.statements??[],ve(m,w),m),q=te(h.meta,ae,n.today),F=Pe(e,t,m.title,h),L=F?.confirmed||!m.penalty?F:{value:m.penalty,source:m.source,checked_at:j(m,w)},H=Ee(q.statements??[],L,f.article.meta.title),Q=(h.meta.tags??[]).includes(x)?X(h.content,H):Ae(h.content,H),oe=[...new Set([...h.meta.related??[],f.article.meta.title,...L?[G(`${m.title} penalty`)]:[]])],ce=[...new Set([...h.meta.sources??[],...w.entries.filter(k=>m.source.includes(k.id)).map(k=>k.id)])],E={...q,related:oe,sources:ce},A={title:m.title,page:`${h.agentId}/${h.path}`,created:h.created,deadline:(E.statements??[]).some(k=>k.property==="due_rule"),penalty:!!L,linked:[]};if(n.dryRun){A.preview=H,A.linked=ie(e,m,w,h,!0,b.dropped),b.rules.push(A);continue}let I=e.getAgentWiki(h.agentId);if(!I.writeArticle(h.path,E,Q,h.meta.owner||h.agentId)){b.dropped.push(`${m.title}: write refused`),N=!0;continue}if(l.set(g(m.title),{...h,meta:E,content:Q,created:!1}),m.penalty&&!F?.confirmed){let k=Ue(m,{...h,meta:E},w,n.today),C=I.readArticle(k.path);if(!C)I.writeArticle(k.path,k.meta,k.content,k.meta.owner);else if((C.meta.tags??[]).includes(x)){let le=te({...k.meta,created:C.meta.created,statements:C.meta.statements},k.meta.statements??[],n.today);I.writeArticle(k.path,le,k.content,k.meta.owner)}else b.dropped.push(`${m.title}: ${k.path} already exists`)}A.linked=ie(e,m,w,{...h,meta:E},!1,b.dropped),I.rebuildIndex(),b.rules.push(A)}b.status=n.dryRun?"dry-run":b.rules.length?"written":N?"failed":"no-rules",a.outcomes.push(b);let K=n.dryRun?null:e.getAgentWiki(f.agentId).readArticle(f.article.path);K&&(y=ee({agentId:f.agentId,article:K})),c(u.id,y,R.costUsd,N&&b.rules.length===0)}return a}export{he as DEFAULT_RULE_WORDS,U as RULES_BY,x as RULES_TAG,We as buildRulesPrompt,_e as checkRules,Pe as knownPenalty,Fe as loadRulesState,xe as mergeRuleStatements,Ee as ruleOverview,be as ruleSources,ve as ruleStatements,Ne as ruleWordsPattern,Re as rulesContext,ee as rulesFingerprint,He as runRules,Le as saveRulesState,j as sourceDate,$e as statesRules,te as withRuleStatements,Ae as withRuleSummary};
|
|
24
|
+
//# sourceMappingURL=rules-HUUFXQD6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/rules.ts"],"sourcesContent":["// --- Rule pages: one page per obligation, with deadline, penalty, source and check date (#811) ---\n//\n// Agents research the same rule again and again (a filing deadline, a\n// late fee) because the answer stays inside the page or chat where it\n// came up. This job reads the pages that state rules: legal sources,\n// obligation pages agents wrote, and any other page whose text speaks of\n// deadlines, penalties or filings. One model call per source page\n// returns the rules it states. Each rule is checked against what the\n// call was shown, then written once as an obligation page:\n// - statements for the obligation lens (action, bearer, due, amount,\n// authority, created by, procedure), each with its source and the\n// date of that source, marked proposed until the owner confirms them;\n// - a penalty page linked to it with `penalty_for`;\n// - `subject_to` on the page of each person or organization that must\n// follow it, so their Obligations panel lists it.\n// A later source that states less keeps what an earlier one stated: a\n// field is replaced only when the new source gives it. The model gets no\n// tools and every write goes through the store, which keeps the old version.\n\nimport { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport type { WikiHub } from \"./hub\"\nimport type { WikiArticleMeta, WikiEntry } from \"./types\"\nimport { normName, slugify, type Entity, type GraphPage, type WikiGraph } from \"./ontology/graph\"\nimport type { WikiStatement } from \"./ontology/types\"\nimport { bodyOf } from \"./ontology/view-entity\"\nimport { parseEnrichReply, readableAlongside, targetPage, withOverview, type EnrichCall } from \"./enrich\"\n\nexport const RULES_BY = \"wiki-rules\"\n/** Tag on the pages this job creates; they are never read as a source. */\nexport const RULES_TAG = \"wiki-rules\"\n\n/** Words that mark a page as stating a rule. Stems, matched at a word start. */\nexport const DEFAULT_RULE_WORDS = [\n \"deadline\", \"due date\", \"due by\", \"penalt\", \"late fee\", \"fine of\", \"fined\", \"must file\", \"must pay\", \"must declare\",\n \"must submit\", \"filing\", \"obligation\", \"compliance\", \"tax return\",\n \"échéance\", \"date limite\", \"délai\", \"pénalit\", \"amende\", \"majoration\", \"déclaration\", \"obligation\",\n \"غرامة\", \"أجل\", \"آجال\", \"تصريح\", \"خطية\",\n]\n\n/** Types never read as a rule source: things that happen or run, not rules. */\nconst SKIP_TYPES = new Set([\"event\", \"agent\", \"device\", \"server\", \"app\", \"domain\", \"account\", \"penalty\", \"relief\", \"due_date\", \"person\"])\n/** Types a rule's bearer may link to; anything else stays text. */\nconst BEARER_TYPES = new Set([\"person\", \"organization\"])\n\nconst PAGE_CHARS = 6000\nconst ENTRY_CHARS = 900\nconst clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s)\nconst str = (v: unknown): string => (typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\")\n/** Frontmatter keeps a title on one quoted line. */\nconst cleanTitle = (s: string) => str(s).replace(/[\"\\[\\]]/g, \"\").slice(0, 120).trim()\n\nexport function ruleWordsPattern(words: string[] = DEFAULT_RULE_WORDS): RegExp {\n const escaped = words.map(w => w.trim().replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).filter(Boolean)\n return new RegExp(`(^|[^\\\\p{L}\\\\p{N}])(${escaped.join(\"|\")})`, \"iu\")\n}\n\nexport interface RulesContext {\n /** The entity whose page is read. */\n source: Entity\n page: GraphPage\n entries: WikiEntry[]\n /** Obligation pages that already exist, so a known rule is updated, not doubled. */\n known: Entity[]\n /** Legal source pages a rule may cite as its basis. */\n laws: Entity[]\n /** People and organizations the page links or names. */\n parties: Entity[]\n /** Organizations a rule may name as its authority. */\n authorities: Entity[]\n}\n\nexport interface RuleDraft {\n title: string\n /** Set when the rule matches an existing obligation page. */\n existing?: Entity\n action: string\n bearers: string[]\n deadline: string\n amount: string\n authority: string\n penalty: string\n basis: string\n procedure: string\n source: string\n}\n\nexport interface RulesResult {\n rules: RuleDraft[]\n dropped: string[]\n}\n\n/** True when the page reads like it states a rule. */\nexport function statesRules(page: GraphPage, words: RegExp): boolean {\n return words.test(`${page.article.meta.title}\\n${bodyOf(page.article.content)}`)\n}\n\n/**\n * Entities whose page this job reads: legal sources and obligation pages\n * first, then any other page whose text matches the rule words. Pages\n * this job created are skipped.\n */\nexport function ruleSources(g: WikiGraph, words: RegExp, only: string[] = []): Entity[] {\n const wanted = new Set(only.map(normName))\n const ours = (e: Entity) => e.pages.every(p => (p.article.meta.tags ?? []).includes(RULES_TAG))\n const rank = (e: Entity) => (e.type === \"legal_source\" ? 0 : e.type === \"obligation\" ? 1 : 2)\n return [...g.entities.values()]\n .filter(e => !ours(e))\n .filter(e => wanted.size\n ? wanted.has(normName(e.id)) || wanted.has(normName(e.title))\n : e.type === \"legal_source\" || e.type === \"obligation\" || (!SKIP_TYPES.has(e.type) && e.pages.some(p => statesRules(p, words))))\n .sort((a, b) => rank(a) - rank(b) || b.sources.length - a.sources.length || a.title.localeCompare(b.title))\n}\n\n/** Entities of a type whose title appears in the text, or linked to `e`. */\nfunction partiesOf(g: WikiGraph, e: Entity, text: string, types: Set<string>): Entity[] {\n const hay = ` ${normName(text)} `\n const linked = new Set([...(g.outgoing.get(e.id) ?? []).map(x => x.to), ...(g.incoming.get(e.id) ?? []).map(x => x.from)])\n return [...g.entities.values()]\n .filter(x => types.has(x.type) && x.id !== e.id)\n .filter(x => linked.has(x.id) || (normName(x.title).length >= 3 && hay.includes(` ${normName(x.title)} `)))\n .slice(0, 40)\n}\n\n/** What one call for `source` may read: its page and the entries behind it. */\nexport function rulesContext(g: WikiGraph, source: Entity, page: GraphPage, readEntries: (ids: string[]) => WikiEntry[]): RulesContext {\n const text = `${page.article.meta.title}\\n${bodyOf(page.article.content)}`\n const entries = readEntries(page.article.meta.sources ?? []).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 10)\n const all = `${text}\\n${entries.map(x => x.content).join(\"\\n\")}`\n const visible = (x: Entity) => x.pages.some(p => readableAlongside(p.article.meta, page.article.meta))\n const of = (type: string) => [...g.entities.values()].filter(x => x.type === type && x.id !== source.id && visible(x))\n return {\n source,\n page,\n entries,\n known: of(\"obligation\").slice(0, 60),\n laws: of(\"legal_source\").slice(0, 40),\n parties: partiesOf(g, source, all, BEARER_TYPES).filter(visible),\n authorities: partiesOf(g, source, all, new Set([\"organization\"])).filter(visible),\n }\n}\n\n/** Changes when the source page's text or the entries behind it change.\n * A `subject_to` link this job adds to the page does not change it. */\nexport function rulesFingerprint(page: GraphPage): string {\n const parts = [`${page.agentId}/${page.article.path}`, bodyOf(page.article.content), ...(page.article.meta.sources ?? []).slice().sort()]\n return createHash(\"sha1\").update(parts.join(\"\\n\")).digest(\"hex\").slice(0, 16)\n}\n\nfunction knownLine(g: WikiGraph, e: Entity): string {\n const facts = e.statements.filter(s => [\"action\", \"due_rule\"].includes(s.property)).map(s => `${s.property}: ${s.value}`)\n return `- ${e.title}${facts.length ? ` (${facts.join(\"; \")})` : \"\"}`\n}\n\nexport function buildRulesPrompt(g: WikiGraph, ctx: RulesContext, today: string): string {\n const p = ctx.page\n const lines = [\n `You are writing the rules one wiki page states, so nobody has to research them again. Today is ${today}.`,\n \"\",\n `## The page: ${p.agentId}/${p.article.path}: \"${p.article.meta.title}\"`,\n clip(bodyOf(p.article.content), PAGE_CHARS),\n \"\",\n \"## Source entries behind the page (newest first)\",\n ]\n for (const en of ctx.entries) lines.push(`### entry ${en.id} (${en.date}, ${en.agentId})`, clip(en.content.trim(), ENTRY_CHARS), \"\")\n lines.push(\"## Rule pages that already exist\", ...ctx.known.map(e => knownLine(g, e)), \"\")\n lines.push(\"## Legal source pages\", ...ctx.laws.map(e => `- ${e.title}`), \"\")\n lines.push(\"## People and organizations it names\", ...ctx.parties.map(e => `- ${e.title} (${e.type})`), \"\")\n lines.push(\n \"## Task\",\n \"List each rule the page or the entries state: something a person or organization must do, by a deadline or on a schedule, often with a penalty when they do not.\",\n \"Return one JSON object and nothing else:\",\n `{\"rules\": [{\"title\": \"…\", \"action\": \"…\", \"bearer\": [\"…\"], \"deadline\": \"…\", \"amount\": \"…\", \"authority\": \"…\", \"penalty\": \"…\", \"basis\": \"…\", \"procedure\": \"…\", \"source\": \"…\"}]}`,\n \"\",\n \"Rules:\",\n \"- title: a short name for the rule, such as \\\"Monthly payroll tax filing\\\". When it is one of the rule pages that already exist, use that title exactly.\",\n \"- action: what must be done, in one sentence. A rule without one is dropped.\",\n \"- bearer: who must do it. Use a listed person or organization title when it is one, else a short description such as \\\"every employer\\\".\",\n \"- deadline: when, as the rule says it (\\\"by the 15th of the following month\\\"), not a computed date.\",\n \"- amount: what is paid or declared, if the rule says. authority: who it is filed with or paid to.\",\n \"- penalty: what happens when it is late or missing, as stated.\",\n \"- basis: the law, article or document it comes from. Use a listed legal source title when it is one.\",\n \"- procedure: how it is done, in one sentence, if stated.\",\n \"- source: the entry id or the page (agent/path) the rule comes from. A rule without one is dropped.\",\n \"- Leave a field empty when the page and entries do not state it. Never guess a deadline, an amount or a penalty.\",\n \"- Do not list one-time tasks, reminders or plans; only standing rules.\",\n \"- Write in the language the page is written in.\",\n \"- No rules on the page: return {\\\"rules\\\": []}.\",\n )\n return lines.join(\"\\n\")\n}\n\n/** Keep only rules with an action and a source the call was shown. */\nexport function checkRules(raw: Record<string, unknown>, ctx: RulesContext, g: WikiGraph): RulesResult {\n const dropped: string[] = []\n const p = ctx.page\n const sourceIds = [...ctx.entries.map(x => x.id), `${p.agentId}/${p.article.path}`, p.article.path]\n const known = new Map(ctx.known.map(e => [normName(e.title), e]))\n const rules: RuleDraft[] = []\n const seen = new Set<string>()\n for (const item of Array.isArray(raw.rules) ? raw.rules : []) {\n const r = (item ?? {}) as Record<string, unknown>\n const title = cleanTitle(str(r.title))\n const action = clip(str(r.action), 400)\n const source = str(r.source)\n if (!title) { dropped.push(\"a rule with no title\"); continue }\n if (!action) { dropped.push(`${title}: no action`); continue }\n if (!source || !sourceIds.some(id => source.includes(id))) { dropped.push(`${title}: source not among those given`); continue }\n if (seen.has(normName(title))) continue\n seen.add(normName(title))\n const existing = known.get(normName(title))\n const taken = g.names.get(normName(title))\n const clash = !existing && taken ? g.entities.get(taken) : undefined\n if (clash && clash.type !== \"obligation\") { dropped.push(`${title}: a page of type ${clash.type} already has this title`); continue }\n const bearers = (Array.isArray(r.bearer) ? r.bearer : [r.bearer]).map(b => clip(str(b), 120)).filter(Boolean)\n rules.push({\n title: existing?.title ?? clash?.title ?? title,\n existing: existing ?? clash,\n action,\n bearers: [...new Set(bearers)].slice(0, 5),\n deadline: clip(str(r.deadline), 200),\n amount: clip(str(r.amount), 200),\n authority: clip(str(r.authority), 120),\n penalty: clip(str(r.penalty), 300),\n basis: clip(str(r.basis), 200),\n procedure: clip(str(r.procedure), 400),\n source: clip(source, 200),\n })\n }\n return { rules, dropped }\n}\n\n/** The title of a listed page when `value` names one, else the value. */\nfunction asPage(value: string, list: Entity[]): string {\n const hit = list.find(e => normName(e.title) === normName(value))\n return hit?.title ?? value\n}\n\n/**\n * The date of what the rule was read from: the entry it cites, else the\n * newest entry behind the page, else the day the page was created. Never\n * the run date: nothing was checked at the law or the authority.\n */\nexport function sourceDate(r: Pick<RuleDraft, \"source\">, ctx: RulesContext): string | undefined {\n const day = (d?: string) => (d && /^\\d{4}-\\d{2}-\\d{2}/.test(d) ? d.slice(0, 10) : undefined)\n const cited = ctx.entries.filter(x => r.source.includes(x.id)).map(x => day(x.date)).filter(Boolean).sort()\n return cited.at(-1) ?? day(ctx.entries[0]?.date) ?? day(ctx.page.article.meta.created)\n}\n\n/** Statements an obligation page gets for one rule, proposed until the owner confirms them. */\nexport function ruleStatements(r: RuleDraft, ctx: RulesContext): WikiStatement[] {\n const checked = sourceDate(r, ctx)\n const st = (property: string, value: string): WikiStatement => ({\n property, value, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\", by: RULES_BY,\n })\n const out = [st(\"action\", r.action)]\n for (const b of r.bearers) out.push(st(\"bearer\", asPage(b, ctx.parties)))\n if (r.deadline) out.push(st(\"due_rule\", r.deadline))\n if (r.amount) out.push(st(\"amount_rule\", r.amount))\n if (r.authority) out.push(st(\"authority\", asPage(r.authority, ctx.authorities)))\n out.push(st(\"created_by\", r.basis ? asPage(r.basis, ctx.laws) : ctx.page.article.meta.title))\n if (r.procedure) out.push(st(\"procedure\", r.procedure))\n return out\n}\n\n/** Properties a rule holds one value of; `bearer` may hold several. */\nconst SINGLE = new Set([\"action\", \"due_rule\", \"amount_rule\", \"authority\", \"created_by\", \"procedure\"])\n\n/**\n * This job's statements for a rule after reading one more source: a\n * field the new source states replaces the earlier one; a field it leaves\n * empty keeps the earlier value with its own source and date. A basis the\n * new source does not name (`created_by` set to the page read) does not\n * replace a law an earlier source named. Bearers add up.\n */\nexport function mergeRuleStatements(earlier: WikiStatement[], fresh: WikiStatement[], r: Pick<RuleDraft, \"basis\">): WikiStatement[] {\n const prev = earlier.filter(s => s.by === RULES_BY)\n const stated = new Set(fresh.filter(s => s.property !== \"created_by\" || r.basis || !prev.some(p => p.property === \"created_by\")).map(s => s.property))\n const out = fresh.filter(s => stated.has(s.property))\n for (const s of prev) {\n if (SINGLE.has(s.property) ? !stated.has(s.property) : !out.some(o => o.property === s.property && normName(o.value) === normName(s.value))) out.push(s)\n }\n return out\n}\n\n/** Statements merged in: this job's earlier ones replaced, others kept. A\n * statement the owner confirmed stays, and wins over a new value. */\nexport function withRuleStatements(meta: WikiArticleMeta, statements: WikiStatement[], today: string): WikiArticleMeta {\n const kept = (meta.statements ?? []).filter(s => s.by !== RULES_BY || s.status === \"confirmed\")\n const confirmed = new Set(kept.filter(s => s.status === \"confirmed\" && SINGLE.has(s.property)).map(s => s.property))\n const key = (s: WikiStatement) => `${s.property}\\n${normName(s.value)}`\n const taken = new Set(kept.map(key))\n const all = [...kept, ...statements.filter(s => !confirmed.has(s.property) && !taken.has(key(s)))]\n return { ...meta, statements: all.length ? all : undefined, lastUpdated: today }\n}\n\n/** A penalty as stated, with where it was read and that source's date. */\nexport interface PenaltyFact {\n value: string\n source?: string\n checked_at?: string\n /** The owner confirmed it: it wins over what a new source states. */\n confirmed?: boolean\n}\n\nconst missing = \"not found in the sources yet\"\n\n/** The plain-words summary at the top of an obligation page, built from\n * the statements the page holds after the merge. */\nexport function ruleOverview(statements: WikiStatement[], penalty: PenaltyFact | undefined, readFrom: string): string {\n const all = (p: string) => statements.filter(s => s.property === p)\n const one = (p: string) => statements.find(s => s.property === p)\n const action = one(\"action\")\n // A field read from another source than the action says which.\n const from = (s?: { source?: string; checked_at?: string }) =>\n s && s.source && s.source !== action?.source ? ` (from ${s.source}${s.checked_at ? `, ${s.checked_at}` : \"\"})` : \"\"\n const line = (label: string, s?: WikiStatement) => `- **${label}:** ${s ? `${s.value}${from(s)}` : missing}`\n const sources = [...new Set([...statements, ...(penalty ? [penalty] : [])].map(s => s.source).filter((x): x is string => !!x))]\n const dates = [...statements.filter(s => [\"action\", \"due_rule\"].includes(s.property)), ...(penalty ? [penalty] : [])]\n .map(s => s.checked_at).filter((x): x is string => !!x).sort()\n const basis = one(\"created_by\")?.value\n return [\n line(\"What to do\", action),\n `- **Who:** ${all(\"bearer\").length ? all(\"bearer\").map(s => s.value).join(\", \") : missing}`,\n line(\"Deadline\", one(\"due_rule\")),\n ...(one(\"amount_rule\") ? [line(\"Amount\", one(\"amount_rule\"))] : []),\n ...(one(\"authority\") ? [line(\"Filed with\", one(\"authority\"))] : []),\n `- **Penalty:** ${penalty ? `${penalty.value}${from(penalty)}` : missing}`,\n `- **Source:** ${basis ? `${basis}, ` : \"\"}last read from [[${readFrom}]]${sources.length ? ` (sources: ${sources.join(\", \")})` : \"\"}`,\n `- **Source date:** ${dates[0] ?? \"not known\"}. Not yet checked with the law or the authority.`,\n ].join(\"\\n\")\n}\n\nconst SUMMARY_HEAD = \"## Rule summary\"\nconst SUMMARY_END = \"<!-- /rule-summary -->\"\n\n/**\n * The summary on a page this job did not create. It goes in its own\n * section, which only this job rewrites, so the page's own Overview is\n * never replaced.\n */\nexport function withRuleSummary(content: string, summary: string): string {\n const section = `${SUMMARY_HEAD}\\n\\n${summary.trim()}\\n\\n${SUMMARY_END}\\n`\n const start = content.indexOf(`${SUMMARY_HEAD}\\n`)\n const end = start < 0 ? -1 : content.indexOf(SUMMARY_END, start)\n if (start >= 0 && end >= 0) return `${content.slice(0, start)}${section}${content.slice(end + SUMMARY_END.length).replace(/^\\n/, \"\")}`\n return `${section}\\n${content.trim()}\\n`\n}\n\nexport interface RulesState {\n sources: Record<string, { fingerprint: string; at: string; costUsd?: number; failures?: number }>\n}\n\nexport function loadRulesState(wikiDir: string): RulesState {\n const file = resolve(wikiDir, \"_rules\", \"state.json\")\n if (!existsSync(file)) return { sources: {} }\n try {\n const v = JSON.parse(readFileSync(file, \"utf-8\"))\n return v && typeof v.sources === \"object\" ? v : { sources: {} }\n } catch {\n return { sources: {} }\n }\n}\n\nexport function saveRulesState(wikiDir: string, state: RulesState): void {\n mkdirSync(resolve(wikiDir, \"_rules\"), { recursive: true })\n writeFileSync(resolve(wikiDir, \"_rules\", \"state.json\"), JSON.stringify(state, null, 2))\n}\n\nexport interface RulesOptions {\n /** Entity ids or titles; empty means every page that states rules. */\n only: string[]\n words: RegExp\n max: number\n maxCostUsd: number\n dryRun: boolean\n force: boolean\n today: string\n save?: (state: RulesState) => void\n}\n\nexport interface RuleWrite {\n title: string\n /** agent/path of the obligation page. */\n page: string\n created: boolean\n deadline: boolean\n penalty: boolean\n /** Bearer pages that got a `subject_to` link. */\n linked: string[]\n /** Dry runs: the summary that would be written. */\n preview?: string\n}\n\nexport interface RulesOutcome {\n source: string\n title: string\n page?: string\n status: \"written\" | \"dry-run\" | \"unchanged\" | \"no-page\" | \"no-reply\" | \"no-rules\" | \"failed\"\n rules: RuleWrite[]\n costUsd: number\n dropped: string[]\n}\n\nexport interface RulesRun {\n outcomes: RulesOutcome[]\n costUsd: number\n capped: boolean\n}\n\ninterface Target {\n agentId: string\n path: string\n meta: WikiArticleMeta\n content: string\n created: boolean\n}\n\n/**\n * Where a rule is written: the existing obligation page when one is\n * owned here and no wider audience than the source can read it, else a\n * new page in the source page's wiki with the source page's access.\n */\nfunction ruleTarget(hub: WikiHub, r: RuleDraft, ctx: RulesContext, made: Map<string, Target>, today: string): Target | string {\n const src = ctx.page\n const again = made.get(normName(r.title))\n if (again) return readableAlongside(src.article.meta, again.meta) ? again : \"the rule page is readable by agents who cannot read the source\"\n if (r.existing) {\n const page = targetPage(hub, r.existing)\n if (!page) return \"the rule page was copied from another machine\"\n // The run waited for the model: merge onto what is on disk now, not\n // the copy read when the run started.\n const now = hub.getAgentWiki(page.agentId).readArticle(page.article.path)\n if (!now) return \"the rule page was moved or removed during the run\"\n if (!readableAlongside(src.article.meta, now.meta)) return \"the rule page is readable by agents who cannot read the source\"\n return { agentId: page.agentId, path: page.article.path, meta: now.meta, content: now.content, created: false }\n }\n const owner = src.article.meta.owner || src.agentId\n const store = hub.getAgentWiki(src.agentId)\n let path = `obligations/${slugify(r.title)}.md`\n for (let n = 2; store.readArticle(path); n++) path = `obligations/${slugify(r.title)}-${n}.md`\n const meta: WikiArticleMeta = {\n title: r.title, class: \"obligation\", tags: [RULES_TAG], owner, access: src.article.meta.access,\n sharedWith: src.article.meta.sharedWith, created: today, lastUpdated: today, sources: [],\n }\n return { agentId: src.agentId, path, meta, content: `${r.title}.\\n`, created: true }\n}\n\nconst penaltyPath = (title: string) => `penalties/${slugify(cleanTitle(`${title} penalty`))}.md`\n\n/**\n * The penalty a rule already has: on the page this job wrote for it, else\n * on any penalty page linked to it with `penalty_for`. A confirmed\n * statement is preferred over a proposed one on the same page.\n */\nexport function knownPenalty(hub: WikiHub, g: WikiGraph, title: string, t: Pick<Target, \"agentId\" | \"meta\">): PenaltyFact | undefined {\n const fact = (statements?: WikiStatement[]): PenaltyFact | undefined => {\n const all = (statements ?? []).filter(x => x.property === \"amount_rule\" && x.value)\n const s = all.find(x => x.status === \"confirmed\") ?? all[0]\n return s ? { value: s.value, source: s.source, checked_at: s.checked_at, ...(s.status === \"confirmed\" ? { confirmed: true } : {}) } : undefined\n }\n const own = hub.getAgentWiki(t.agentId).readArticle(penaltyPath(title))\n if (own && (own.meta.tags ?? []).includes(RULES_TAG)) return fact(own.meta.statements)\n for (const e of g.entities.values()) {\n if (e.type !== \"penalty\" || !e.statements.some(s => s.property === \"penalty_for\" && normName(s.value) === normName(title))) continue\n const page = e.pages.find(p => readableAlongside(t.meta, p.article.meta))\n const f = page && fact(page.article.meta.statements)\n if (f) return f\n }\n return undefined\n}\n\nfunction penaltyPage(r: RuleDraft, t: Target, ctx: RulesContext, today: string): { path: string; meta: WikiArticleMeta; content: string } {\n const title = cleanTitle(`${r.title} penalty`)\n const checked = sourceDate(r, ctx)\n const st = (property: string, value: string): WikiStatement => ({\n property, value, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\", by: RULES_BY,\n })\n const statements = [st(\"penalty_for\", r.title), st(\"amount_rule\", r.penalty), st(\"created_by\", r.basis ? asPage(r.basis, ctx.laws) : ctx.page.article.meta.title)]\n return {\n path: penaltyPath(r.title),\n meta: {\n title, class: \"penalty\", tags: [RULES_TAG], owner: t.meta.owner, access: t.meta.access, sharedWith: t.meta.sharedWith,\n created: today, lastUpdated: today, sources: t.meta.sources, statements, related: [r.title],\n },\n content: `## Overview\\n\\n${r.penalty}\\n\\nFor [[${r.title}]]. Source: ${r.source}${checked ? `, dated ${checked}` : \"\"}. Not yet checked with the law or the authority.\\n`,\n }\n}\n\n/** Add `subject_to` to each bearer's page that may show the rule. */\nfunction linkBearers(hub: WikiHub, r: RuleDraft, ctx: RulesContext, t: Target, dryRun: boolean, dropped: string[]): string[] {\n const linked: string[] = []\n for (const b of r.bearers) {\n const e = ctx.parties.find(x => normName(x.title) === normName(b))\n if (!e) continue\n const page = targetPage(hub, e)\n if (!page) { dropped.push(`${r.title} → ${e.title}: page copied from another machine`); continue }\n // The link shows the rule's title on the bearer's page.\n if (!readableAlongside(t.meta, page.article.meta)) { dropped.push(`${r.title} → ${e.title}: page readable by agents who cannot read the rule`); continue }\n const linkedTo = (m: WikiArticleMeta) => (m.statements ?? []).some(s => s.property === \"subject_to\" && normName(s.value) === normName(r.title))\n if (linkedTo(page.article.meta)) continue\n if (dryRun) { linked.push(e.title); continue }\n // Write onto the page as it is now, not the copy read at the start.\n const store = hub.getAgentWiki(page.agentId)\n const now = store.readArticle(page.article.path)\n if (!now) { dropped.push(`${r.title} → ${e.title}: page moved or removed during the run`); continue }\n if (!readableAlongside(t.meta, now.meta)) { dropped.push(`${r.title} → ${e.title}: page readable by agents who cannot read the rule`); continue }\n if (linkedTo(now.meta)) continue\n const checked = sourceDate(r, ctx)\n const statements = [...(now.meta.statements ?? []), { property: \"subject_to\", value: r.title, source: r.source, ...(checked ? { checked_at: checked } : {}), status: \"proposed\" as const, by: RULES_BY }]\n // A link added is not an edit of the page: `lastUpdated` stays.\n const meta = { ...now.meta, statements }\n if (store.writeArticle(page.article.path, meta, now.content, now.meta.owner || page.agentId)) {\n page.article.meta = meta\n linked.push(e.title)\n } else {\n dropped.push(`${r.title} → ${e.title}: write refused`)\n }\n }\n return linked\n}\n\nexport async function runRules(hub: WikiHub, g: WikiGraph, call: EnrichCall, opts: RulesOptions, state: RulesState): Promise<RulesRun> {\n const failures = (e: Entity) => state.sources[e.id]?.failures ?? 0\n const candidates = ruleSources(g, opts.words, opts.only).sort((a, b) => failures(a) - failures(b))\n const readEntries = (ids: string[]) => hub.getSharedStore().readEntries(ids)\n const run: RulesRun = { outcomes: [], costUsd: 0, capped: false }\n const made = new Map<string, Target>()\n let calls = 0\n const remember = (id: string, fp: string, costUsd: number, failed = false) => {\n if (opts.dryRun) return\n const prev = state.sources[id]\n state.sources[id] = failed\n ? { fingerprint: prev?.fingerprint ?? \"\", at: new Date().toISOString(), costUsd, failures: (prev?.failures ?? 0) + 1 }\n : { fingerprint: fp, at: new Date().toISOString(), costUsd }\n opts.save?.(state)\n }\n\n for (const e of candidates) {\n if (calls >= opts.max) break\n const base = { source: e.id, title: e.title, rules: [] as RuleWrite[], costUsd: 0, dropped: [] as string[] }\n const page = targetPage(hub, e)\n if (!page) { if (opts.only.length) run.outcomes.push({ ...base, status: \"no-page\" }); continue }\n const ctx = rulesContext(g, e, page, readEntries)\n let fp = rulesFingerprint(page)\n if (!opts.force && state.sources[e.id]?.fingerprint === fp) {\n if (opts.only.length) run.outcomes.push({ ...base, status: \"unchanged\" })\n continue\n }\n if (run.costUsd >= opts.maxCostUsd) { run.capped = true; break }\n\n calls++\n const where = `${page.agentId}/${page.article.path}`\n let reply: { text: string; costUsd: number }\n try {\n reply = await call(buildRulesPrompt(g, ctx, opts.today))\n } catch (err) {\n run.outcomes.push({ ...base, page: where, status: \"failed\", dropped: [(err as Error).message.slice(0, 200)] })\n remember(e.id, fp, 0, true)\n continue\n }\n run.costUsd += reply.costUsd\n const outcome: RulesOutcome = { ...base, page: where, status: \"no-reply\", costUsd: reply.costUsd }\n const parsed = parseEnrichReply(reply.text)\n if (!parsed) { run.outcomes.push(outcome); remember(e.id, fp, reply.costUsd); continue }\n const checked = checkRules(parsed, ctx, g)\n outcome.dropped = checked.dropped\n if (checked.rules.length === 0) {\n outcome.status = \"no-rules\"\n run.outcomes.push(outcome)\n remember(e.id, fp, reply.costUsd)\n continue\n }\n\n let failed = false\n for (const r of checked.rules) {\n const t = ruleTarget(hub, r, ctx, made, opts.today)\n if (typeof t === \"string\") { outcome.dropped.push(`${r.title}: ${t}`); continue }\n // What an earlier source stated stays when this one leaves it out.\n const statements = mergeRuleStatements(t.meta.statements ?? [], ruleStatements(r, ctx), r)\n const meta0 = withRuleStatements(t.meta, statements, opts.today)\n // A penalty the owner confirmed wins, as on the rule page itself.\n const known = knownPenalty(hub, g, r.title, t)\n const penalty = known?.confirmed || !r.penalty ? known : { value: r.penalty, source: r.source, checked_at: sourceDate(r, ctx) }\n const summary = ruleOverview(meta0.statements ?? [], penalty, page.article.meta.title)\n // A page this job did not create keeps its own Overview.\n const ours = (t.meta.tags ?? []).includes(RULES_TAG)\n const content = ours ? withOverview(t.content, summary) : withRuleSummary(t.content, summary)\n const related = [...new Set([...(t.meta.related ?? []), page.article.meta.title, ...(penalty ? [cleanTitle(`${r.title} penalty`)] : [])])]\n const sources = [...new Set([...(t.meta.sources ?? []), ...ctx.entries.filter(x => r.source.includes(x.id)).map(x => x.id)])]\n const meta = { ...meta0, related, sources }\n const write: RuleWrite = {\n title: r.title, page: `${t.agentId}/${t.path}`, created: t.created,\n deadline: (meta.statements ?? []).some(s => s.property === \"due_rule\"), penalty: !!penalty, linked: [],\n }\n if (opts.dryRun) {\n write.preview = summary\n write.linked = linkBearers(hub, r, ctx, t, true, outcome.dropped)\n outcome.rules.push(write)\n continue\n }\n const store = hub.getAgentWiki(t.agentId)\n if (!store.writeArticle(t.path, meta, content, t.meta.owner || t.agentId)) {\n outcome.dropped.push(`${r.title}: write refused`)\n failed = true\n continue\n }\n made.set(normName(r.title), { ...t, meta, content, created: false })\n if (r.penalty && !known?.confirmed) {\n const pen = penaltyPage(r, { ...t, meta }, ctx, opts.today)\n const old = store.readArticle(pen.path)\n // A penalty page someone else wrote at that path is left alone; on\n // ours, statements the owner confirmed stay.\n if (!old) store.writeArticle(pen.path, pen.meta, pen.content, pen.meta.owner)\n else if ((old.meta.tags ?? []).includes(RULES_TAG)) {\n const merged = withRuleStatements({ ...pen.meta, created: old.meta.created, statements: old.meta.statements }, pen.meta.statements ?? [], opts.today)\n store.writeArticle(pen.path, merged, pen.content, pen.meta.owner)\n } else outcome.dropped.push(`${r.title}: ${pen.path} already exists`)\n }\n write.linked = linkBearers(hub, r, ctx, { ...t, meta }, false, outcome.dropped)\n store.rebuildIndex()\n outcome.rules.push(write)\n }\n outcome.status = opts.dryRun ? \"dry-run\" : outcome.rules.length ? \"written\" : failed ? \"failed\" : \"no-rules\"\n run.outcomes.push(outcome)\n // A rule written onto the source page itself changes its text; the\n // next run must not pay to read back what this one wrote.\n const now = opts.dryRun ? null : hub.getAgentWiki(page.agentId).readArticle(page.article.path)\n if (now) fp = rulesFingerprint({ agentId: page.agentId, article: now })\n remember(e.id, fp, reply.costUsd, failed && outcome.rules.length === 0)\n }\n return run\n}\n"],"mappings":"4TAmBA,OAAS,cAAAA,OAAkB,SAC3B,OAAS,cAAAC,GAAY,aAAAC,GAAW,gBAAAC,GAAc,iBAAAC,OAAqB,KACnE,OAAS,WAAAC,MAAe,OAQjB,IAAMC,EAAW,aAEXC,EAAY,aAGZC,GAAqB,CAChC,WAAY,WAAY,SAAU,SAAU,WAAY,UAAW,QAAS,YAAa,WAAY,eACrG,cAAe,SAAU,aAAc,aAAc,aACrD,iBAAY,cAAe,WAAS,aAAW,SAAU,aAAc,iBAAe,aACtF,iCAAS,qBAAO,2BAAQ,iCAAS,0BACnC,EAGMC,GAAa,IAAI,IAAI,CAAC,QAAS,QAAS,SAAU,SAAU,M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AC,GACtEwB,EAASjI,EAAE,GAAIkI,EAAIK,EAAM,QAASH,GAAUK,EAAQ,MAAM,SAAW,CAAC,EAExE,OAAOV,CACT","names":["createHash","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","RULES_BY","RULES_TAG","DEFAULT_RULE_WORDS","SKIP_TYPES","BEARER_TYPES","PAGE_CHARS","ENTRY_CHARS","clip","s","n","str","v","cleanTitle","ruleWordsPattern","words","escaped","w","statesRules","page","bodyOf","ruleSources","g","only","wanted","normName","ours","e","p","rank","a","b","partiesOf","text","types","hay","linked","x","rulesContext","source","readEntries","entries","all","visible","readableAlongside","of","type","rulesFingerprint","parts","createHash","knownLine","facts","buildRulesPrompt","ctx","today","lines","en","checkRules","raw","dropped","sourceIds","known","rules","seen","item","r","title","action","id","existing","taken","clash","bearers","asPage","value","list","sourceDate","day","d","ruleStatements","checked","st","property","out","SINGLE","mergeRuleStatements","earlier","fresh","prev","stated","o","withRuleStatements","meta","statements","kept","confirmed","key","missing","ruleOverview","penalty","readFrom","one","from","line","label","sources","dates","basis","SUMMARY_HEAD","SUMMARY_END","withRuleSummary","content","summary","section","start","end","loadRulesState","wikiDir","file","resolve","existsSync","readFileSync","saveRulesState","state","mkdirSync","writeFileSync","ruleTarget","hub","made","src","again","targetPage","now","owner","store","path","slugify","penaltyPath","knownPenalty","t","fact","own","f","penaltyPage","linkBearers","dryRun","linkedTo","m","runRules","call","opts","failures","candidates","ids","run","calls","remember","fp","costUsd","failed","base","where","reply","err","outcome","parsed","parseEnrichReply","meta0","withOverview","related","write","pen","old","merged"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b}from"./chunk-IPMXIPTS.js";import"./chunk-RKPAVWXF.js";import"./chunk-GL3H7XMI.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as resolveScheduleCaller,a as runScheduleTool};
|
|
2
|
+
//# sourceMappingURL=schedule-tool-46TVGEYU.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as a,o as b,p as c,q as d,r as e,s as f}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=scheduler-
|
|
1
|
+
import{n as a,o as b,p as c,q as d,r as e,s as f}from"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as AGENT_RUN_TIMEOUT_FLOOR,f as CronScheduler,b as agentRunTimeout,e as cronRunId,d as getNextCronDate,c as runLinkIds};
|
|
2
|
+
//# sourceMappingURL=scheduler-I3QB4GI3.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import"./chunk-QIJLFPWE.js";function S(n){let s=n.trim();return(s.startsWith("[")?JSON.parse(s):s.split(`
|
|
2
|
+
`).filter(r=>r.trim()).map(r=>JSON.parse(r))).map((r,e)=>{let t=r??{},i=typeof t.question=="string"?t.question.trim():"",u=Array.isArray(t.expect)?t.expect.filter(c=>typeof c=="string"&&!!c.trim()):[];if(!i||u.length===0)throw new Error(`question ${e+1} needs a "question" and a non-empty "expect" list`);return{id:typeof t.id=="string"&&t.id?t.id:`q${e+1}`,question:i,expect:u}})}var l=n=>n.toLowerCase().replace(/[\s ]+/g," ").trim(),m=n=>n.replace(/\D+/g,"");function h(n,s){let o=l(n),r=m(n),e=[],t=[];for(let i of s)(i.split("|").some(c=>{let g=m(c);return!!c.trim()&&o.includes(l(c))||g.length>=5&&r.includes(g)})?e:t).push(i);return{found:e,missing:t}}function x(n,s){let o=s.map(({q:e,answer:t,status:i,citations:u,method:c,ms:g,costUsd:d})=>{let{found:a,missing:f}=h(t,e.expect);return{id:e.id,question:e.question,expect:e.expect,found:a,missing:f,score:a.length/e.expect.length,status:i,answer:t,citations:u,...c?{method:c}:{},...g!==void 0?{ms:g}:{},...d!==void 0?{costUsd:d}:{}}}),r=o.length?o.reduce((e,t)=>e+t.score,0)/o.length:0;return{at:n.at??new Date().toISOString(),questions:n.questions,agent:n.agent,shared:n.shared,...n.settings?{settings:n.settings}:{},score:r,full:o.filter(e=>e.missing.length===0).length,results:o}}function p(n){let s=e=>e.length?e.reduce((t,i)=>t+i,0)/e.length:void 0,o=n.results.flatMap(e=>e.ms===void 0?[]:[e.ms]),r=n.results.flatMap(e=>e.costUsd===void 0?[]:[e.costUsd]);return{meanMs:s(o),meanCostUsd:s(r),unpriced:n.results.length-r.length}}function R(n,s){let o=new Map(n.results.map(t=>[t.id,t])),r=s.results.map(t=>{let i=o.get(t.id);return{id:t.id,question:t.question,before:i?.score??0,after:t.score,gained:t.found.filter(u=>!i?.found.includes(u)),lost:(i?.found??[]).filter(u=>!t.found.includes(u)),...i?.ms!==void 0||t.ms!==void 0?{ms:{before:i?.ms,after:t.ms}}:{},...i?.costUsd!==void 0||t.costUsd!==void 0?{costUsd:{before:i?.costUsd,after:t.costUsd}}:{}}}),e=new Set(s.results.map(t=>t.id));return{before:n.score,after:s.score,deltas:r,changed:b(n,s),onlyBefore:n.results.filter(t=>!e.has(t.id)).map(t=>t.id),onlyAfter:s.results.filter(t=>!o.has(t.id)).map(t=>t.id),cost:{before:p(n),after:p(s)}}}function b(n,s){if(!n.settings||!s.settings)return"unknown";let o={...n.settings,agent:n.agent,shared:n.shared},r={...s.settings,agent:s.agent,shared:s.shared};return[...new Set([...Object.keys(o),...Object.keys(r)])].filter(e=>o[e]!==r[e]).map(e=>`${e}: ${String(o[e])} \u2192 ${String(r[e])}`)}export{x as buildReport,R as compareReports,h as matchFacts,S as parseQuestionSet,p as runCost};
|
|
3
|
+
//# sourceMappingURL=score-LNJ46A67.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/score.ts"],"sourcesContent":["// --- Score the wiki against a question set (#824) ---\n//\n// The fleet test behind #824 scored the wiki by hand: each agent took 10\n// to 12 real questions from its own past work and checked whether the\n// wiki answered them (47% and 75%). This makes that repeatable, so the\n// same set can be run before and after a week of daily contributions.\n//\n// A question set is JSON (an array) or JSON lines, one question each:\n//\n// {\"id\": \"q1\", \"question\": \"What is the vendor's billing contact's phone?\", \"expect\": [\"+1 555 0100\"]}\n//\n// An answer scores the share of its expected facts it contains. Matching\n// ignores case and spacing; a fact with five or more digits (a phone,\n// an invoice number) also matches on its digits alone. \"a|b\" accepts\n// either spelling (a date or an amount written two ways). Question sets\n// hold real facts, so they belong outside the repository.\n\nexport interface ScoreQuestion {\n id: string\n question: string\n /** Facts a correct answer contains, copied as they should appear. */\n expect: string[]\n}\n\nexport interface ScoreResult {\n id: string\n question: string\n expect: string[]\n found: string[]\n missing: string[]\n /** found / expected, 0–1. */\n score: number\n status: string\n answer: string\n citations: string[]\n /** How the pages were picked for this question. */\n method?: string\n /** Wall time of the question, in milliseconds. */\n ms?: number\n /** Model spend of the question, in dollars. Unset when it is not known\n * (the catalog method, or a call that reported no cost). */\n costUsd?: number\n}\n\n/** What a run was asked with, so two reports show what changed between them. */\nexport interface ScoreSettings {\n method: string\n linkedPages: number\n linkedChars: number\n live: boolean\n notes: boolean\n /** Models of the summaries method. */\n navigatorModel: string\n answerModel: string\n /** Models of the catalog method. With `method: auto` each question's\n * `method` says which pair answered it. Unset in reports written before\n * they were recorded. */\n catalogSelectorModel?: string\n catalogSynthModel?: string\n}\n\nexport interface ScoreReport {\n at: string\n questions: string\n agent: string\n /** Whether the shared wiki was searched too. */\n shared: boolean\n /** Unset in reports written before #863. */\n settings?: ScoreSettings\n /** Mean of the question scores, 0–1. */\n score: number\n /** Questions every expected fact was found for. */\n full: number\n results: ScoreResult[]\n}\n\nexport function parseQuestionSet(text: string): ScoreQuestion[] {\n const trimmed = text.trim()\n const raw: unknown[] = trimmed.startsWith(\"[\")\n ? JSON.parse(trimmed)\n : trimmed.split(\"\\n\").filter((l) => l.trim()).map((l) => JSON.parse(l))\n return raw.map((x, i) => {\n const r = (x ?? {}) as Record<string, unknown>\n const question = typeof r.question === \"string\" ? r.question.trim() : \"\"\n const expect = Array.isArray(r.expect) ? r.expect.filter((e): e is string => typeof e === \"string\" && !!e.trim()) : []\n if (!question || expect.length === 0) throw new Error(`question ${i + 1} needs a \"question\" and a non-empty \"expect\" list`)\n return { id: typeof r.id === \"string\" && r.id ? r.id : `q${i + 1}`, question, expect }\n })\n}\n\nconst norm = (s: string) => s.toLowerCase().replace(/[\\s ]+/g, \" \").trim()\nconst digits = (s: string) => s.replace(/\\D+/g, \"\")\n\n/** Which expected facts the answer contains. */\nexport function matchFacts(answer: string, expect: string[]): { found: string[]; missing: string[] } {\n const text = norm(answer)\n const textDigits = digits(answer)\n const found: string[] = []\n const missing: string[] = []\n for (const fact of expect) {\n // \"2027-03-31|31/03/2027\": any one spelling counts.\n const hit = fact.split(\"|\").some((alt) => {\n const d = digits(alt)\n return (!!alt.trim() && text.includes(norm(alt))) || (d.length >= 5 && textDigits.includes(d))\n })\n ;(hit ? found : missing).push(fact)\n }\n return { found, missing }\n}\n\nexport function buildReport(\n meta: { questions: string; agent: string; shared: boolean; at?: string; settings?: ScoreSettings },\n answers: Array<{ q: ScoreQuestion; answer: string; status: string; citations: string[]; method?: string; ms?: number; costUsd?: number }>,\n): ScoreReport {\n const results = answers.map(({ q, answer, status, citations, method, ms, costUsd }) => {\n const { found, missing } = matchFacts(answer, q.expect)\n return {\n id: q.id, question: q.question, expect: q.expect, found, missing, score: found.length / q.expect.length, status, answer, citations,\n ...(method ? { method } : {}), ...(ms !== undefined ? { ms } : {}), ...(costUsd !== undefined ? { costUsd } : {}),\n }\n })\n const score = results.length ? results.reduce((s, r) => s + r.score, 0) / results.length : 0\n return {\n at: meta.at ?? new Date().toISOString(),\n questions: meta.questions, agent: meta.agent, shared: meta.shared,\n ...(meta.settings ? { settings: meta.settings } : {}),\n score, full: results.filter((r) => r.missing.length === 0).length, results,\n }\n}\n\nexport interface ScoreDelta {\n id: string\n question: string\n before: number\n after: number\n /** Facts the later run found that the earlier one missed. */\n gained: string[]\n lost: string[]\n /** Wall time and spend of the question in each run, when recorded. */\n ms?: { before?: number; after?: number }\n costUsd?: { before?: number; after?: number }\n}\n\n/** Mean time and spend per question of one report, over the questions\n * that recorded them. Unset when none did. */\nexport interface RunCost {\n meanMs?: number\n meanCostUsd?: number\n /** Questions with no recorded spend: the mean leaves them out. */\n unpriced: number\n}\n\nexport function runCost(report: ScoreReport): RunCost {\n const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : undefined)\n const ms = report.results.flatMap((r) => (r.ms === undefined ? [] : [r.ms]))\n const usd = report.results.flatMap((r) => (r.costUsd === undefined ? [] : [r.costUsd]))\n return { meanMs: mean(ms), meanCostUsd: mean(usd), unpriced: report.results.length - usd.length }\n}\n\nexport interface ReportComparison {\n before: number\n after: number\n deltas: ScoreDelta[]\n /** Settings that differ, as \"key: before → after\". Unknown when either\n * report predates recorded settings. A fair test changes one. */\n changed: string[] | \"unknown\"\n /** Question ids only one of the two reports holds. */\n onlyBefore: string[]\n onlyAfter: string[]\n cost: { before: RunCost; after: RunCost }\n}\n\n/** Per-question change between two reports on the same set. */\nexport function compareReports(before: ScoreReport, after: ScoreReport): ReportComparison {\n const prior = new Map(before.results.map((r) => [r.id, r]))\n const deltas = after.results.map((r) => {\n const b = prior.get(r.id)\n return {\n id: r.id, question: r.question,\n before: b?.score ?? 0, after: r.score,\n gained: r.found.filter((f) => !b?.found.includes(f)),\n lost: (b?.found ?? []).filter((f) => !r.found.includes(f)),\n ...(b?.ms !== undefined || r.ms !== undefined ? { ms: { before: b?.ms, after: r.ms } } : {}),\n ...(b?.costUsd !== undefined || r.costUsd !== undefined ? { costUsd: { before: b?.costUsd, after: r.costUsd } } : {}),\n }\n })\n const afterIds = new Set(after.results.map((r) => r.id))\n return {\n before: before.score, after: after.score, deltas,\n changed: settingsChanged(before, after),\n onlyBefore: before.results.filter((r) => !afterIds.has(r.id)).map((r) => r.id),\n onlyAfter: after.results.filter((r) => !prior.has(r.id)).map((r) => r.id),\n cost: { before: runCost(before), after: runCost(after) },\n }\n}\n\nfunction settingsChanged(before: ScoreReport, after: ScoreReport): string[] | \"unknown\" {\n if (!before.settings || !after.settings) return \"unknown\"\n const a: Record<string, unknown> = { ...before.settings, agent: before.agent, shared: before.shared }\n const b: Record<string, unknown> = { ...after.settings, agent: after.agent, shared: after.shared }\n return [...new Set([...Object.keys(a), ...Object.keys(b)])]\n .filter((k) => a[k] !== b[k])\n .map((k) => `${k}: ${String(a[k])} → ${String(b[k])}`)\n}\n"],"mappings":"4BA4EO,SAASA,EAAiBC,EAA+B,CAC9D,IAAMC,EAAUD,EAAK,KAAK,EAI1B,OAHuBC,EAAQ,WAAW,GAAG,EACzC,KAAK,MAAMA,CAAO,EAClBA,EAAQ,MAAM;AAAA,CAAI,EAAE,OAAQC,GAAMA,EAAE,KAAK,CAAC,EAAE,IAAKA,GAAM,KAAK,MAAMA,CAAC,CAAC,GAC7D,IAAI,CAACC,EAAGC,IAAM,CACvB,IAAMC,EAAKF,GAAK,CAAC,EACXG,EAAW,OAAOD,EAAE,UAAa,SAAWA,EAAE,SAAS,KAAK,EAAI,GAChEE,EAAS,MAAM,QAAQF,EAAE,MAAM,EAAIA,EAAE,OAAO,OAAQG,GAAmB,OAAOA,GAAM,UAAY,CAAC,CAACA,EAAE,KAAK,CAAC,EAAI,CAAC,EACrH,GAAI,CAACF,GAAYC,EAAO,SAAW,EAAG,MAAM,IAAI,MAAM,YAAYH,EAAI,oDAAoD,EAC1H,MAAO,CAAE,GAAI,OAAOC,EAAE,IAAO,UAAYA,EAAE,GAAKA,EAAE,GAAK,IAAID,EAAI,IAAK,SAAAE,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CAAC,CAAC,CAAC,EACvD,OAAQU,GAAMX,EAAEW,CAAC,IAAMV,EAAEU,CAAC,CAAC,EAC3B,IAAKA,GAAM,GAAGA,MAAM,OAAOX,EAAEW,CAAC,CAAC,YAAO,OAAOV,EAAEU,CAAC,CAAC,GAAG,CACzD","names":["parseQuestionSet","text","trimmed","l","x","i","r","question","expect","e","norm","s","digits","matchFacts","answer","textDigits","found","missing","fact","alt","d","buildReport","meta","answers","results","q","status","citations","method","ms","costUsd","score","runCost","report","mean","xs","a","b","usd","compareReports","before","after","prior","deltas","f","afterIds","settingsChanged","k"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i,x as j,y as k,z as l}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=seat-
|
|
1
|
+
import{o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i,x as j,y as k,z as l}from"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";l();export{a as DEFAULT_SEAT_TIMEOUT_MS,k as askSeat,c as configureDecisions,b as configuredSeatTimeout,e as decisionsRuntime,h as getSeatMode,i as labelSeatCall,f as parseSeatMode,j as recordSeatOutcome,d as resetDecisionsRuntime,g as seatEnvVar};
|
|
2
|
+
//# sourceMappingURL=seat-4Y3EW3KU.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as S,z as w}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=select-
|
|
1
|
+
import{y as S,z as w}from"./chunk-66DPMVUC.js";import{a as g,b as h,f as R}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import{e as f}from"./chunk-JHCI6XCJ.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";w();R();var p="skill-select";function y(l){return{task:d(l.task,1200),...l.agent?{agent:l.agent}:{},skills:l.candidates.map(t=>({name:t.name,purpose:d(t.description,300),...t.category?{category:t.category}:{},...t.tags?.length?{tags:t.tags.slice(0,8)}:{}}))}}function b(l){let t={};for(let i of l)t[i.name]=d(i.description,300);return{anyRelevant:g("At least one of these skills is about the task at hand.",{true:"The task is the kind of work one of these skills exists for, and following it would change how the work is done \u2014 it names the same system, the same procedure or the same kind of artefact.",false:"None of them is about this task. They may share vocabulary with it, mention the same tools, or belong to the same project without bearing on what is being asked. Sharing words with a task is not being about it."}),best:h(t,"Which skill is this task most about?")}}function v(l){let t=l.anyRelevant,i=l.best,o=Object.entries(i.probabilities??{}).map(([e,s])=>({name:e,p:Number(s)||0})).sort((e,s)=>s.p-e.p);return{anyRelevant:t.noul,name:i.choice,confidence:i.confidence,ranked:o}}function d(l,t){return l.length>t?`${l.slice(0,t)}\u2026`:l}var x=.1,A=12;async function E(l,t,i={}){let o=i.minRelevant??.6,e=f(l,t).filter(n=>n.relevance>=x).slice(0,A),s=e.map(n=>({name:n.skill.frontmatter.name,lexical:n.relevance}));if(e.length===0)return{skill:null,anyRelevant:0,confidence:0,shortlist:s,judged:!1,reason:"no skill mentions anything in this task"};if(e.length===1)return{skill:e[0].skill,anyRelevant:e[0].relevance,confidence:e[0].relevance,shortlist:s,judged:!1,reason:`only ${e[0].skill.frontmatter.name} matched (${e[0].matchReason})`};let r=e.map(n=>({name:n.skill.frontmatter.name,description:n.skill.frontmatter.description,category:n.skill.frontmatter.category??null,tags:n.skill.frontmatter.tags})),m=await S(p,y({task:t,agent:i.agent??null,candidates:r}),b(r),{incumbent:{best:r[0].name},features:{agent:i.agent??"unknown",candidates:r.length}});if(!m)return{skill:e[0].skill,anyRelevant:e[0].relevance,confidence:e[0].relevance,shortlist:s,judged:!1,reason:`seat off \u2014 lexical top match (${e[0].matchReason})`};let a=v(m.answers),c=s.map(n=>({...n,p:a.ranked.find(k=>k.name===n.name)?.p??0})).sort((n,k)=>(k.p??0)-(n.p??0));if(a.anyRelevant<o)return{skill:null,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`nothing on the shortlist is about this task (${a.anyRelevant.toFixed(2)} below ${o})`};let u=e.find(n=>n.skill.frontmatter.name===a.name);return u?{skill:u.skill,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`${a.name} (confidence ${a.confidence.toFixed(2)})`}:{skill:null,anyRelevant:a.anyRelevant,confidence:a.confidence,shortlist:c,judged:!0,reason:`seat chose "${a.name}", which was not on the shortlist`}}export{E as pickSkillForTask};
|
|
2
|
+
//# sourceMappingURL=select-LZKN3FER.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=set-enabled-
|
|
1
|
+
import{b as a}from"./chunk-WRJFKA43.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";async function i(o,r,s={}){let e=null,n=await a(l=>{let t=l.crons?.[o];if(t?r&&t.approval?.action==="create"?e={ok:!1,status:409,error:`schedule "${o}" is waiting for approval: agentx schedule approve ${o}`}:t.enabled===r&&(e={ok:!0,id:o,enabled:r,changed:!1}):e={ok:!1,status:404,error:`no schedule "${o}"`},e)throw new Error("no write");t.enabled=r,e={ok:!0,id:o,enabled:r,changed:!0}},{configPath:s.configPath,reload:!1});return e&&(!e.ok||!e.changed)?e:n.success?e??{ok:!1,status:500,error:"mutation did not run"}:{ok:!1,status:500,error:n.error||"could not write agentx.json"}}export{i as setCronEnabled};
|
|
2
|
+
//# sourceMappingURL=set-enabled-WSTOHJDE.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-IPMXIPTS.js";import"./chunk-RKPAVWXF.js";import{b as l}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-GL3H7XMI.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var g=t=>typeof t=="string"?t.trim():"",w={in_progress:"in progress",waiting_owner:"waiting on the owner",waiting_other:"waiting on another agent",needs_attention:"needs attention"};function f(t){return t.length?t.map(e=>{let a=new Date(e.createdAt).toISOString().slice(0,16).replace("T"," "),c=e.state==="waiting_owner"&&e.question?` Question: ${e.question}`:e.state==="needs_attention"&&e.attentionReason?` ${e.attentionReason}`:"",n=String(e.text).replace(/\s+/g," ").trim();return`- ${e.id} [${w[e.state]??e.state}] ${a} UTC, ${e.channel}, ${e.agentId}: ${n.length>160?`${n.slice(0,159)}\u2026`:n}.${c}`}).join(`
|
|
2
2
|
`):"No open requests."}function $(t){return(t??[]).map(e=>`${e.idx}. ${e.name} (${e.agentId}, ${e.kind}) [${e.state}]${e.needsApproval?` approval: ${e.approval}`:""}`)}async function y(t,e){let a=e.fetch??fetch,c=e.daemonUrl.replace(/\/$/,""),n=(g(t.action)||"list").toLowerCase();try{if(n==="list"){let u=await a(`${c}/requests`,{signal:AbortSignal.timeout(1e4)}),r=await u.json().catch(()=>({}));return u.ok?r.enabled?`${r.count} open request${r.count===1?"":"s"}, oldest first.
|
|
3
3
|
${f(r.items??[])}`:"Requests are turned off on this node (requests.enabled), so nothing is recorded.":`Error: ${r?.error||`HTTP ${u.status}`}`}let i=e.env??process.env,p=h(t,i);if(!p)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let d=await a(`${c}/requests`,{method:"POST",headers:{"Content-Type":"application/json",...l(i)},body:JSON.stringify({action:n,agentId:p.agentId,id:t.id,question:t.question,evidence:t.evidence,reason:t.reason,steps:t.steps,step:t.step,status:t.status,note:t.note}),signal:AbortSignal.timeout(1e4)}),s=await d.json().catch(()=>({}));if(!d.ok)return`Error: ${s?.error||`HTTP ${d.status}`}`;let o=s.request;return n==="accept"&&s.plan?[`Request ${o.id} is open with a plan of ${s.steps.length} steps. The daemon hands each step to its agent in order, nudges a step that goes quiet, and tells the owner when it is finished or blocked.`,...$(s.steps),`Steps the owner approves get a decision card now; an approved message is sent by the daemon itself. Report your own steps with {action:"step", id:"${o.id}", step:<n>, status:"progress"|"done"|"blocked"}.`].join(`
|
|
4
4
|
`):n==="step"?[`Step reported. Plan of ${o.id}:`,...$(s.steps)].join(`
|
|
5
5
|
`):n==="accept"?`Request ${o.id} is open and in progress. Close it with done (and a link to the evidence) or decline (and the reason); it stays on the owner's list until then.`:n==="wait"?`Request ${o.id} is waiting on the owner with your question. Ask them the question now, once.`:n==="done"?`Request ${o.id} is closed as done. Evidence: ${o.evidence}`:`Request ${o.id} is closed as declined. Reason: ${o.closeReason}`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{f as describeOpen,$ as describeSteps,y as runRequestTool};
|
|
6
|
-
//# sourceMappingURL=tool-
|
|
6
|
+
//# sourceMappingURL=tool-AKXO2EJU.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{b as f}from"./chunk-IPMXIPTS.js";import"./chunk-RKPAVWXF.js";import{f as y}from"./chunk-Y4CYQV7G.js";import{b as u}from"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-GL3H7XMI.js";import"./chunk-AK3XOA5N.js";import"./chunk-WRJFKA43.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var w=new Set(["cron","heartbeat","api","a2a","mesh","approvals","requests"]);function c(t){return typeof t=="string"?t.trim():""}async function b(t,s){let d=s.fetch??fetch,l=s.daemonUrl.replace(/\/$/,""),i=(c(t.action)||"create").toLowerCase(),o=f(t,s.env??process.env);if(i==="status"){let n=c(t.id);if(!n)return"Error: `id` is required for status (the card id you got when you raised it).";try{let a=await d(`${l}/approvals/${encodeURIComponent(n)}`,{signal:AbortSignal.timeout(1e4)}),r=await a.json().catch(()=>({}));if(!a.ok)return`Error: ${r?.error||`HTTP ${a.status}`}`;let e=r.card;if(o&&e.raised_by!==o.agentId)return`Error: card "${n}" was raised by another agent.`;if(e.status==="pending")return`Card ${e.id} is still waiting for the operator. It expires ${e.expires}; then "${e.if_silent}" applies.`;if(e.status==="decided"){let h=e.verdict==="yes"?y(e).join(`
|
|
2
|
+
`):"";return`Card ${e.id}: the operator said ${String(e.verdict).toUpperCase()}.${e.note?` Note: ${e.note}`:""}${h?`
|
|
3
|
+
${h}`:""}`}return e.status==="resolved"?`Card ${e.id} was closed by ${e.raised_by}: ${e.resolution??"answered outside the card"}.`:`Card ${e.id} expired unanswered; the default applied: ${e.outcome??e.if_silent}.`}catch(a){return`Error: couldn't reach the daemon (${a?.message??a}).`}}if(i==="resolve"){let n=c(t.id),a=c(t.reason);if(!n)return"Error: `id` is required for resolve (the card id you got when you raised it).";if(!a)return'Error: `reason` is required for resolve: where the owner answered and what you did, e.g. "approved in chat, done".';if(!o)return"Error: couldn't tell which agent you are. Pass callerAgentId.";try{let r=await d(`${l}/approvals/${encodeURIComponent(n)}/resolve`,{method:"POST",headers:{"Content-Type":"application/json",...u(s.env??process.env)},body:JSON.stringify({raised_by:o.agentId,reason:a}),signal:AbortSignal.timeout(1e4)}),e=await r.json().catch(()=>({}));return r.ok?`Card ${e.card.id} is closed. It left the operator's inbox, so nobody will be asked about it again.`:`Error: ${e?.error||`HTTP ${r.status}`}`}catch(r){return`Error: couldn't reach the daemon (${r?.message??r}).`}}if(i!=="create")return`Error: unknown action "${i}". Use create, status or resolve.`;if(!o)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let p=o.channel&&o.chatId&&!w.has(o.channel)?{channel:o.channel,chatId:o.chatId,...o.accountId?{accountId:o.accountId}:{}}:void 0,$={title:t.title,ask:t.ask,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,source:t.source,choices:t.choices,draft:t.draft,say:t.say,context:t.context,raised_by:o.agentId,...p?{reply:p}:{}};try{let n=await d(`${l}/approvals`,{method:"POST",headers:{"Content-Type":"application/json",...u(s.env??process.env)},body:JSON.stringify($),signal:AbortSignal.timeout(1e4)}),a=await n.json().catch(()=>({}));if(!n.ok)return`Error: ${a?.error||`HTTP ${n.status}`}`;let r=a.card;return[`Decision card ${r.id} is in the operator's Approvals inbox.`,`If nobody answers by ${r.expires}, "${r.if_silent}" applies.`,"You will get a message with the result. Tell the requester it is waiting for approval; don't ask the operator again in chat.",`If the operator answers the same thing in chat and you act on it, close the card with {action:"resolve", id:"${r.id}", reason:"approved in chat, done"} so it is not asked again.`].join(" ")}catch(n){return`Error: couldn't reach the daemon (${n?.message??n}).`}}export{b as runApprovalTool};
|
|
4
|
+
//# sourceMappingURL=tool-NLMIUOHR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/approvals/tool.ts"],"sourcesContent":["import { resolveScheduleCaller } from \"@/crons/schedule-tool\"\nimport { callerHeaders } from \"@/calls/service\"\nimport { answerLines } from \"./choices\"\n\n// --- Agent-facing `agentx_approval` tool ---\n//\n// Lets an agent raise a decision card instead of asking the operator in\n// chat, check what happened to one, and close its own card once the owner\n// answered the same thing in chat and it acted on that (#909). It talks to\n// the daemon's /approvals endpoints, which never decide: there is no\n// action here that approves or rejects anything.\n\nexport type ApprovalToolAction = \"create\" | \"status\" | \"resolve\"\n\nexport interface ApprovalToolDeps {\n daemonUrl: string\n fetch?: typeof fetch\n env?: NodeJS.ProcessEnv\n}\n\nconst NON_CHAT_CHANNELS = new Set([\"cron\", \"heartbeat\", \"api\", \"a2a\", \"mesh\", \"approvals\", \"requests\"])\n\nfunction str(v: unknown): string {\n return typeof v === \"string\" ? v.trim() : \"\"\n}\n\n/** Returns the text the agent sees. Every refusal is text, never a throw. */\nexport async function runApprovalTool(args: Record<string, unknown>, deps: ApprovalToolDeps): Promise<string> {\n const doFetch = deps.fetch ?? fetch\n const base = deps.daemonUrl.replace(/\\/$/, \"\")\n const action = (str(args.action) || \"create\").toLowerCase() as ApprovalToolAction\n const caller = resolveScheduleCaller(args, deps.env ?? process.env)\n\n if (action === \"status\") {\n const id = str(args.id)\n if (!id) return \"Error: `id` is required for status (the card id you got when you raised it).\"\n try {\n const res = await doFetch(`${base}/approvals/${encodeURIComponent(id)}`, { signal: AbortSignal.timeout(10_000) })\n const data = await res.json().catch(() => ({})) as any\n if (!res.ok) return `Error: ${data?.error || `HTTP ${res.status}`}`\n const c = data.card\n if (caller && c.raised_by !== caller.agentId) return `Error: card \"${id}\" was raised by another agent.`\n if (c.status === \"pending\") return `Card ${c.id} is still waiting for the operator. It expires ${c.expires}; then \"${c.if_silent}\" applies.`\n if (c.status === \"decided\") {\n const picked = c.verdict === \"yes\" ? answerLines(c).join(\"\\n\") : \"\"\n return `Card ${c.id}: the operator said ${String(c.verdict).toUpperCase()}.${c.note ? ` Note: ${c.note}` : \"\"}${picked ? `\\n${picked}` : \"\"}`\n }\n if (c.status === \"resolved\") return `Card ${c.id} was closed by ${c.raised_by}: ${c.resolution ?? \"answered outside the card\"}.`\n return `Card ${c.id} expired unanswered; the default applied: ${c.outcome ?? c.if_silent}.`\n } catch (e: any) {\n return `Error: couldn't reach the daemon (${e?.message ?? e}).`\n }\n }\n\n if (action === \"resolve\") {\n const id = str(args.id)\n const reason = str(args.reason)\n if (!id) return \"Error: `id` is required for resolve (the card id you got when you raised it).\"\n if (!reason) return \"Error: `reason` is required for resolve: where the owner answered and what you did, e.g. \\\"approved in chat, done\\\".\"\n if (!caller) return \"Error: couldn't tell which agent you are. Pass callerAgentId.\"\n try {\n const res = await doFetch(`${base}/approvals/${encodeURIComponent(id)}/resolve`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...callerHeaders(deps.env ?? process.env) },\n body: JSON.stringify({ raised_by: caller.agentId, reason }),\n signal: AbortSignal.timeout(10_000),\n })\n const data = await res.json().catch(() => ({})) as any\n if (!res.ok) return `Error: ${data?.error || `HTTP ${res.status}`}`\n return `Card ${data.card.id} is closed. It left the operator's inbox, so nobody will be asked about it again.`\n } catch (e: any) {\n return `Error: couldn't reach the daemon (${e?.message ?? e}).`\n }\n }\n\n if (action !== \"create\") return `Error: unknown action \"${action}\". Use create, status or resolve.`\n if (!caller) return \"Error: couldn't tell which agent you are. Pass callerAgentId.\"\n\n const reply = caller.channel && caller.chatId && !NON_CHAT_CHANNELS.has(caller.channel)\n ? { channel: caller.channel, chatId: caller.chatId, ...(caller.accountId ? { accountId: caller.accountId } : {}) }\n : undefined\n const payload = {\n title: args.title,\n ask: args.ask,\n recommend: args.recommend,\n if_silent: args.if_silent,\n expires: args.expires,\n source: args.source,\n choices: args.choices,\n draft: args.draft,\n say: args.say,\n context: args.context,\n raised_by: caller.agentId,\n ...(reply ? { reply } : {}),\n }\n try {\n const res = await doFetch(`${base}/approvals`, {\n method: \"POST\",\n // The headers name this run: a card moves a request to \"waiting on\n // the owner\" only when it comes from the turn of that request.\n headers: { \"Content-Type\": \"application/json\", ...callerHeaders(deps.env ?? process.env) },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(10_000),\n })\n const data = await res.json().catch(() => ({})) as any\n if (!res.ok) return `Error: ${data?.error || `HTTP ${res.status}`}`\n const c = data.card\n return [\n `Decision card ${c.id} is in the operator's Approvals inbox.`,\n `If nobody answers by ${c.expires}, \"${c.if_silent}\" applies.`,\n \"You will get a message with the result. Tell the requester it is waiting for approval; don't ask the operator again in chat.\",\n `If the operator answers the same thing in chat and you act on it, close the card with {action:\"resolve\", id:\"${c.id}\", reason:\"approved in chat, done\"} so it is not asked again.`,\n ].join(\" \")\n } catch (e: any) {\n return `Error: couldn't reach the daemon (${e?.message ?? e}).`\n }\n}\n"],"mappings":"oeAoBA,IAAMA,EAAoB,IAAI,IAAI,CAAC,OAAQ,YAAa,MAAO,MAAO,OAAQ,YAAa,UAAU,CAAC,EAEtG,SAASC,EAAIC,EAAoB,CAC/B,OAAO,OAAOA,GAAM,SAAWA,EAAE,KAAK,EAAI,EAC5C,CAGA,eAAsBC,EAAgBC,EAA+BC,EAAyC,CAC5G,IAAMC,EAAUD,EAAK,OAAS,MACxBE,EAAOF,EAAK,UAAU,QAAQ,MAAO,EAAE,EACvCG,GAAUP,EAAIG,EAAK,MAAM,GAAK,UAAU,YAAY,EACpDK,EAASC,EAAsBN,EAAMC,EAAK,KAAO,QAAQ,GAAG,EAElE,GAAIG,IAAW,SAAU,CACvB,IAAMG,EAAKV,EAAIG,EAAK,EAAE,EACtB,GAAI,CAACO,EAAI,MAAO,+EAChB,GAAI,CACF,IAAMC,EAAM,MAAMN,EAAQ,GAAGC,eAAkB,mBAAmBI,CAAE,IAAK,CAAE,OAAQ,YAAY,QAAQ,GAAM,CAAE,CAAC,EAC1GE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,MAAO,UAAUC,GAAM,OAAS,QAAQD,EAAI,WACzD,IAAME,EAAID,EAAK,KACf,GAAIJ,GAAUK,EAAE,YAAcL,EAAO,QAAS,MAAO,gBAAgBE,kCACrE,GAAIG,EAAE,SAAW,UAAW,MAAO,QAAQA,EAAE,oDAAoDA,EAAE,kBAAkBA,EAAE,sBACvH,GAAIA,EAAE,SAAW,UAAW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kB,IAAIS,EAAO,OAAO,EAClF,CAAE,QAASA,EAAO,QAAS,OAAQA,EAAO,OAAQ,GAAIA,EAAO,UAAY,CAAE,UAAWA,EAAO,SAAU,EAAI,CAAC,CAAG,EAC/G,OACEY,EAAU,CACd,MAAOjB,EAAK,MACZ,IAAKA,EAAK,IACV,UAAWA,EAAK,UAChB,UAAWA,EAAK,UAChB,QAASA,EAAK,QACd,OAAQA,EAAK,OACb,QAASA,EAAK,QACd,MAAOA,EAAK,MACZ,IAAKA,EAAK,IACV,QAASA,EAAK,QACd,UAAWK,EAAO,QAClB,GAAIW,EAAQ,CAAE,MAAAA,CAAM,EAAI,CAAC,CAC3B,EACA,GAAI,CACF,IAAMR,EAAM,MAAMN,EAAQ,GAAGC,cAAkB,CAC7C,OAAQ,OAGR,QAAS,CAAE,eAAgB,mBAAoB,GAAGY,EAAcd,EAAK,KAAO,QAAQ,GAAG,CAAE,EACzF,KAAM,KAAK,UAAUgB,CAAO,EAC5B,OAAQ,YAAY,QAAQ,GAAM,CACpC,CAAC,EACKR,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,MAAO,UAAUC,GAAM,OAAS,QAAQD,EAAI,WACzD,IAAME,EAAID,EAAK,KACf,MAAO,CACL,iBAAiBC,EAAE,2CACnB,wBAAwBA,EAAE,aAAaA,EAAE,sBACzC,+HACA,gHAAgHA,EAAE,iEACpH,EAAE,KAAK,GAAG,CACZ,OAASG,EAAP,CACA,MAAO,qCAAqCA,GAAG,SAAWA,KAC5D,CACF","names":["NON_CHAT_CHANNELS","str","v","runApprovalTool","args","deps","doFetch","base","action","caller","resolveScheduleCaller","id","res","data","c","picked","answerLines","e","reason","callerHeaders","reply","payload"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import"./chunk-VWTBHLMX.js";import{a as b}from"./chunk-C43E3YFT.js";import{a}from"./chunk-OISCRNMW.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import{d as c}from"./chunk-PV623BLN.js";import"./chunk-SKSYII3K.js";import"./chunk-OW5EXDVY.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{b as WikiHub,a as WikiStore,c as agenticQuery};
|
|
2
|
+
//# sourceMappingURL=wiki-ZS6OHOWQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.136.0",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|