agentix-cli 0.135.1 → 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-YT5TOTC7.js → absorb-eval-COPVH2M2.js} +2 -2
- package/dist/{agent-DRUIMWF5.js → agent-VCGAUBER.js} +2 -2
- package/dist/{board-dashboard-2524GN5N.js → board-dashboard-JZM3FQNV.js} +4 -4
- package/dist/{board-dashboard-2524GN5N.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-TTG3ZW3W.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-SN7YH4E4.js → chunk-C43E3YFT.js} +2 -2
- package/dist/{chunk-ZEAT2B5B.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-R6ECKZLE.js → chunk-H2N7DOPT.js} +2 -2
- package/dist/{chunk-XOUO4XNA.js → chunk-HEJTE7OC.js} +2 -2
- package/dist/{chunk-3F4GPRGQ.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-R6KLH34H.js → chunk-K75LFQE3.js} +2 -2
- package/dist/{chunk-UTW56K5I.js → chunk-KZXQD6ZK.js} +2 -2
- package/dist/{chunk-P3I7AATX.js → chunk-M5AHI2PZ.js} +2 -2
- package/dist/{chunk-3D5XUOBL.js → chunk-M5B4QG6J.js} +2 -2
- 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-32LIPTHM.js → chunk-PV623BLN.js} +3 -3
- package/dist/{chunk-WYEWNN76.js → chunk-QCUJTAAZ.js} +6 -6
- package/dist/{chunk-NG72DYJR.js → chunk-QTDKNJXD.js} +210 -210
- package/dist/chunk-QTDKNJXD.js.map +1 -0
- 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-UXOGNBGL.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-ZD6ZGTJR.js → contributions-H6T65TCY.js} +2 -2
- package/dist/{contributions-ZD6ZGTJR.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/{program-WOQXOAYQ.js → program-WROQ55F5.js} +240 -238
- package/dist/program-WROQ55F5.js.map +1 -0
- package/dist/promote-HDLU44MX.js +2 -0
- package/dist/{query-RRHYPXOM.js → query-6G27CBZQ.js} +2 -2
- package/dist/query-runs-VXS572PQ.js +6 -0
- package/dist/query-runs-VXS572PQ.js.map +1 -0
- package/dist/{query-settings-WKVLQEVZ.js → query-settings-G4M75LVQ.js} +2 -2
- 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/{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/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-KA2UIZXG.js +0 -3
- package/dist/chunk-KA2UIZXG.js.map +0 -1
- package/dist/chunk-KXR6GVL7.js +0 -5
- package/dist/chunk-MUVE3UAS.js +0 -105
- package/dist/chunk-MUVE3UAS.js.map +0 -1
- package/dist/chunk-NG72DYJR.js.map +0 -1
- package/dist/config-mutator-6ITNU5DT.js +0 -2
- package/dist/enrich-EFIPWA3P.js +0 -16
- package/dist/enrich-EFIPWA3P.js.map +0 -1
- package/dist/event-levels-7CY7AJLY.js +0 -3
- package/dist/event-levels-7CY7AJLY.js.map +0 -1
- package/dist/fact-proposals-LZWS5KFO.js +0 -2
- package/dist/hub-MVX3U6A2.js +0 -2
- package/dist/ledger-CH7R756S.js +0 -2
- package/dist/program-WOQXOAYQ.js.map +0 -1
- package/dist/promote-X2XQEEQP.js +0 -2
- package/dist/query-runs-WYRNBLLC.js +0 -6
- package/dist/query-runs-WYRNBLLC.js.map +0 -1
- package/dist/registry-VXK36CCL.js +0 -2
- package/dist/rotation-memo-store-A4YW6FSK.js +0 -2
- package/dist/schedule-tool-KPVTMYL3.js +0 -2
- package/dist/tool-XLWLXGB5.js +0 -4
- package/dist/tool-XLWLXGB5.js.map +0 -1
- package/dist/wiki-QZ7XNAMJ.js +0 -2
- package/dist/wiki-enrich-PMG4T6PP.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-YT5TOTC7.js.map → absorb-eval-COPVH2M2.js.map} +0 -0
- /package/dist/{agent-DRUIMWF5.js.map → agent-VCGAUBER.js.map} +0 -0
- /package/dist/{chunk-TTG3ZW3W.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-SN7YH4E4.js.map → chunk-C43E3YFT.js.map} +0 -0
- /package/dist/{chunk-ZEAT2B5B.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-R6ECKZLE.js.map → chunk-H2N7DOPT.js.map} +0 -0
- /package/dist/{chunk-XOUO4XNA.js.map → chunk-HEJTE7OC.js.map} +0 -0
- /package/dist/{chunk-3F4GPRGQ.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-R6KLH34H.js.map → chunk-K75LFQE3.js.map} +0 -0
- /package/dist/{chunk-UTW56K5I.js.map → chunk-KZXQD6ZK.js.map} +0 -0
- /package/dist/{chunk-P3I7AATX.js.map → chunk-M5AHI2PZ.js.map} +0 -0
- /package/dist/{chunk-3D5XUOBL.js.map → chunk-M5B4QG6J.js.map} +0 -0
- /package/dist/{chunk-ERULJ2ZL.js.map → chunk-OW5EXDVY.js.map} +0 -0
- /package/dist/{chunk-32LIPTHM.js.map → chunk-PV623BLN.js.map} +0 -0
- /package/dist/{chunk-WYEWNN76.js.map → chunk-QCUJTAAZ.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-UXOGNBGL.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-MVX3U6A2.js.map → grants-CEUGZBQ4.js.map} +0 -0
- /package/dist/{ledger-CH7R756S.js.map → hub-IIW2GBO5.js.map} +0 -0
- /package/dist/{promote-X2XQEEQP.js.map → ledger-P62U3FHT.js.map} +0 -0
- /package/dist/{query-RRHYPXOM.js.map → promote-HDLU44MX.js.map} +0 -0
- /package/dist/{registry-VXK36CCL.js.map → query-6G27CBZQ.js.map} +0 -0
- /package/dist/{query-settings-WKVLQEVZ.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/{wiki-QZ7XNAMJ.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-enrich-PMG4T6PP.js.map → wiki-ZS6OHOWQ.js.map} +0 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{a as _,k as O,l as M,m as D}from"./chunk-H4NSB54D.js";import{f as N,g as Y}from"./chunk-MTX4UPNB.js";import{f as v}from"./chunk-QAWKN2N4.js";import{c as G}from"./chunk-OWNQ2FD4.js";import{b as C}from"./chunk-KEXBEUSU.js";import{createHash as J}from"crypto";import{existsSync as B,mkdirSync as V,readFileSync as q,writeFileSync as K}from"fs";import{resolve as P}from"path";var H="wiki-enrich",$e=["person","organization","project","place","device","server","app","domain","account"],Q=new Set(["person","organization","project","place"]),F=3500,X=700;function Z(e,n){let s=e.ontology.types.find(r=>r.id===n)?.lens??[],t=new Map;for(let r of s)if(Y(r)==="statements")for(let i of N(r)){if(i==="related"||t.has(i))continue;let l=e.ontology.properties.find(u=>u.id===i);l?.domain&&!l.domain.includes(n)||t.set(i,l?.label??i.replace(/_/g," "))}return t}function T(e,n,s){let t=v(n.title);return t.length<4?[]:[...e.entities.values()].filter(r=>r.type===s&&r.id!==n.id&&` ${v(r.title)} `.includes(` ${t} `))}function L(e){return e.access==="public"?null:new Set([e.owner,...e.access==="shared"?e.sharedWith??[]:[]])}function ee(e,n){let s=L(e);if(!s)return!0;let t=L(n);return!!t&&[...t].every(r=>s.has(r))}function te(e,n,s,t){let r=a=>!t||ee(a.article.meta,t.article.meta),i=a=>a.pages.some(r),l=n.pages.filter(r),u=t?[...new Set(l.flatMap(a=>a.article.meta.sources??[]))]:n.sources,p=_(e,n,null).filter(i),f=a=>[...new Map(a.map(g=>[g.id,g])).values()],E=f([...p.filter(a=>a.type==="event"),...T(e,n,"event").filter(i)]).sort((a,g)=>(g.date||"").localeCompare(a.date||"")).slice(0,30),o=f([...p.filter(a=>a.type==="project"),...T(e,n,"project").filter(i)]).slice(0,12),d=p.filter(a=>a.type!=="event"&&a.type!=="project").filter(i).filter(a=>n.type!=="person"||Q.has(a.type)).slice(0,40),w=s(u).sort((a,g)=>g.date.localeCompare(a.date)).slice(0,14),c=Z(e,n.type),m=new Map;for(let a of c.keys()){let g=e.ontology.properties.find(h=>h.id===a)?.range;g?.length&&m.set(a,g)}return{entity:n,pages:l,properties:c,ranges:m,neighbours:d,events:E,projects:o,entries:w,sources:u,mentions:ne(e,n,12,r)}}function ne(e,n,s=12,t=()=>!0){let r=[n.title,...n.pages.flatMap(p=>p.article.meta.aliases??[])].filter(p=>p.trim().length>=3);if(r.length===0)return[];let i=r.map(p=>p.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),l=new RegExp(`(^|[^\\p{L}\\p{N}])(${i.join("|")})(?=$|[^\\p{L}\\p{N}])`,"iu"),u=[];for(let p of e.entities.values())if(!(p.id===n.id||p.type==="event"))for(let f of p.pages){if(!t(f))continue;let E=O(f.article.content),o=l.exec(E);if(!o)continue;let d=Math.max(0,o.index-250);u.push({page:f,excerpt:E.slice(d,o.index+450).replace(/\s+/g," ").trim(),at:f.article.meta.lastUpdated||""});break}return u.sort((p,f)=>f.at.localeCompare(p.at)).slice(0,s).map(({page:p,excerpt:f})=>({page:p,excerpt:f}))}function ie(e){let n=[...e.pages.map(s=>`${s.agentId}/${s.article.path}`),...e.sources,...e.events.map(s=>s.id),...e.projects.map(s=>s.id),...e.mentions.map(s=>`${s.page.agentId}/${s.page.article.path}`)].sort();return J("sha1").update(n.join(`
|
|
2
|
+
`)).digest("hex").slice(0,16)}var x=(e,n)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function se(e,n,s){let t=e.entity,r=[`You are bringing one wiki page up to date. Today is ${s}.`,`Subject: "${t.title}" (${n}).`,"","## What the agents' pages say"];for(let i of e.pages)r.push(`### page ${i.agentId}/${i.article.path} (updated ${i.article.meta.lastUpdated||"?"})`,x(O(i.article.content),F),"");if(e.mentions.length){r.push("## Other pages that name the subject");for(let i of e.mentions)r.push(`### page ${i.page.agentId}/${i.page.article.path}: "${i.page.article.meta.title}"`,i.excerpt,"")}r.push("## Source entries (newest first)");for(let i of e.entries)r.push(`### entry ${i.id} (${i.date}, ${i.agentId}, ${i.source})`,x(i.content.trim(),X),"");return r.push("## Event pages",...e.events.map(i=>`- ${i.date||"?"} \xB7 ${i.title}`),""),r.push("## Project pages",...e.projects.map(i=>`- ${i.title}`),""),r.push("## Other pages it may name",...e.neighbours.map(i=>`- ${i.title} (${i.type})`),""),r.push(`## Properties you may use (the subject is always ${t.title})`,...[...e.properties].map(([i,l])=>`- ${i}: "${t.title} ${l} <value>"${e.ranges.get(i)?`, value is a ${e.ranges.get(i).join(" or ")}`:""}`),""),r.push("## Task","Return one JSON object and nothing else:",'{"overview": "\u2026", "statements": [{"property": "\u2026", "value": "\u2026", "role": "\u2026", "since": "YYYY-MM-DD", "until": "YYYY-MM-DD", "source": "\u2026"}], "history": ["event page title"], "projects": ["project page title"]}',"","Rules:",`- overview: 3 to 6 full sentences telling the story of the relationship: who ${t.title} is to us, how it started, what changed, and where it stands now, with dates. Plain prose. Link pages as [[Exact Title]] only when the title is listed above. Never stop mid-sentence.`,"- statements: only facts the pages or entries state. Use only the listed properties. value is a listed page title when it names one, else a short literal. role, since and until only when stated.","- source: the entry id, the page (agent/path) or the event title the fact comes from. A statement without one of these is dropped.","- Do not list an AI agent or bot as a person's relation.","- history: titles of the listed event pages that are about the subject. projects: listed project titles it takes part in.","- Leave out anything you could not verify. Do not write 'unknown' or 'not captured' as a fact.","- Write in the language the pages are written in."),r.join(`
|
|
3
|
+
`)}function re(e){let n=e.match(/```(?:json)?\s*\n([\s\S]*?)\n```/),s=n?n[1]:e.slice(e.indexOf("{"),e.lastIndexOf("}")+1);try{let t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}var z=/^\d{4}-\d{2}(-\d{2})?$/,b=e=>typeof e=="string"?e.trim():"";function oe(e,n,s){let t=[],r=n.entity,i=b(e.overview);if(i&&!/[.!?؟)»"']$/.test(i)){let o=Math.max(i.lastIndexOf(". "),i.lastIndexOf("? "),i.lastIndexOf("! "));i=o>0?i.slice(0,o+1):"",t.push("overview: unfinished last sentence removed")}let l=[...n.entries.map(o=>o.id),...n.pages.map(o=>`${o.agentId}/${o.article.path}`),...n.pages.map(o=>o.article.path),...n.mentions.map(o=>`${o.page.agentId}/${o.page.article.path}`),...n.mentions.map(o=>o.page.article.path),...n.events.map(o=>o.title)],u=[],p=new Set;for(let o of Array.isArray(e.statements)?e.statements:[]){let d=o??{},w=b(d.property),c=b(d.value),m=b(d.source),a=`${w} ${c}`;if(!n.properties.has(w)){t.push(`${a}: property not allowed`);continue}if(!c||/^(unknown|not (given|known|captured|recorded))\b/i.test(c)){t.push(`${a}: no value`);continue}if(!m||!l.some(k=>m.includes(k))){t.push(`${a}: source not among those given`);continue}let g=s.names.get(v(c)),h=g?s.entities.get(g):void 0;if(h?.id===r.id){t.push(`${a}: points at itself`);continue}if(r.type==="person"&&h?.type==="agent"){t.push(`${a}: an agent is not a person's relation`);continue}let j=n.ranges.get(w);if(j&&h&&!j.includes(h.type)){t.push(`${a}: value is a ${h.type}, expected ${j.join(" or ")}`);continue}let A=`${w}
|
|
4
|
+
${v(c)}`;if(p.has(A))continue;p.add(A);let $={property:w,value:h?.title??c,source:x(m,200)},W=b(d.role);W&&($.role=x(W,80)),z.test(b(d.since))&&($.since=b(d.since)),z.test(b(d.until))&&($.until=b(d.until)),u.push($)}let f=new Map([...n.events,...n.projects].map(o=>[v(o.title),o.title])),E=[];for(let o of[...Array.isArray(e.history)?e.history:[],...Array.isArray(e.projects)?e.projects:[]]){let d=f.get(v(b(o).replace(/^\d{4}-\d{2}-\d{2}\s*·\s*/,"")));d&&!E.includes(d)?E.push(d):!d&&b(o)&&t.push(`link ${b(o)}: no such page`)}return{overview:i,statements:u,links:E,dropped:t}}function ae(e,n){let s=`## Overview
|
|
5
|
+
|
|
6
|
+
${n.trim()}
|
|
7
|
+
|
|
8
|
+
${M}
|
|
9
|
+
`,t=D(e);if(t){let r=e.slice(t.end,t.after)===M,i=/^#{1,2}[ \t]/m.test(e.slice(t.end,t.end+4)),u=(r||i&&O(e).length<=F?e.slice(t.after):e.slice(t.textStart)).trim();return`${e.slice(0,t.start)}${s}${u?`
|
|
10
|
+
${u}
|
|
11
|
+
`:""}`}return`${s}
|
|
12
|
+
${e.trim()}
|
|
13
|
+
`}function ce(e,n,s){let t=p=>`${p.property}
|
|
14
|
+
${v(p.value)}`,r=(e.statements??[]).filter(p=>p.by!==H),i=new Set(r.map(t)),l=[...r,...n.statements.filter(p=>!i.has(t(p))).map(p=>({...p,checked_at:s,by:H}))],u=[...new Set([...e.related??[],...n.links])];return{...e,statements:l.length?l:void 0,related:u.length?u:void 0,lastUpdated:s}}function pe(e,n){return n.pages.filter(s=>!e.syncedFrom(s.agentId)).sort((s,t)=>(t.article.meta.sources?.length??0)-(s.article.meta.sources?.length??0)||t.article.content.length-s.article.content.length)[0]}var le={person:"people",organization:"organizations",project:"projects",place:"places"};function Ee(e,n,s,t,r){let i=n.replace(/\s+/g," ").trim(),l=e.getAgentWiki(t);if(l.listAllArticles().some(E=>v(E.meta.title)===v(i)))return null;let u=`${le[s]??`${s}s`}/${v(i).replace(/ /g,"-").slice(0,80)||"page"}.md`,p=C(s)?s:void 0,f={title:i,type:p,class:s,tags:[],owner:t,access:"shared",created:r,lastUpdated:r,sources:[]};return l.writeArticle(u,f,`${i}.
|
|
15
|
+
`,t)?u:null}function ke(e){let n=P(e,"_enrich","state.json");if(!B(n))return{entities:{}};try{let s=JSON.parse(q(n,"utf-8"));return s&&typeof s.entities=="object"?s:{entities:{}}}catch{return{entities:{}}}}function be(e,n){V(P(e,"_enrich"),{recursive:!0}),K(P(e,"_enrich","state.json"),JSON.stringify(n,null,2))}async function Se(e,n,s,t,r){let i=new Set(t.types),l=new Set(t.only.map(v)),u=c=>c.sources.length+c.pages.length,p=c=>r.entities[c.id]?.failures??0,f=[...n.entities.values()].filter(c=>i.has(c.type)).filter(c=>l.size===0||l.has(v(c.id))||l.has(v(c.title))).sort((c,m)=>p(c)-p(m)||u(m)-u(c)),E=c=>e.getSharedStore().readEntries(c),o={outcomes:[],costUsd:0,capped:!1},d=0,w=(c,m,a,g=!1)=>{if(t.dryRun)return;let h=r.entities[c];r.entities[c]=g?{fingerprint:h?.fingerprint??"",at:new Date().toISOString(),costUsd:a,failures:(h?.failures??0)+1}:{fingerprint:m,at:new Date().toISOString(),costUsd:a},t.save?.(r)};for(let c of f){if(d>=t.max)break;let m={entity:c.id,title:c.title,statements:0,links:0,overview:!1,costUsd:0,dropped:[]},a=pe(e,c);if(!a){o.outcomes.push({...m,status:"no-page"});continue}let g=te(n,c,E,a),h=ie(g);if(!t.force&&r.entities[c.id]?.fingerprint===h){l.size&&o.outcomes.push({...m,status:"unchanged"});continue}if(o.costUsd>=t.maxCostUsd){o.capped=!0;break}d++;let j=n.ontology.types.find(y=>y.id===c.type)?.label??c.type,A=`${a.agentId}/${a.article.path}`,$;try{$=await s(se(g,j,t.today))}catch(y){o.outcomes.push({...m,page:A,status:"failed",dropped:[y.message.slice(0,200)]}),w(c.id,h,0,!0);continue}o.costUsd+=$.costUsd;let W=re($.text),k={...m,page:A,status:"no-reply",costUsd:$.costUsd};if(!W){o.outcomes.push(k),w(c.id,h,$.costUsd);continue}let S=oe(W,g,n);if(Object.assign(k,{statements:S.statements.length,links:S.links.length,overview:!!S.overview,dropped:S.dropped}),!S.overview&&S.statements.length===0&&S.links.length===0){k.status="nothing-new",o.outcomes.push(k),w(c.id,h,$.costUsd);continue}let U=y=>S.overview?ae(y.content,S.overview):y.content;if(t.dryRun){o.outcomes.push({...k,status:"dry-run",preview:U(a.article),facts:S.statements});continue}let R=e.getAgentWiki(a.agentId),I;try{I=R.withArticleLock(a.article.path,()=>{let y=R.readArticle(a.article.path);return y?R.writeArticle(a.article.path,ce(y.meta,S,t.today),U(y),y.meta.owner||a.agentId)?void 0:"write refused":"the page was moved or removed during the run"})}catch(y){if(!(y instanceof G))throw y;I="the page was busy; run again"}if(I){k.status="failed",k.dropped.push(I),o.outcomes.push(k),w(c.id,h,$.costUsd,!0);continue}R.rebuildIndex(),w(c.id,h,$.costUsd),k.status="written",o.outcomes.push(k)}return o}export{H as a,$e as b,Z as c,ee as d,te as e,ne as f,ie as g,se as h,re as i,oe as j,ae as k,ce as l,pe as m,Ee as n,ke as o,be as p,Se as q};
|
|
16
|
+
//# sourceMappingURL=chunk-U6EJ53DA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/enrich.ts"],"sourcesContent":["// --- Bring entity pages up to a full overview, typed facts and history (#820) ---\n//\n// For each person, organisation, project, place or asset in the typed\n// graph, one model call reads every agent's page about it, the event and\n// project pages linked to it, and the raw entries the pages came from.\n// It returns:\n// - an overview: who they are to us, how it started, what changed, where\n// it stands now;\n// - typed statements (role at, client of, owns…), each with a source;\n// - the event and project pages its History should link to.\n// Everything is checked against what the call was shown before one page\n// is written through the store, which keeps the old version. Only\n// entities whose sources or links changed since the last run are redone,\n// and a run stops before the next call once its spending cap is reached.\n\nimport { createHash } from \"crypto\"\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { LockBusyError } from \"./facts/ledger-file\"\nimport type { WikiHub } from \"./hub\"\nimport { isWikiArticleType, type WikiArticleMeta, type WikiEntry } from \"./types\"\nimport { normName, type Entity, type GraphPage, type WikiGraph } from \"./ontology/graph\"\nimport { linkedEntities } from \"./ontology/lens\"\nimport { panelFrom, panelSource } from \"./ontology/load\"\nimport type { WikiStatement } from \"./ontology/types\"\nimport { bodyOf, OVERVIEW_END, overviewSpan } from \"./ontology/view-entity\"\n\nexport const ENRICH_BY = \"wiki-enrich\"\n\nexport const ENRICH_TYPES =[\"person\", \"organization\", \"project\", \"place\", \"device\", \"server\", \"app\", \"domain\", \"account\"]\n\n/** Types a person's relation may point at; never an agent (#819). */\nconst PERSON_RELATION_TYPES = new Set([\"person\", \"organization\", \"project\", \"place\"])\n\nexport interface EnrichContext {\n entity: Entity\n pages: GraphPage[]\n /** Property id → label, the typed relations this type's lens shows. */\n properties: Map<string, string>\n /** Property id → the types its value may be, where the ontology says. */\n ranges: Map<string, string[]>\n /** Other entities the page may name, by title. */\n neighbours: Entity[]\n events: Entity[]\n projects: Entity[]\n entries: WikiEntry[]\n /** Raw entry ids behind the pages the call may read. */\n sources: string[]\n /** Other pages that name the subject in their text, with the passage. */\n mentions: Array<{ page: GraphPage; excerpt: string }>\n}\n\nexport interface EnrichResult {\n overview: string\n statements: WikiStatement[]\n /** Titles of event and project pages to link. */\n links: string[]\n /** What the checks removed, for the run log. */\n dropped: string[]\n}\n\nexport interface EnrichState {\n entities: Record<string, {\n fingerprint: string\n at: string\n costUsd?: number\n /** Calls that failed in a row; such entities go after the rest. */\n failures?: number\n }>\n}\n\nconst PAGE_CHARS = 3500\nconst ENTRY_CHARS = 700\n\n/** Typed properties the entity's lens shows, without plain links. */\nexport function lensProperties(g: WikiGraph, type: string): Map<string, string> {\n const lens = g.ontology.types.find(t => t.id === type)?.lens ?? []\n const out = new Map<string, string>()\n for (const panel of lens) {\n if (panelSource(panel) !== \"statements\") continue\n for (const id of panelFrom(panel)) {\n if (id === \"related\" || out.has(id)) continue\n const def = g.ontology.properties.find(p => p.id === id)\n // An organisation's \"people\" panel reads role_at from person pages.\n if (def?.domain && !def.domain.includes(type)) continue\n out.set(id, def?.label ?? id.replace(/_/g, \" \"))\n }\n }\n return out\n}\n\n/** Events whose title names the entity, for pages that never linked them. */\nfunction namedIn(g: WikiGraph, e: Entity, type: string): Entity[] {\n const name = normName(e.title)\n if (name.length < 4) return []\n return [...g.entities.values()].filter(x => x.type === type && x.id !== e.id && ` ${normName(x.title)} `.includes(` ${name} `))\n}\n\n/** Agents who can read a page; null means everyone. */\nfunction readers(m: WikiArticleMeta): Set<string> | null {\n if (m.access === \"public\") return null\n return new Set([m.owner, ...(m.access === \"shared\" ? m.sharedWith ?? [] : [])])\n}\n\n/** True when everyone who can read `target` can also read `source`, so\n * text from `source` may be written into `target` (#820). */\nexport function readableAlongside(source: WikiArticleMeta, target: WikiArticleMeta): boolean {\n const s = readers(source)\n if (!s) return true\n const t = readers(target)\n return !!t && [...t].every(a => s.has(a))\n}\n\n/**\n * What one call for `e` may read. With a target page, only pages its\n * readers can already read are included: an owner-only page is never\n * summarised into a shared or public one.\n */\nexport function enrichContext(g: WikiGraph, e: Entity, readEntries: (ids: string[]) => WikiEntry[], target?: GraphPage): EnrichContext {\n const readable = (p: GraphPage) => !target || readableAlongside(p.article.meta, target.article.meta)\n const visible = (x: Entity) => x.pages.some(readable)\n const pages = e.pages.filter(readable)\n const sources = target ? [...new Set(pages.flatMap(p => p.article.meta.sources ?? []))] : e.sources\n const linked = linkedEntities(g, e, null).filter(visible)\n const byId = (list: Entity[]) => [...new Map(list.map(x => [x.id, x])).values()]\n const events = byId([...linked.filter(x => x.type === \"event\"), ...namedIn(g, e, \"event\").filter(visible)])\n .sort((a, b) => (b.date || \"\").localeCompare(a.date || \"\")).slice(0, 30)\n const projects = byId([...linked.filter(x => x.type === \"project\"), ...namedIn(g, e, \"project\").filter(visible)]).slice(0, 12)\n const neighbours = linked\n .filter(x => x.type !== \"event\" && x.type !== \"project\")\n .filter(visible)\n .filter(x => e.type !== \"person\" || PERSON_RELATION_TYPES.has(x.type))\n .slice(0, 40)\n const entries = readEntries(sources).sort((a, b) => b.date.localeCompare(a.date)).slice(0, 14)\n const properties = lensProperties(g, e.type)\n const ranges = new Map<string, string[]>()\n for (const id of properties.keys()) {\n const range = g.ontology.properties.find(p => p.id === id)?.range\n if (range?.length) ranges.set(id, range)\n }\n return { entity: e, pages, properties, ranges, neighbours, events, projects, entries, sources, mentions: mentionsOf(g, e, 12, readable) }\n}\n\n/** Non-event pages whose text names the subject: what a new or thin page\n * can be written from. The newest first, a passage around the first hit. */\nexport function mentionsOf(g: WikiGraph, e: Entity, max = 12, readable: (p: GraphPage) => boolean = () => true): Array<{ page: GraphPage; excerpt: string }> {\n const names = [e.title, ...e.pages.flatMap(p => p.article.meta.aliases ?? [])].filter(n => n.trim().length >= 3)\n if (names.length === 0) return []\n const escaped = names.map(n => n.trim().replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n const re = new RegExp(`(^|[^\\\\p{L}\\\\p{N}])(${escaped.join(\"|\")})(?=$|[^\\\\p{L}\\\\p{N}])`, \"iu\")\n const out: Array<{ page: GraphPage; excerpt: string; at: string }> = []\n for (const other of g.entities.values()) {\n if (other.id === e.id || other.type === \"event\") continue\n for (const page of other.pages) {\n if (!readable(page)) continue\n const body = bodyOf(page.article.content)\n const m = re.exec(body)\n if (!m) continue\n const start = Math.max(0, m.index - 250)\n out.push({ page, excerpt: body.slice(start, m.index + 450).replace(/\\s+/g, \" \").trim(), at: page.article.meta.lastUpdated || \"\" })\n break\n }\n }\n return out.sort((a, b) => b.at.localeCompare(a.at)).slice(0, max).map(({ page, excerpt }) => ({ page, excerpt }))\n}\n\n/** Changes when the entity gains a source, a page or a linked event. */\nexport function fingerprint(ctx: EnrichContext): string {\n const parts = [\n ...ctx.pages.map(p => `${p.agentId}/${p.article.path}`),\n ...ctx.sources,\n ...ctx.events.map(x => x.id),\n ...ctx.projects.map(x => x.id),\n ...ctx.mentions.map(m => `${m.page.agentId}/${m.page.article.path}`),\n ].sort()\n return createHash(\"sha1\").update(parts.join(\"\\n\")).digest(\"hex\").slice(0, 16)\n}\n\nconst clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s)\n\nexport function buildEnrichPrompt(ctx: EnrichContext, typeLabel: string, today: string): string {\n const e = ctx.entity\n const lines: string[] = [\n `You are bringing one wiki page up to date. Today is ${today}.`,\n `Subject: \"${e.title}\" (${typeLabel}).`,\n \"\",\n \"## What the agents' pages say\",\n ]\n for (const p of ctx.pages) {\n lines.push(`### page ${p.agentId}/${p.article.path} (updated ${p.article.meta.lastUpdated || \"?\"})`, clip(bodyOf(p.article.content), PAGE_CHARS), \"\")\n }\n if (ctx.mentions.length) {\n lines.push(\"## Other pages that name the subject\")\n for (const m of ctx.mentions) lines.push(`### page ${m.page.agentId}/${m.page.article.path}: \"${m.page.article.meta.title}\"`, m.excerpt, \"\")\n }\n lines.push(\"## Source entries (newest first)\")\n for (const en of ctx.entries) lines.push(`### entry ${en.id} (${en.date}, ${en.agentId}, ${en.source})`, clip(en.content.trim(), ENTRY_CHARS), \"\")\n lines.push(\"## Event pages\", ...ctx.events.map(x => `- ${x.date || \"?\"} · ${x.title}`), \"\")\n lines.push(\"## Project pages\", ...ctx.projects.map(x => `- ${x.title}`), \"\")\n lines.push(\"## Other pages it may name\", ...ctx.neighbours.map(x => `- ${x.title} (${x.type})`), \"\")\n lines.push(\n `## Properties you may use (the subject is always ${e.title})`,\n ...[...ctx.properties].map(([id, label]) => `- ${id}: \"${e.title} ${label} <value>\"${ctx.ranges.get(id) ? `, value is a ${ctx.ranges.get(id)!.join(\" or \")}` : \"\"}`),\n \"\",\n )\n lines.push(\n \"## Task\",\n \"Return one JSON object and nothing else:\",\n `{\"overview\": \"…\", \"statements\": [{\"property\": \"…\", \"value\": \"…\", \"role\": \"…\", \"since\": \"YYYY-MM-DD\", \"until\": \"YYYY-MM-DD\", \"source\": \"…\"}], \"history\": [\"event page title\"], \"projects\": [\"project page title\"]}`,\n \"\",\n \"Rules:\",\n `- overview: 3 to 6 full sentences telling the story of the relationship: who ${e.title} is to us, how it started, what changed, and where it stands now, with dates. Plain prose. Link pages as [[Exact Title]] only when the title is listed above. Never stop mid-sentence.`,\n \"- statements: only facts the pages or entries state. Use only the listed properties. value is a listed page title when it names one, else a short literal. role, since and until only when stated.\",\n \"- source: the entry id, the page (agent/path) or the event title the fact comes from. A statement without one of these is dropped.\",\n \"- Do not list an AI agent or bot as a person's relation.\",\n \"- history: titles of the listed event pages that are about the subject. projects: listed project titles it takes part in.\",\n \"- Leave out anything you could not verify. Do not write 'unknown' or 'not captured' as a fact.\",\n \"- Write in the language the pages are written in.\",\n )\n return lines.join(\"\\n\")\n}\n\n/** The JSON object in the reply, fenced or not. */\nexport function parseEnrichReply(text: string): Record<string, unknown> | null {\n const fenced = text.match(/```(?:json)?\\s*\\n([\\s\\S]*?)\\n```/)\n const raw = fenced ? fenced[1] : text.slice(text.indexOf(\"{\"), text.lastIndexOf(\"}\") + 1)\n try {\n const v = JSON.parse(raw)\n return v && typeof v === \"object\" && !Array.isArray(v) ? v as Record<string, unknown> : null\n } catch {\n return null\n }\n}\n\nconst DATE = /^\\d{4}-\\d{2}(-\\d{2})?$/\nconst str = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\")\n\n/** Keep only what the call was shown and allowed to write. */\nexport function checkEnrichment(raw: Record<string, unknown>, ctx: EnrichContext, g: WikiGraph): EnrichResult {\n const dropped: string[] = []\n const e = ctx.entity\n let overview = str(raw.overview)\n if (overview && !/[.!?؟)»\"']$/.test(overview)) {\n // A cut-off last sentence is worse than a shorter overview.\n const end = Math.max(overview.lastIndexOf(\". \"), overview.lastIndexOf(\"? \"), overview.lastIndexOf(\"! \"))\n overview = end > 0 ? overview.slice(0, end + 1) : \"\"\n dropped.push(\"overview: unfinished last sentence removed\")\n }\n\n const sourceIds = [\n ...ctx.entries.map(x => x.id),\n ...ctx.pages.map(p => `${p.agentId}/${p.article.path}`),\n ...ctx.pages.map(p => p.article.path),\n ...ctx.mentions.map(m => `${m.page.agentId}/${m.page.article.path}`),\n ...ctx.mentions.map(m => m.page.article.path),\n ...ctx.events.map(x => x.title),\n ]\n const statements: WikiStatement[] = []\n const seen = new Set<string>()\n for (const item of Array.isArray(raw.statements) ? raw.statements : []) {\n const s = (item ?? {}) as Record<string, unknown>\n const property = str(s.property)\n const value = str(s.value)\n const source = str(s.source)\n const label = `${property} ${value}`\n if (!ctx.properties.has(property)) { dropped.push(`${label}: property not allowed`); continue }\n if (!value || /^(unknown|not (given|known|captured|recorded))\\b/i.test(value)) { dropped.push(`${label}: no value`); continue }\n if (!source || !sourceIds.some(id => source.includes(id))) { dropped.push(`${label}: source not among those given`); continue }\n const targetId = g.names.get(normName(value))\n const target = targetId ? g.entities.get(targetId) : undefined\n if (target?.id === e.id) { dropped.push(`${label}: points at itself`); continue }\n if (e.type === \"person\" && target?.type === \"agent\") { dropped.push(`${label}: an agent is not a person's relation`); continue }\n const range = ctx.ranges.get(property)\n if (range && target && !range.includes(target.type)) { dropped.push(`${label}: value is a ${target.type}, expected ${range.join(\" or \")}`); continue }\n const key = `${property}\\n${normName(value)}`\n if (seen.has(key)) continue\n seen.add(key)\n const st: WikiStatement = { property, value: target?.title ?? value, source: clip(source, 200) }\n const role = str(s.role)\n if (role) st.role = clip(role, 80)\n if (DATE.test(str(s.since))) st.since = str(s.since)\n if (DATE.test(str(s.until))) st.until = str(s.until)\n statements.push(st)\n }\n\n const allowed = new Map([...ctx.events, ...ctx.projects].map(x => [normName(x.title), x.title]))\n const links: string[] = []\n for (const t of [...(Array.isArray(raw.history) ? raw.history : []), ...(Array.isArray(raw.projects) ? raw.projects : [])]) {\n // The prompt lists events as \"date · title\"; a reply may copy the date.\n const title = allowed.get(normName(str(t).replace(/^\\d{4}-\\d{2}-\\d{2}\\s*·\\s*/, \"\")))\n if (title && !links.includes(title)) links.push(title)\n else if (!title && str(t)) dropped.push(`link ${str(t)}: no such page`)\n }\n return { overview, statements, links, dropped }\n}\n\n/** Put the overview at the top of the body, replacing an older one. */\nexport function withOverview(content: string, overview: string): string {\n const section = `## Overview\\n\\n${overview.trim()}\\n\\n${OVERVIEW_END}\\n`\n const span = overviewSpan(content)\n if (span) {\n const ours = content.slice(span.end, span.after) === OVERVIEW_END\n const followed = /^#{1,2}[ \\t]/m.test(content.slice(span.end, span.end + 4))\n // Replace the old text only when its end is certain (this job's marker,\n // or a heading) and, for someone else's, the call was shown all of it.\n // Otherwise keep it below, so nothing is lost.\n const replace = ours || (followed && bodyOf(content).length <= PAGE_CHARS)\n const rest = (replace ? content.slice(span.after) : content.slice(span.textStart)).trim()\n return `${content.slice(0, span.start)}${section}${rest ? `\\n${rest}\\n` : \"\"}`\n }\n return `${section}\\n${content.trim()}\\n`\n}\n\n/** Page meta with the new statements and links merged in. */\nexport function mergedMeta(meta: WikiArticleMeta, r: EnrichResult, today: string): WikiArticleMeta {\n const key = (s: WikiStatement) => `${s.property}\\n${normName(s.value)}`\n // This job's earlier facts are replaced as a whole; others' are kept.\n // A fact someone else already wrote stays theirs, with its status,\n // note and dates: tagging it as ours would drop it on a later run.\n const kept = (meta.statements ?? []).filter(s => s.by !== ENRICH_BY)\n const taken = new Set(kept.map(key))\n const statements = [\n ...kept,\n ...r.statements.filter(s => !taken.has(key(s))).map(s => ({ ...s, checked_at: today, by: ENRICH_BY })),\n ]\n const related = [...new Set([...(meta.related ?? []), ...r.links])]\n return { ...meta, statements: statements.length ? statements : undefined, related: related.length ? related : undefined, lastUpdated: today }\n}\n\n/** The page the result is written to: one this node owns, with the most sources. */\nexport function targetPage(hub: Pick<WikiHub, \"syncedFrom\">, e: Entity): GraphPage | undefined {\n return e.pages\n .filter(p => !hub.syncedFrom(p.agentId))\n .sort((a, b) => (b.article.meta.sources?.length ?? 0) - (a.article.meta.sources?.length ?? 0) || b.article.content.length - a.article.content.length)[0]\n}\n\nconst FOLDERS: Record<string, string> = { person: \"people\", organization: \"organizations\", project: \"projects\", place: \"places\" }\n\n/**\n * A new page for a thing the wiki only names in other pages, typed with\n * `class` so the graph does not have to guess. The enrichment that\n * follows writes its overview and facts from the pages that mention it.\n * Returns the page path, or null when the owner already has that title.\n */\nexport function createEntityPage(hub: WikiHub, name: string, type: string, owner: string, today: string): string | null {\n // Frontmatter is one line per key: a line break would end the title.\n const title = name.replace(/\\s+/g, \" \").trim()\n const store = hub.getAgentWiki(owner)\n if (store.listAllArticles().some(a => normName(a.meta.title) === normName(title))) return null\n const path = `${FOLDERS[type] ?? `${type}s`}/${normName(title).replace(/ /g, \"-\").slice(0, 80) || \"page\"}.md`\n const legacy = isWikiArticleType(type) ? type : undefined\n const meta: WikiArticleMeta = { title, type: legacy, class: type, tags: [], owner, access: \"shared\", created: today, lastUpdated: today, sources: [] }\n return store.writeArticle(path, meta, `${title}.\\n`, owner) ? path : null\n}\n\nexport function loadEnrichState(wikiDir: string): EnrichState {\n const file = resolve(wikiDir, \"_enrich\", \"state.json\")\n if (!existsSync(file)) return { entities: {} }\n try {\n const v = JSON.parse(readFileSync(file, \"utf-8\"))\n return v && typeof v.entities === \"object\" ? v : { entities: {} }\n } catch {\n return { entities: {} }\n }\n}\n\nexport function saveEnrichState(wikiDir: string, state: EnrichState): void {\n mkdirSync(resolve(wikiDir, \"_enrich\"), { recursive: true })\n writeFileSync(resolve(wikiDir, \"_enrich\", \"state.json\"), JSON.stringify(state, null, 2))\n}\n\nexport interface EnrichCall {\n (prompt: string): Promise<{ text: string; costUsd: number }>\n}\n\nexport interface EnrichOptions {\n types: string[]\n /** Entity ids or titles; empty means every entity of the types. */\n only: string[]\n max: number\n maxCostUsd: number\n dryRun: boolean\n /** Redo entities whose sources did not change. */\n force: boolean\n today: string\n /** Persists the state; called after every paid call. */\n save?: (state: EnrichState) => void\n}\n\nexport interface EnrichOutcome {\n entity: string\n title: string\n page?: string\n status: \"written\" | \"dry-run\" | \"unchanged\" | \"no-page\" | \"no-reply\" | \"nothing-new\" | \"failed\"\n statements: number\n links: number\n overview: boolean\n costUsd: number\n dropped: string[]\n /** Dry runs: the body that would be written, and the facts. */\n preview?: string\n facts?: WikiStatement[]\n}\n\nexport interface EnrichRun {\n outcomes: EnrichOutcome[]\n costUsd: number\n /** Set when the run stopped at its spending cap. */\n capped: boolean\n}\n\nexport async function runEnrich(hub: WikiHub, g: WikiGraph, call: EnrichCall, opts: EnrichOptions, state: EnrichState): Promise<EnrichRun> {\n const types = new Set(opts.types)\n const only = new Set(opts.only.map(normName))\n const size = (e: Entity) => e.sources.length + e.pages.length\n // Entities whose last calls failed go last, so they cannot starve the rest.\n const failures = (e: Entity) => state.entities[e.id]?.failures ?? 0\n const candidates = [...g.entities.values()]\n .filter(e => types.has(e.type))\n .filter(e => only.size === 0 || only.has(normName(e.id)) || only.has(normName(e.title)))\n .sort((a, b) => failures(a) - failures(b) || size(b) - size(a))\n const readEntries = (ids: string[]) => hub.getSharedStore().readEntries(ids)\n const run: EnrichRun = { outcomes: [], costUsd: 0, capped: false }\n let calls = 0\n // Saved after every paid call, so a run killed part-way (a job's\n // timeout, then its retry) does not pay for the same entities again.\n const remember = (id: string, fp: string, costUsd: number, failed = false) => {\n if (opts.dryRun) return\n const prev = state.entities[id]\n state.entities[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 = { entity: e.id, title: e.title, statements: 0, links: 0, overview: false, costUsd: 0, dropped: [] as string[] }\n const page = targetPage(hub, e)\n if (!page) { run.outcomes.push({ ...base, status: \"no-page\" }); continue }\n const ctx = enrichContext(g, e, readEntries, page)\n const fp = fingerprint(ctx)\n if (!opts.force && state.entities[e.id]?.fingerprint === fp) {\n if (only.size) run.outcomes.push({ ...base, status: \"unchanged\" })\n continue\n }\n if (run.costUsd >= opts.maxCostUsd) { run.capped = true; break }\n\n calls++\n const label = g.ontology.types.find(t => t.id === e.type)?.label ?? e.type\n const where = `${page.agentId}/${page.article.path}`\n let reply: { text: string; costUsd: number }\n try {\n reply = await call(buildEnrichPrompt(ctx, label, 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 parsed = parseEnrichReply(reply.text)\n const outcome: EnrichOutcome = { ...base, page: where, status: \"no-reply\", costUsd: reply.costUsd }\n // A paid answer with nothing usable is remembered too: the same\n // sources would give the same answer.\n if (!parsed) { run.outcomes.push(outcome); remember(e.id, fp, reply.costUsd); continue }\n const r = checkEnrichment(parsed, ctx, g)\n Object.assign(outcome, { statements: r.statements.length, links: r.links.length, overview: !!r.overview, dropped: r.dropped })\n if (!r.overview && r.statements.length === 0 && r.links.length === 0) {\n outcome.status = \"nothing-new\"\n run.outcomes.push(outcome)\n remember(e.id, fp, reply.costUsd)\n continue\n }\n\n const withNew = (a: { content: string }) => (r.overview ? withOverview(a.content, r.overview) : a.content)\n if (opts.dryRun) {\n run.outcomes.push({ ...outcome, status: \"dry-run\", preview: withNew(page.article), facts: r.statements })\n continue\n }\n const store = hub.getAgentWiki(page.agentId)\n // Absorb may have changed the page while the run waited for the model:\n // merge onto what is on disk now, not the copy read at the start. The\n // page lock keeps another write from landing between this read and\n // the write.\n let why: string | undefined\n try {\n why = store.withArticleLock(page.article.path, () => {\n const current = store.readArticle(page.article.path)\n if (!current) return \"the page was moved or removed during the run\"\n return store.writeArticle(page.article.path, mergedMeta(current.meta, r, opts.today), withNew(current), current.meta.owner || page.agentId) ? undefined : \"write refused\"\n })\n } catch (err) {\n if (!(err instanceof LockBusyError)) throw err\n why = \"the page was busy; run again\"\n }\n if (why) {\n outcome.status = \"failed\"\n outcome.dropped.push(why)\n run.outcomes.push(outcome)\n remember(e.id, fp, reply.costUsd, true)\n continue\n }\n store.rebuildIndex()\n remember(e.id, fp, reply.costUsd)\n outcome.status = \"written\"\n run.outcomes.push(outcome)\n }\n return run\n}\n"],"mappings":"oOAeA,OAAS,cAAAA,MAAkB,SAC3B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,MAAe,OAUjB,IAAMC,EAAY,cAEZC,GAAc,CAAC,SAAU,eAAgB,UAAW,QAAS,SAAU,SAAU,MAAO,SAAU,SAAS,EAGlHC,EAAwB,IAAI,IAAI,CAAC,SAAU,eAAgB,UAAW,OAAO,CAAC,EAuC9EC,EAAa,KACbC,EAAc,IAGb,SAASC,EAAeC,EAAcC,EAAmC,CAC9E,IAAMC,EAAOF,EAAE,SAAS,MAAM,KAAKG,GAAKA,EAAE,KAAOF,CAAI,GAAG,MAAQ,CAAC,EAC3DG,EAAM,IAAI,IAChB,QAAWC,KAASH,EAClB,GAAII,EAAYD,CAAK,IAAM,aAC3B,QAAWE,KAAMC,EAAUH,CAAK,EAAG,CACjC,GAAIE,IAAO,WAAaH,EAAI,IAAIG,CAAE,EAAG,SACrC,IAAME,EAAMT,EAAE,SAAS,WAAW,KAAKU,GAAKA,EAAE,KAAOH,CAAE,EAEnDE,GAAK,QAAU,CAACA,EAAI,OAAO,SAASR,CAAI,GAC5CG,EAAI,IAAIG,EAAIE,GAAK,OAASF,EAAG,QAAQ,KAAM,GAAG,CAAC,EAGnD,OAAOH,CACT,CAGA,SAASO,EAAQX,EAAcY,EAAWX,EAAwB,CAChE,IAAMY,EAAOC,EAASF,EAAE,KAAK,EAC7B,OAAIC,EAAK,OAAS,EAAU,CAAC,EACtB,CAAC,GAAGb,EAAE,SAAS,OAAO,CAAC,EAAE,OAAOe,GAAKA,EAAE,OAASd,GAAQc,EAAE,KAAO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,EAASzH,EAAE,GAAI0H,EAAIM,EAAM,OAAO,EAChC,SAGF,IAAMI,EAAW3H,GAA4B8E,EAAE,SAAWX,GAAanE,EAAE,QAAS8E,EAAE,QAAQ,EAAI9E,EAAE,QAClG,GAAIuG,EAAK,OAAQ,CACfO,EAAI,SAAS,KAAK,CAAE,GAAGY,EAAS,OAAQ,UAAW,QAASC,EAAQjG,EAAK,OAAO,EAAG,MAAOoD,EAAE,UAAW,CAAC,EACxG,SAEF,IAAMS,EAAQJ,EAAI,aAAazD,EAAK,OAAO,EAKvCkG,EACJ,GAAI,CACFA,EAAMrC,EAAM,gBAAgB7D,EAAK,QAAQ,KAAM,IAAM,CACnD,IAAMmG,EAAUtC,EAAM,YAAY7D,EAAK,QAAQ,IAAI,EACnD,OAAKmG,EACEtC,EAAM,aAAa7D,EAAK,QAAQ,KAAMkD,GAAWiD,EAAQ,KAAM/C,EAAGyB,EAAK,KAAK,EAAGoB,EAAQE,CAAO,EAAGA,EAAQ,KAAK,OAASnG,EAAK,OAAO,EAAI,OAAY,gBADrI,8CAEvB,CAAC,CACH,OAAS8F,EAAP,CACA,GAAI,EAAEA,aAAeM,GAAgB,MAAMN,EAC3CI,EAAM,8BACR,CACA,GAAIA,EAAK,CACPF,EAAQ,OAAS,SACjBA,EAAQ,QAAQ,KAAKE,CAAG,EACxBd,EAAI,SAAS,KAAKY,CAAO,EACzBV,EAASzH,EAAE,GAAI0H,EAAIM,EAAM,QAAS,EAAI,EACtC,SAEFhC,EAAM,aAAa,EACnByB,EAASzH,EAAE,GAAI0H,EAAIM,EAAM,OAAO,EAChCG,EAAQ,OAAS,UACjBZ,EAAI,SAAS,KAAKY,CAAO,EAE3B,OAAOZ,CACT","names":["createHash","existsSync","mkdirSync","readFileSync","writeFileSync","resolve","ENRICH_BY","ENRICH_TYPES","PERSON_RELATION_TYPES","PAGE_CHARS","ENTRY_CHARS","lensProperties","g","type","lens","t","out","panel","panelSource","id","panelFrom","def","p","namedIn","e","name","normName","x","readers","m","readableAlongside","source","target","a","enrichContext","readEntries","readable","visible","pages","sources","linked","linkedEntities","byId","list","events","b","projects","neighbours","entries","properties","ranges","range","mentionsOf","max","names","n","escaped","re","other","page","body","bodyOf","start","excerpt","fingerprint","ctx","parts","createHash","clip","s","buildEnrichPrompt","typeLabel","today","lines","en","label","parseEnrichReply","text","fenced","raw","v","DATE","str","checkEnrichment","dropped","overview","end","sourceIds","statements","seen","item","property","value","targetId","key","st","role","allowed","links","title","withOverview","content","section","OVERVIEW_END","span","overviewSpan","ours","followed","rest","mergedMeta","meta","r","kept","taken","related","targetPage","hub","FOLDERS","createEntityPage","owner","store","path","legacy","isWikiArticleType","loadEnrichState","wikiDir","file","resolve","existsSync","readFileSync","saveEnrichState","state","mkdirSync","writeFileSync","runEnrich","call","opts","types","only","size","failures","candidates","ids","run","calls","remember","fp","costUsd","failed","prev","base","where","reply","err","parsed","outcome","withNew","why","current","LockBusyError"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{i as x,k as A}from"./chunk-
|
|
1
|
+
import{i as x,k as A}from"./chunk-AKWBDCMU.js";import{a as w,e as D}from"./chunk-2QNT5JDS.js";D();var h="guest:",b="guests",P=7,y=365,T=400;function I(e){let t=e.scopes.find(n=>n.startsWith(h));return t?t.slice(h.length):null}function _(e){return`g-${e.toString(36)}-${Math.random().toString(36).slice(2,6)}`}var l=e=>(Array.isArray(e)?e:typeof e=="string"?e.split(","):[]).map(t=>String(t).trim()).filter(Boolean).slice(0,50);function M(e,t){let n=(e.now??Date.now)(),o=String(t.name??"").trim().slice(0,120),s=String(t.guest??"").trim().slice(0,80);if(!o)return{ok:!1,error:'name is required: what you call this grant, e.g. "Support session for company X"'};if(!s)return{ok:!1,error:"guest is required: the other organisation's name"};if(!t.agentId||!e.hasAgent(t.agentId))return{ok:!1,error:`agent must be an agent on this node, got "${t.agentId??""}"`};let a=w.safeParse(t.level??"propose");if(!a.success)return{ok:!1,error:"level must be report, propose or act"};let r=t.days===void 0?P:Number(t.days);if(!Number.isFinite(r)||r<1||r>y)return{ok:!1,error:`days must be between 1 and ${y}`};let d=_(n),{token:u,record:g}=e.tokens.create({name:`guest ${s} (${o})`,scopes:[`${h}${d}`],expiresInDays:Math.ceil(r)}),{code:i,expiresAt:p}=e.codes.create({token:u,tokenId:g.id,name:d}),c={id:d,name:o,guest:s,agentId:t.agentId,folders:l(t.folders),skills:l(t.skills),commands:l(t.commands),level:a.data,state:"pending",tokenId:g.id,createdAt:new Date(n).toISOString(),expiresAt:new Date(n+r*864e5).toISOString(),usage:{turns:0,tokens:0}};return e.guests.add(c),e.guests.log({grant:d,event:"invited",detail:`${s}: ${o}`}),{ok:!0,code:i,codeExpiresAt:p,grant:c}}var j="That code didn't work. Ask the host for a new one.";async function Y(e,t,n){let o=Date.now(),s=n.now??Date.now,a=n.log??(f=>console.log(f)),r=n.limiter.retryAfter(t);if(r>0)return a(`[guests] join refused from ${t}: locked out for ${r}s more`),{status:429,body:{error:"too many attempts",retryAfter:r},retryAfter:r};let d=n.codes.redeem(e.code),u=d?n.tokens.verify(d.token):null,g=u?I(u):null,i=g?n.guests.get(g):null;if(await L(o,n.minMs??T),!d||!u||!i||i.tokenId!==u.id||i.state==="ended")return n.limiter.fail(t),a(`[guests] join failed from ${t}`),{status:401,body:{error:j}};n.limiter.succeed(t);let p=e.node&&typeof e.node=="object"?e.node:{},c=(f,S)=>typeof f=="string"&&f.trim()?f.replace(/\s+/g," ").trim().slice(0,S):void 0,m={id:c(p.id,80),name:c(p.name,80),address:t},$=i.expiresAt.slice(0,10),k=A(n.root,{title:`Guest mesh: ${i.guest} wants to join`,ask:`Let "${m.name??m.id??"a node"}" at ${t} use ${i.agentId} inside "${i.name}" (${i.level}, until ${$})?`,recommend:`Yes if ${i.guest} told you they are joining now. No if you did not expect it.`,if_silent:"discard",raised_by:b},{now:s()});return k.ok?(n.guests.update(i.id,{guestNode:m,cardId:k.card.id}),n.guests.log({grant:i.id,event:"joined",address:t,detail:m.name??m.id}),a(`[guests] ${i.id}: ${i.guest} joined from ${t}; waiting for the owner (card ${k.card.id})`),{status:200,body:{grant:i.id,name:i.name,agentId:i.agentId,level:i.level,expiresAt:i.expiresAt,state:"pending"},token:d.token}):(a(`[guests] ${i.id}: join from ${t} could not raise a card: ${k.error}`),{status:403,body:{error:"The host cannot take a join right now. Try again later."}})}var G="no grant opens this",R="waiting for the host to approve the join",O="the host paused this grant";function N(e,t){let n=e.now??Date.now,o=e.log??(r=>console.log(r));if(t.state==="ended")return t;if(Date.parse(t.expiresAt)<=n())return o(`[guests] ${t.id}: expired`),v({tokens:e.tokens,guests:e.guests,now:n},t.id,"expired")??t;if(t.state!=="pending")return t;let s=t.cardId?x(e.root,t.cardId):null,a=s?s.status==="decided"?s.verdict:s.status==="expired"?"no":null:null;if(a==="yes"){let r=e.guests.update(t.id,{state:"active",approvedAt:new Date(n()).toISOString()})??t;return e.guests.log({grant:t.id,event:"approved",detail:s?.decided_by}),o(`[guests] ${t.id}: join approved`),r}if(a==="no"){let r=s?.status==="expired"?"the host did not answer in time":"the host said no",d=v({tokens:e.tokens,guests:e.guests,now:n},t.id,r)??t;return e.guests.log({grant:t.id,event:"refused",detail:r}),o(`[guests] ${t.id}: join refused: ${r}`),d}return t}function J(e,t){let n=e?t.tokens.verify(e):null,o=n?I(n):null,s=o?t.guests.get(o):null;if(!n||!s||s.tokenId!==n.id)return{ok:!1,status:401,error:G};let a=N(t,s);return a.state==="ended"?{ok:!1,status:401,error:G}:a.state==="pending"?{ok:!1,status:403,error:R,waiting:!0}:a.state==="paused"?{ok:!1,status:403,error:O,paused:!0}:{ok:!0,grant:a}}function C(e){let t=(o,s)=>o.length?o.join(", "):`none named: do not touch ${s} unless the owner's own instructions already allow it for this work`,n=e.level==="report"?"report: read and answer only; change nothing":e.level==="propose"?"propose: you may prepare changes and open a merge request or draft; never merge, deploy or delete":"act: you may act inside the grant without asking";return[`[Guest mesh] You are working for a guest organisation, "${e.guest}", under the grant "${e.name}" that the owner of this node opened.`,`Stay inside it. Folders: ${t(e.folders,"files")}. Skills: ${t(e.skills,"skills")}. Commands: ${t(e.commands,"commands")}. Freedom: ${n}. The grant ends on ${e.expiresAt.slice(0,10)}.`,"Anything outside the grant: say it is not covered and stop. The guest sees only your answers: never reveal other chats, agents, people or files of this node."].join(`
|
|
2
2
|
`)}function q(e,t){return{agentId:e.agentId,message:t,context:{channel:"guest",chatId:`guest:${e.id}`,sender:`guest:${e.guest}`},systemPromptAppend:C(e),...e.level==="act"?{}:{autonomy:e.level}}}function B(e,t){let n=e.guests.get(t);if(!n||n.state!=="active")return null;let o=e.guests.update(t,{state:"paused",pausedAt:new Date((e.now??Date.now)()).toISOString()});return e.guests.log({grant:t,event:"paused"}),o}function U(e,t){let n=e.guests.get(t);if(!n||n.state!=="paused")return null;let o=e.guests.update(t,{state:"active",pausedAt:void 0});return e.guests.log({grant:t,event:"resumed"}),o}function v(e,t,n="ended by the host"){let o=e.guests.get(t);if(!o||o.state==="ended")return null;e.tokens.revoke(o.tokenId);let s=e.guests.update(t,{state:"ended",endedAt:new Date((e.now??Date.now)()).toISOString(),endedReason:n});return e.guests.log({grant:t,event:n==="expired"?"expired":"ended",detail:n}),s}function X(e,t,n){let o=e.guests.get(t);if(!o||o.state==="ended")return{ok:!1,error:`no open grant "${t}"`};let s={};if(n.folders!==void 0&&(s.folders=l(n.folders)),n.skills!==void 0&&(s.skills=l(n.skills)),n.commands!==void 0&&(s.commands=l(n.commands)),n.level!==void 0){let u=w.safeParse(n.level);if(!u.success)return{ok:!1,error:"level must be report, propose or act"};s.level=u.data}if(n.days!==void 0){let u=Number(n.days);if(!Number.isFinite(u)||u<1||u>y)return{ok:!1,error:`days must be between 1 and ${y}`};s.expiresAt=new Date((e.now??Date.now)()+u*864e5).toISOString()}let a=e.guests.update(t,s),r=["report","propose","act"],d=s.level&&r.indexOf(s.level)>r.indexOf(o.level)||s.folders&&s.folders.length>o.folders.length||s.skills&&s.skills.length>o.skills.length||s.commands&&s.commands.length>o.commands.length||s.expiresAt&&s.expiresAt>o.expiresAt;return e.guests.log({grant:t,event:d?"widened":"narrowed",detail:Object.keys(s).join(", ")}),{ok:!0,grant:a}}function W(e){return{grant:e.id,name:e.name,agentId:e.agentId,level:e.level,folders:e.folders,skills:e.skills,commands:e.commands,state:e.state,expiresAt:e.expiresAt,usage:e.usage}}async function L(e,t){let n=e+t-Date.now();n>0&&await new Promise(o=>setTimeout(o,n))}export{h as a,b,P as c,y as d,I as e,_ as f,M as g,j as h,Y as i,G as j,R as k,O as l,N as m,J as n,C as o,q as p,B as q,U as r,v as s,X as t,W as u};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-UNIXYV3U.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pa as l,xa as m}from"./chunk-
|
|
1
|
+
import{pa as l,xa as m}from"./chunk-54OORW5I.js";m();import{existsSync as g,readFileSync as u,writeFileSync as a,copyFileSync as y}from"fs";import{resolve as p}from"path";function P(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(!g(t))throw new Error(`agentx.json not found at ${t}`);let i=JSON.parse(u(t,"utf-8")),o=e(i),s=typeof o=="string"?{summary:o}:o,c=JSON.stringify(i,null,2)+`
|
|
2
2
|
`,f=t+".tmp";a(f,c,"utf-8");try{JSON.parse(u(f,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let r;return n.skipBackup||(r=`${t}.bak.${Date.now()}`,y(t,r)),a(t,c,"utf-8"),n.skipReload||h().catch(()=>{}),{summary:s.summary,payload:s.payload,backupPath:r}}function S(e,n={}){let t=n.configPath||p(process.cwd(),"agentx.json");if(g(t)&&!n.overwrite)throw new Error(`agentx.json already exists at ${t}. Pass overwrite=true to replace it.`);return a(t,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8"),{file:t}}async function h(){try{let n=l().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${n}/reload`,{method:"POST"}).catch(()=>null)}catch{}}export{P as a,S as b};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-VA24JS2S.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{na as m,oa as $,xa as x}from"./chunk-
|
|
1
|
+
import{na as m,oa as $,xa as x}from"./chunk-54OORW5I.js";x();import{readFileSync as S,writeFileSync as P,existsSync as b}from"fs";import{resolve as f}from"path";function w(r){if(r)return f(r);let e=[f(process.cwd(),"agentx.json"),f(process.cwd(),".agentx/config.json")];for(let n of e)if(b(n))return n;return e[0]}function v(r){return JSON.parse(JSON.stringify(r))}async function O(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function J(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:u,daemonUrl:c}=e,o=w(u);if(!b(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let d;try{d=S(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let g;try{g=JSON.parse(d)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=v(g);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=$(i),l=m.safeParse(a);if(!l.success){let k=l.error.issues.map(y=>` ${y.path.join(".")||"<root>"}: ${y.message}`).join(`
|
|
2
2
|
`);return{success:!1,path:o,error:`Validation failed:
|
|
3
3
|
${k}`,after:i}}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{P(o,JSON.stringify(i,null,2)+`
|
|
4
4
|
`)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let p=!1,h;if(s){let a=c||R(i),l=await O(a);l.ok?p=!0:h=l.reason}return{success:!0,path:o,after:i,reloaded:p,reloadSkipped:h}}function R(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function N(r,e,n){let t=e.split("."),s=r;for(let u=0;u<t.length-1;u++){let c=t[u];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function j(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function A(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{w as a,J as b,N as c,j as d,A as e};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-WRJFKA43.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-3RE5SG22.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-ZPJVDX2U.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var s=o(process.versions.node);s&&(console.error(s),process.exit(1));var{buildProgram:r}=await import("./program-WROQ55F5.js"),{installCliSignalExit:i}=await import("./signal-exit-WL7G3EEZ.js");i();var e=await r();process.argv.slice(2).length===0?e.outputHelp():e.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-5X37CXJF.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-SMOWSRJY.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g,ja as h,ka as i,la as j,ma as k,na as l,oa as m,pa as n,qa as o,ra as p,sa as q,ta as r,ua as s,va as t,xa as u}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-
|
|
1
|
+
import{ca as a,da as b,ea as c,fa as d,ga as e,ha as f,ia as g,ja as h,ka as i,la as j,ma as k,na as l,oa as m,pa as n,qa as o,ra as p,sa as q,ta as r,ua as s,va as t,xa as u}from"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";u();export{a as INTEGRATION_KINDS,p as WIKI_CONTRIBUTE_JOB,q as WIKI_CONTRIBUTE_MERGE_JOB,s as WIKI_SUMMARIZE_JOB,k as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,l as daemonConfigSchema,b as eventSubscriptionSchema,m as expandEnvVars,d as isCronExpression,n as loadDaemonConfig,i as membersConfigSchema,h as peopleConfigSchema,g as personSchema,j as requestStatusConfigSchema,f as requestsConfigSchema,o as validateWorkspaces,r as withContributionJobs,t as withSummariesJob};
|
|
2
|
+
//# sourceMappingURL=config-OGUDWYAA.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-mutate-
|
|
1
|
+
import{a,b}from"./chunk-VA24JS2S.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-BH27TMWK.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-WRJFKA43.js";import"./chunk-54OORW5I.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-Q62AS2TR.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-
|
|
1
|
+
import{a as ee}from"./chunk-EVTTAM7S.js";import"./chunk-KZXQD6ZK.js";import{f as Q,k as V}from"./chunk-QSKG754X.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.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-66DPMVUC.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-6TURWSMN.js";import"./chunk-QD6IICK7.js";import{b as N,c as H}from"./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";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
3
|
${k.join(`
|
|
4
4
|
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
|
|
|
54
54
|
`).replace(/\n{3,}/g,`
|
|
55
55
|
|
|
56
56
|
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
-
//# sourceMappingURL=contributions-
|
|
57
|
+
//# sourceMappingURL=contributions-H6T65TCY.js.map
|