agentix-cli 0.146.0 → 0.147.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-EU2AJWW5.js → App-AW4OROPH.js} +2 -2
- package/dist/{ChatApp-ORR3U3AN.js → ChatApp-USXQHII3.js} +2 -2
- package/dist/{absorb-eval-3VGPDRWS.js → absorb-eval-WZCC5VPS.js} +2 -2
- package/dist/{agent-NVJNOK5L.js → agent-TJ2K7FZG.js} +2 -2
- package/dist/{board-dashboard-JV2JNRWD.js → board-dashboard-JY4YQ5TM.js} +216 -216
- package/dist/board-dashboard-JY4YQ5TM.js.map +1 -0
- package/dist/{chunk-OEB6RTRA.js → chunk-4F5XUF6T.js} +2 -2
- package/dist/{chunk-TZVJP4H3.js → chunk-5TGY4RIQ.js} +2 -2
- package/dist/chunk-6UP5VD3H.js +64 -0
- package/dist/{chunk-IBK7AG4S.js.map → chunk-6UP5VD3H.js.map} +1 -1
- package/dist/{chunk-5TFXFLMN.js → chunk-7HCSLOTP.js} +3 -3
- package/dist/{chunk-7O7VDA3J.js → chunk-7ICJCJ43.js} +2 -2
- package/dist/{chunk-WCOT35YG.js → chunk-7T6SMNVY.js} +2 -2
- package/dist/{chunk-SNCRLEH3.js → chunk-7W3TLSZQ.js} +5 -5
- package/dist/chunk-E7YHXMJG.js +7 -0
- package/dist/chunk-E7YHXMJG.js.map +1 -0
- package/dist/{chunk-3BMIZY6X.js → chunk-EG7Y2XLK.js} +2 -2
- package/dist/{chunk-OT5KLHUT.js → chunk-EKAUOUN2.js} +2 -2
- package/dist/{chunk-USTNT7P7.js → chunk-GJMYG53S.js} +2 -2
- package/dist/{chunk-TYONASHA.js → chunk-GLLHUHX2.js} +41 -41
- package/dist/chunk-GLLHUHX2.js.map +1 -0
- package/dist/{chunk-SK24JFEK.js → chunk-GTOQWMRY.js} +2 -2
- package/dist/chunk-HAEI2LNC.js +7 -0
- package/dist/chunk-HAEI2LNC.js.map +1 -0
- package/dist/chunk-JCFVH3NC.js +533 -0
- package/dist/chunk-JCFVH3NC.js.map +1 -0
- package/dist/{chunk-5YAUENDI.js → chunk-JLEVL66V.js} +2 -2
- package/dist/{chunk-WBG6NA7R.js → chunk-KP7KDLZ2.js} +2 -2
- package/dist/{chunk-O7ZJS33Z.js → chunk-KW6SHOAN.js} +2 -2
- package/dist/{chunk-QNS3WHGU.js → chunk-MXDTLR45.js} +2 -2
- package/dist/{chunk-UYLVSS6I.js → chunk-P5BFFU4Y.js} +2 -2
- package/dist/{chunk-MOCKFVYE.js → chunk-P6PFTNN4.js} +2 -2
- package/dist/{chunk-UFX6INNI.js → chunk-PUW4C6YO.js} +2 -2
- package/dist/{chunk-DG2DC43E.js → chunk-PYHR4HXO.js} +2 -2
- package/dist/{chunk-UTYNYG7M.js → chunk-Q2QU32JP.js} +2 -2
- package/dist/{chunk-GECGRCYC.js → chunk-QXPX2NGL.js} +2 -2
- package/dist/{chunk-UVJLIHLL.js → chunk-UVF3K5YS.js} +2 -2
- package/dist/{chunk-DTWBB7B7.js → chunk-YE2X3AFU.js} +2 -2
- package/dist/chunk-Z3AI4KXT.js +18 -0
- package/dist/chunk-Z3AI4KXT.js.map +1 -0
- package/dist/{chunk-NBDYBTI6.js → chunk-ZZNAR6R2.js} +256 -256
- package/dist/chunk-ZZNAR6R2.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-6KZZKCN2.js → client-GLBNS45C.js} +2 -2
- package/dist/config-VRDFC7LW.js +2 -0
- package/dist/{config-mutate-57YT7BNB.js → config-mutate-HU3KKYCD.js} +2 -2
- package/dist/config-mutator-JCAIGP6W.js +2 -0
- package/dist/{contributions-Y6B6LG7X.js → contributions-JXPYCLVB.js} +2 -2
- package/dist/doctor-5Y7QSXNQ.js +2 -0
- package/dist/{follow-up-tool-5AMZKVI4.js → follow-up-tool-53AYA2UQ.js} +2 -2
- package/dist/{hub-BZF3ZYQ5.js → hub-YCOUZFNU.js} +2 -2
- package/dist/index.d.ts +75 -1
- package/dist/index.js +1 -1
- package/dist/{program-MO7HLAP5.js → program-CIJEGFYG.js} +209 -209
- package/dist/program-CIJEGFYG.js.map +1 -0
- package/dist/{promote-IJANZNQK.js → promote-THTEHZHU.js} +2 -2
- package/dist/{query-DC74NB3R.js → query-N7JBDLR7.js} +2 -2
- package/dist/{query-settings-RXFOATOZ.js → query-settings-BJTVDDCH.js} +2 -2
- package/dist/{registry-24IXRDWX.js → registry-LJ66OZYJ.js} +2 -2
- package/dist/{request-planner-33CWWCJU.js → request-planner-PCELXLK7.js} +2 -2
- package/dist/{review-candidates-ENWB6LHD.js → review-candidates-EMJUROJH.js} +2 -2
- package/dist/{routing-AUFJ4MNP.js → routing-D2KNBEMG.js} +2 -2
- package/dist/schedule-tool-55MOWHKD.js +2 -0
- package/dist/{scheduler-KWSBBZKW.js → scheduler-73UEBYV4.js} +2 -2
- package/dist/{seat-YGMLJ6KS.js → seat-UFAMWG7M.js} +2 -2
- package/dist/{select-JJGBM6ZT.js → select-EPWELLAV.js} +2 -2
- package/dist/{set-enabled-THE7QIGQ.js → set-enabled-LS65QZQS.js} +2 -2
- package/dist/{tool-6LR6VORJ.js → tool-4S3YKLCN.js} +2 -2
- package/dist/{tool-4ACTSFKC.js → tool-7LKYIA6D.js} +2 -2
- package/dist/{wiki-YAW7UEOQ.js → wiki-LHT6X2JF.js} +2 -2
- package/dist/wiki-enrich-CBBS3AC7.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-JV2JNRWD.js.map +0 -1
- package/dist/chunk-IBK7AG4S.js +0 -62
- package/dist/chunk-J723FL3J.js +0 -7
- package/dist/chunk-J723FL3J.js.map +0 -1
- package/dist/chunk-K3QDK4BX.js +0 -5
- package/dist/chunk-K3QDK4BX.js.map +0 -1
- package/dist/chunk-MO7DH5L6.js +0 -535
- package/dist/chunk-MO7DH5L6.js.map +0 -1
- package/dist/chunk-NBDYBTI6.js.map +0 -1
- package/dist/chunk-S2GAEH2F.js +0 -13
- package/dist/chunk-S2GAEH2F.js.map +0 -1
- package/dist/chunk-TYONASHA.js.map +0 -1
- package/dist/config-W6JNVPBY.js +0 -2
- package/dist/config-mutator-6NWQPE7K.js +0 -2
- package/dist/doctor-ZP4KADAD.js +0 -2
- package/dist/program-MO7HLAP5.js.map +0 -1
- package/dist/schedule-tool-NAMOBMZE.js +0 -2
- package/dist/wiki-enrich-6ANFA2VB.js +0 -2
- /package/dist/{App-EU2AJWW5.js.map → App-AW4OROPH.js.map} +0 -0
- /package/dist/{ChatApp-ORR3U3AN.js.map → ChatApp-USXQHII3.js.map} +0 -0
- /package/dist/{absorb-eval-3VGPDRWS.js.map → absorb-eval-WZCC5VPS.js.map} +0 -0
- /package/dist/{agent-NVJNOK5L.js.map → agent-TJ2K7FZG.js.map} +0 -0
- /package/dist/{chunk-OEB6RTRA.js.map → chunk-4F5XUF6T.js.map} +0 -0
- /package/dist/{chunk-TZVJP4H3.js.map → chunk-5TGY4RIQ.js.map} +0 -0
- /package/dist/{chunk-5TFXFLMN.js.map → chunk-7HCSLOTP.js.map} +0 -0
- /package/dist/{chunk-7O7VDA3J.js.map → chunk-7ICJCJ43.js.map} +0 -0
- /package/dist/{chunk-WCOT35YG.js.map → chunk-7T6SMNVY.js.map} +0 -0
- /package/dist/{chunk-SNCRLEH3.js.map → chunk-7W3TLSZQ.js.map} +0 -0
- /package/dist/{chunk-3BMIZY6X.js.map → chunk-EG7Y2XLK.js.map} +0 -0
- /package/dist/{chunk-OT5KLHUT.js.map → chunk-EKAUOUN2.js.map} +0 -0
- /package/dist/{chunk-USTNT7P7.js.map → chunk-GJMYG53S.js.map} +0 -0
- /package/dist/{chunk-SK24JFEK.js.map → chunk-GTOQWMRY.js.map} +0 -0
- /package/dist/{chunk-5YAUENDI.js.map → chunk-JLEVL66V.js.map} +0 -0
- /package/dist/{chunk-WBG6NA7R.js.map → chunk-KP7KDLZ2.js.map} +0 -0
- /package/dist/{chunk-O7ZJS33Z.js.map → chunk-KW6SHOAN.js.map} +0 -0
- /package/dist/{chunk-QNS3WHGU.js.map → chunk-MXDTLR45.js.map} +0 -0
- /package/dist/{chunk-UYLVSS6I.js.map → chunk-P5BFFU4Y.js.map} +0 -0
- /package/dist/{chunk-MOCKFVYE.js.map → chunk-P6PFTNN4.js.map} +0 -0
- /package/dist/{chunk-UFX6INNI.js.map → chunk-PUW4C6YO.js.map} +0 -0
- /package/dist/{chunk-DG2DC43E.js.map → chunk-PYHR4HXO.js.map} +0 -0
- /package/dist/{chunk-UTYNYG7M.js.map → chunk-Q2QU32JP.js.map} +0 -0
- /package/dist/{chunk-GECGRCYC.js.map → chunk-QXPX2NGL.js.map} +0 -0
- /package/dist/{chunk-UVJLIHLL.js.map → chunk-UVF3K5YS.js.map} +0 -0
- /package/dist/{chunk-DTWBB7B7.js.map → chunk-YE2X3AFU.js.map} +0 -0
- /package/dist/{client-6KZZKCN2.js.map → client-GLBNS45C.js.map} +0 -0
- /package/dist/{config-W6JNVPBY.js.map → config-VRDFC7LW.js.map} +0 -0
- /package/dist/{config-mutate-57YT7BNB.js.map → config-mutate-HU3KKYCD.js.map} +0 -0
- /package/dist/{config-mutator-6NWQPE7K.js.map → config-mutator-JCAIGP6W.js.map} +0 -0
- /package/dist/{contributions-Y6B6LG7X.js.map → contributions-JXPYCLVB.js.map} +0 -0
- /package/dist/{doctor-ZP4KADAD.js.map → doctor-5Y7QSXNQ.js.map} +0 -0
- /package/dist/{follow-up-tool-5AMZKVI4.js.map → follow-up-tool-53AYA2UQ.js.map} +0 -0
- /package/dist/{hub-BZF3ZYQ5.js.map → hub-YCOUZFNU.js.map} +0 -0
- /package/dist/{promote-IJANZNQK.js.map → promote-THTEHZHU.js.map} +0 -0
- /package/dist/{query-DC74NB3R.js.map → query-N7JBDLR7.js.map} +0 -0
- /package/dist/{query-settings-RXFOATOZ.js.map → query-settings-BJTVDDCH.js.map} +0 -0
- /package/dist/{registry-24IXRDWX.js.map → registry-LJ66OZYJ.js.map} +0 -0
- /package/dist/{request-planner-33CWWCJU.js.map → request-planner-PCELXLK7.js.map} +0 -0
- /package/dist/{review-candidates-ENWB6LHD.js.map → review-candidates-EMJUROJH.js.map} +0 -0
- /package/dist/{routing-AUFJ4MNP.js.map → routing-D2KNBEMG.js.map} +0 -0
- /package/dist/{schedule-tool-NAMOBMZE.js.map → schedule-tool-55MOWHKD.js.map} +0 -0
- /package/dist/{scheduler-KWSBBZKW.js.map → scheduler-73UEBYV4.js.map} +0 -0
- /package/dist/{seat-YGMLJ6KS.js.map → seat-UFAMWG7M.js.map} +0 -0
- /package/dist/{select-JJGBM6ZT.js.map → select-EPWELLAV.js.map} +0 -0
- /package/dist/{set-enabled-THE7QIGQ.js.map → set-enabled-LS65QZQS.js.map} +0 -0
- /package/dist/{tool-6LR6VORJ.js.map → tool-4S3YKLCN.js.map} +0 -0
- /package/dist/{tool-4ACTSFKC.js.map → tool-7LKYIA6D.js.map} +0 -0
- /package/dist/{wiki-YAW7UEOQ.js.map → wiki-LHT6X2JF.js.map} +0 -0
- /package/dist/{wiki-enrich-6ANFA2VB.js.map → wiki-enrich-CBBS3AC7.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as w}from"./chunk-
|
|
1
|
+
import{c as w}from"./chunk-7ICJCJ43.js";function T(t){let r=1779033703^t.length;for(let s=0;s<t.length;s++)r=Math.imul(r^t.charCodeAt(s),3432918353),r=r<<13|r>>>19;let o=r>>>0;return()=>{o=o+1831565813>>>0;let s=o;return s=Math.imul(s^s>>>15,s|1),s^=s+Math.imul(s^s>>>7,s|61),((s^s>>>14)>>>0)/4294967296}}function _(t,r,o){let s=T(o),i=[...t].sort((e,u)=>e.path.localeCompare(u.path));for(let e=i.length-1;e>0;e--){let u=Math.floor(s()*(e+1));[i[e],i[u]]=[i[u],i[e]]}return i.slice(0,Math.max(0,r)).sort((e,u)=>e.path.localeCompare(u.path))}var R=new Set("about after again also because been before being between could does doing during each from have having here into just more most only other over same should some such than that their them then there these they this those through under until very were what when where which while will with would your yours user assistant agent message entry please thanks".split(" "));function k(t){let r=new Set;for(let o of t.toLowerCase().matchAll(/[\p{L}\p{N}][\p{L}\p{N}_-]{3,}/gu))R.has(o[0])||r.add(o[0]);return r}function E(t,r){let o=k(t);if(o.size===0)return 1;let s=k(r),i=0;for(let e of o)s.has(e)&&i++;return i/o.size}var W=.15;function $(t){let r=w(t);return{commits:r.commits,urls:r.urls,numbers:r.numbers}}function j(t,r,o){return t.includes(r)||o.some(s=>s.startsWith(r)||r.startsWith(s))}var y=t=>t.toLowerCase().replace(/\/+$/,"");function N(t,r,o){let s=t.sources.map(a=>r.get(a)).filter(a=>!!a),i=t.sources.filter(a=>!r.has(a)),e=s.filter(a=>k(a.content).size>=5&&E(a.content,t.content)<W).map(a=>a.id),u=[...s.map(a=>`${a.date??""}
|
|
2
2
|
${a.content}`),t.previous??""].join(`
|
|
3
3
|
`),l=u.toLowerCase(),d=$(u),p=new Set(d.urls.map(y)),g=new Set(d.numbers),n=$(t.content),c=[];for(let a of n.commits)j(l,a,d.commits)||c.push(`commit ${a}`);for(let a of n.urls)!p.has(y(a))&&!l.includes(y(a))&&c.push(`link ${a}`);for(let a of n.numbers)/^\d{1,2}$/.test(a)||!g.has(a)&&!l.includes(a)&&c.push(`number ${a}`);let h=[];for(let a of s){let m=$(a.content);if(m.commits.length===0&&m.urls.length===0)continue;let v=o(a.id),S=(v.length>0?v:[t.content]).join(`
|
|
4
4
|
`).toLowerCase(),x=$(S);for(let b of m.commits)j(S,b,x.commits)||h.push({entry:a.id,fact:`commit ${b}`});for(let b of m.urls)S.includes(y(b))||h.push({entry:a.id,fact:`link ${b}`})}return{path:t.path,title:t.title,type:t.type,sources:t.sources.length,missingSources:i,weakSources:e,ungrounded:c,lost:h}}function U(t,r){let o=r.toLowerCase(),s=w(r).commits,i=[];for(let e of t){let u=w(e.content),l=[...u.commits.filter(d=>!j(o,d,s)).map(d=>`commit ${d}`),...u.urls.filter(d=>!o.includes(y(d))).map(d=>`link ${d}`)];l.length>0&&i.push({entry:e.id,facts:l})}return i}var P=new Set("the and for with from into of on in at to by an a".split(" "));function L(t){return new Set((t||"").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(r=>(r.length>1||/\d/.test(r))&&!P.has(r)&&!R.has(r)))}function M(t,r){if(t.size===0||r.size===0)return 0;let o=0;for(let s of t)r.has(s)&&o++;return o/(t.size+r.size-o)}function D(t,r,o={}){let s=o.titleMin??.75,i=o.sourcesMin??.5,e=t.map(l=>({...l,tt:L(l.title),ss:new Set(l.sources??[])})),u=[];for(let l=0;l<e.length;l++)for(let d=l+1;d<e.length;d++){let p=e[l],g=e[d];if(r&&!r.has(p.path)&&!r.has(g.path))continue;let n=(p.type??"")===(g.type??"")?M(p.tt,g.tt):0;if(n>=s){u.push({a:p.path,b:g.path,reason:"title",score:n});continue}if(p.ss.size>=2&&g.ss.size>=2){let c=M(p.ss,g.ss);c>=i&&u.push({a:p.path,b:g.path,reason:"sources",score:c})}}return u.sort((l,d)=>d.score-l.score||l.a.localeCompare(d.a))}var A=4e3;function J(t,r){let o=r.map(i=>{let e=i.content.length>A?`${i.content.slice(0,A)}
|
|
@@ -33,4 +33,4 @@ Reply with JSON only, no fencing:
|
|
|
33
33
|
{"claims": 0, "supported": 0, "unsupported": [], "contradicted": [], "off_subject": [], "missing": [], "verdict": "good"}`}function z(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t,o=l=>Array.isArray(l)?l.map(d=>String(d)):[],s=l=>typeof l=="number"&&Number.isFinite(l)&&l>=0?Math.round(l):NaN,i=s(r.claims);if(Number.isNaN(i))return null;let e=Math.min(i,Number.isNaN(s(r.supported))?i-o(r.unsupported).length:s(r.supported)),u=r.verdict==="good"||r.verdict==="minor"||r.verdict==="major"?r.verdict:null;return u?{claims:i,supported:Math.max(0,e),unsupported:o(r.unsupported),contradicted:o(r.contradicted),offSubject:o(r.off_subject??r.offSubject),missing:o(r.missing),verdict:u}:null}function I(t,r,o,s=[],i=5,e){let u={};for(let n of t)u[n.type??"untyped"]=(u[n.type??"untyped"]??0)+1;let l=new Set,d=new Set;for(let n of t)for(let c of n.lost)l.add(c.entry),d.add(`${c.entry}|${c.fact}`);let p=new Set(r.flatMap(n=>[n.a,n.b]).filter(n=>t.some(c=>c.path===n))),g={sample:{articles:t.length,seed:o.seed,since:o.since,byType:u},citations:{withSources:t.filter(n=>n.sources>0).length,missingSources:t.reduce((n,c)=>n+c.missingSources.length,0),weakSources:t.reduce((n,c)=>n+c.weakSources.length,0),articlesWithWeak:t.filter(n=>n.weakSources.length>0).length},grounding:{articlesWithUngrounded:t.filter(n=>n.ungrounded.length>0).length,ungroundedFacts:t.reduce((n,c)=>n+c.ungrounded.length,0)},lost:{entriesWithLostFacts:l.size,lostFacts:d.size},duplicates:{pairs:r.length,articlesInPair:p.size},...e?{uncited:{entries:e.entries,withLostFacts:e.lost.length}}:{},examples:{ungrounded:t.filter(n=>n.ungrounded.length>0).slice(0,i).map(n=>({path:n.path,facts:n.ungrounded.slice(0,6)})),lost:t.flatMap(n=>n.lost.map(c=>({path:n.path,...c}))).slice(0,i),weak:t.filter(n=>n.weakSources.length>0).slice(0,i).map(n=>({path:n.path,entries:n.weakSources})),duplicates:r.slice(0,i),uncited:(e?.lost??[]).slice(0,i).map(n=>({entry:n.entry,facts:n.facts.slice(0,4)})),judged:s.filter(n=>n.verdict.verdict!=="good").slice(0,i).map(n=>({path:n.path,verdict:n.verdict.verdict,unsupported:n.verdict.unsupported.slice(0,4),contradicted:n.verdict.contradicted.slice(0,4),offSubject:n.verdict.offSubject,missing:n.verdict.missing.slice(0,4)}))}};if(s.length>0){let n=s.map(a=>a.verdict),c=n.reduce((a,m)=>a+m.claims,0),h=n.reduce((a,m)=>a+m.supported,0);g.judge={judged:n.length,claims:c,supported:h,supportRate:c>0?h/c:1,unsupported:n.reduce((a,m)=>a+m.unsupported.length,0),contradicted:n.reduce((a,m)=>a+m.contradicted.length,0),articlesWithWrongMerge:n.filter(a=>a.offSubject.length>0).length,missingFacts:n.reduce((a,m)=>a+m.missing.length,0),verdicts:{good:n.filter(a=>a.verdict==="good").length,minor:n.filter(a=>a.verdict==="minor").length,major:n.filter(a=>a.verdict==="major").length}}}return g}var f=(t,r)=>r>0?`${Math.round(t/r*100)}%`:"\u2013";function O(t){let r=t.sample.articles,o=["# Wiki absorb scorecard","",`Sample: ${r} articles (seed \`${t.sample.seed}\`${t.sample.since?`, changed since ${t.sample.since}`:""}). Types: ${Object.entries(t.sample.byType).map(([e,u])=>`${e} ${u}`).join(", ")||"\u2013"}.`,"","| Check | Result | Lower is better? |","|---|---|---|",`| Articles citing at least one entry | ${t.citations.withSources}/${r} (${f(t.citations.withSources,r)}) | no |`,`| Cited ids with no entry | ${t.citations.missingSources} | yes |`,`| Articles with a weak citation (entry shares <${Math.round(W*100)}% of its words) | ${t.citations.articlesWithWeak}/${r} (${f(t.citations.articlesWithWeak,r)}) | yes |`,`| Articles with an ungrounded commit, link or number | ${t.grounding.articlesWithUngrounded}/${r} (${f(t.grounding.articlesWithUngrounded,r)}) | yes |`,`| Ungrounded facts | ${t.grounding.ungroundedFacts} | yes |`,`| Commits or links lost from cited entries | ${t.lost.lostFacts} across ${t.lost.entriesWithLostFacts} entries | yes |`,`| Sampled articles in a likely duplicate pair | ${t.duplicates.articlesInPair}/${r} (${f(t.duplicates.articlesInPair,r)}) | yes |`];if(t.uncited&&o.push(`| Entries read in the window but cited by no article | ${t.uncited.entries} | \u2013 |`,`| \u2026of which carry a commit or link no article has | ${t.uncited.withLostFacts} | yes |`),t.judge){let e=t.judge;o.push(`| Judge: claims supported by the cited entries | ${e.supported}/${e.claims} (${f(e.supported,e.claims)}) | no |`,`| Judge: unsupported / contradicted claims | ${e.unsupported} / ${e.contradicted} | yes |`,`| Judge: articles with an off-subject source (wrong merge) | ${e.articlesWithWrongMerge}/${e.judged} (${f(e.articlesWithWrongMerge,e.judged)}) | yes |`,`| Judge: facts missing from the article | ${e.missingFacts} | yes |`,`| Judge verdicts good / minor / major | ${e.verdicts.good} / ${e.verdicts.minor} / ${e.verdicts.major} | \u2013 |`)}let s=t.examples,i=(e,u)=>{u.length!==0&&o.push("",`## ${e}`,"",...u)};return i("Examples: ungrounded facts",s.ungrounded.map(e=>`- \`${e.path}\`: ${e.facts.join("; ")}`)),i("Examples: lost facts",s.lost.map(e=>`- \`${e.path}\` \u2190 entry \`${e.entry}\`: ${e.fact}`)),i("Examples: weak citations",s.weak.map(e=>`- \`${e.path}\`: ${e.entries.map(u=>`\`${u}\``).join(", ")}`)),i("Examples: uncited entries with facts no article has",s.uncited.map(e=>`- \`${e.entry}\`: ${e.facts.join("; ")}`)),i("Examples: likely duplicates",s.duplicates.map(e=>`- \`${e.a}\` \u2194 \`${e.b}\` (${e.reason}, ${e.score.toFixed(2)})`)),i("Examples: judge findings",s.judged.map(e=>{let u=[e.unsupported.length?`unsupported: ${e.unsupported.join(" | ")}`:"",e.contradicted.length?`contradicted: ${e.contradicted.join(" | ")}`:"",e.offSubject.length?`off-subject: ${e.offSubject.join(", ")}`:"",e.missing.length?`missing: ${e.missing.join(" | ")}`:""].filter(Boolean);return`- \`${e.path}\` (${e.verdict}): ${u.join("; ")}`})),o.push("","## Method","","- The sample is drawn with a seeded shuffle from the articles changed in the window, so the same seed and window give the same articles.","- Ungrounded: a commit hash, link or number (three digits or more, or a date) in the article that no cited entry and no earlier version of the article contains.","- Lost: a commit hash or link in a cited entry that no article citing that entry contains.","- Uncited: entries the absorb ledger marks as read in the window that no article cites; those carrying a commit or link that no article on the node has are counted as lost, since absorb will not offer them again.","- Weak citation: a cited entry sharing fewer than 15% of its distinctive words with the article.","- Duplicate: two articles of the same type whose titles share at least 75% of their words, or which share at least half their sources.","- Judge (optional): one model call per article reads the article and its cited entries and lists unsupported, contradicted, off-subject and missing items."),o.join(`
|
|
34
34
|
`)+`
|
|
35
35
|
`}function V(t){if(!t||typeof t!="object")return{};let r=t,o=r.usage??{},s=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0;return{costUsd:s(r.total_cost_usd)??s(r.cost_usd),apiMs:s(r.duration_api_ms),inputTokens:s(o.input_tokens),outputTokens:s(o.output_tokens),cacheReadTokens:s(o.cache_read_input_tokens),cacheWriteTokens:s(o.cache_creation_input_tokens)}}function C(t,r){return t.length===0?0:t[Math.min(t.length-1,Math.floor(r*t.length))]}function Y(t){let r=new Map,o=i=>{let e=i||"(none)",u=r.get(e);return u||r.set(e,u={calls:[],runs:[]}),u};for(let i of t)i.kind==="call"?o(i.label).calls.push(i):i.kind==="run"&&o(i.label).runs.push(i);let s=[];for(let[i,{calls:e,runs:u}]of r){if(e.length===0)continue;let l=e.map(n=>n.wallMs).sort((n,c)=>n-c),d;if(u.length>0)d=u.reduce((n,c)=>n+(Date.parse(c.endedAt)-Date.parse(c.startedAt)),0);else{let n=e.map(h=>Date.parse(h.at)-h.wallMs),c=e.map(h=>Date.parse(h.at));d=Math.max(...c)-Math.min(...n)}let p=e.reduce((n,c)=>n+c.entries,0),g=e.reduce((n,c)=>n+(c.costUsd??0),0);s.push({label:i,calls:e.length,failed:e.filter(n=>n.failed).length,entries:p,articles:e.reduce((n,c)=>n+c.articles,0),refused:e.reduce((n,c)=>n+c.refused,0),heldCited:e.reduce((n,c)=>n+(c.heldCited??0),0),wallMs:d,callMsP50:C(l,.5),callMsP95:C(l,.95),prepMs:e.reduce((n,c)=>n+(c.prepMs??0),0),costUsd:g,costPerEntry:p>0?g/p:0,entriesPerMinute:d>0?p/d*6e4:0,promptChars:e.reduce((n,c)=>n+c.promptChars,0)})}return s.sort((i,e)=>i.label.localeCompare(e.label))}export{T as a,_ as b,k as c,E as d,W as e,N as f,U as g,D as h,A as i,J as j,z as k,I as l,O as m,V as n,Y as o};
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
36
|
+
//# sourceMappingURL=chunk-JLEVL66V.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as i}from"fs";import{homedir as c}from"os";import{join as u}from"path";var l=u(c(),"Library","DoNotDisturb","DB","Assertions.json"),d=u(c(),".agentx","focus.json");function S(e=l,t=d){let r=f(t);return r.active?r:m(e)}function f(e=d){try{if(JSON.parse(i(e,"utf-8"))?.active===!0)return{active:!0,mode:"widget",reason:"holding \u2014 switched on from the widget"}}catch{}return{active:!1,mode:null,reason:"widget hold is off"}}function m(e=l){let t;try{t=i(e,"utf-8")}catch(s){return s?.code==="EPERM"||s?.code==="EACCES"?{active:!1,mode:null,reason:"Focus database not readable \u2014 grant Full Disk Access to the app running agentx"}:{active:!1,mode:null,reason:"no Focus database on this machine"}}let r;try{r=JSON.parse(t)}catch{return{active:!1,mode:null,reason:"Focus database was not readable JSON"}}let n=(Array.isArray(r?.data)?r.data[0]:null)?.storeAssertionRecords;if(!Array.isArray(n)||n.length===0)return{active:!1,mode:null,reason:"no active Focus assertion"};let a=n[0],o=a?.assertionDetails?.assertionDetailsModeIdentifier??a?.assertionDetails?.assertionDetailsModeID??null;return{active:!0,mode:typeof o=="string"?o:null,reason:`Focus assertion present${o?` (${o})`:""}`}}function y(e){return e.active?e.mode==="widget"?"holding (widget)":e.mode==="call"?"in a call":e.mode?`in ${(e.mode.split(".").pop()??e.mode).replace(/-/g," ")}`:"in Focus":"not in Focus"}export{S as a,y as
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{readFileSync as i}from"fs";import{homedir as c}from"os";import{join as u}from"path";var l=u(c(),"Library","DoNotDisturb","DB","Assertions.json"),d=u(c(),".agentx","focus.json");function S(e=l,t=d){let r=f(t);return r.active?r:m(e)}function f(e=d){try{if(JSON.parse(i(e,"utf-8"))?.active===!0)return{active:!0,mode:"widget",reason:"holding \u2014 switched on from the widget"}}catch{}return{active:!1,mode:null,reason:"widget hold is off"}}function m(e=l){let t;try{t=i(e,"utf-8")}catch(s){return s?.code==="EPERM"||s?.code==="EACCES"?{active:!1,mode:null,reason:"Focus database not readable \u2014 grant Full Disk Access to the app running agentx"}:{active:!1,mode:null,reason:"no Focus database on this machine"}}let r;try{r=JSON.parse(t)}catch{return{active:!1,mode:null,reason:"Focus database was not readable JSON"}}let n=(Array.isArray(r?.data)?r.data[0]:null)?.storeAssertionRecords;if(!Array.isArray(n)||n.length===0)return{active:!1,mode:null,reason:"no active Focus assertion"};let a=n[0],o=a?.assertionDetails?.assertionDetailsModeIdentifier??a?.assertionDetails?.assertionDetailsModeID??null;return{active:!0,mode:typeof o=="string"?o:null,reason:`Focus assertion present${o?` (${o})`:""}`}}function y(e){return e.active?e.mode==="widget"?"holding (widget)":e.mode==="call"?"in a call":e.mode?`in ${(e.mode.split(".").pop()??e.mode).replace(/-/g," ")}`:"in Focus":"not in Focus"}export{S as a,m as b,y as c};
|
|
2
|
+
//# sourceMappingURL=chunk-KP7KDLZ2.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as St,c as At}from"./chunk-5TTHN7DP.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-
|
|
1
|
+
import{c as bt}from"./chunk-SZDACK6O.js";import{b as xe}from"./chunk-AFRHKA7B.js";import{b as St,c as At}from"./chunk-5TTHN7DP.js";import{b as ht,e as wt,f as yt,i as It,k as vt,l as $t,q as Rt}from"./chunk-P6PFTNN4.js";import{b as ft,d as gt,e as mt}from"./chunk-PE5V2LI7.js";import{e as ut,g as ct,h as pt,i as Re}from"./chunk-GQ76J72O.js";import{a as kt}from"./chunk-GV7S5BAX.js";import{y as at,z as Bn}from"./chunk-5TGY4RIQ.js";import{b as st,f as Kn}from"./chunk-72SZI2UW.js";import{a as dt,b as $e,c as Se,d as lt,e as Ae}from"./chunk-QD6IICK7.js";import{c as ot,d as it}from"./chunk-QOYAX2FT.js";import{f as ve,n as Hn}from"./chunk-UIBUZ2N3.js";import{existsSync as qn,mkdirSync as xt,readFileSync as zn,writeFileSync as Jn,renameSync as Yn}from"fs";import{resolve as Pt,dirname as Gn}from"path";var Tt=class{filePath;log;constructor(e={}){let t=e.baseDir??Pt(process.cwd(),".agentx");this.filePath=Pt(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),xt(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!qn(this.filePath))return{version:1,overrides:{}};try{let e=zn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){xt(Gn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;Jn(t,JSON.stringify(e,null,2)),Yn(t,this.filePath)}get(e,t,r){let s=this.load().overrides[this.key(e,t,r)];if(s&&!(s.expiresAt&&Date.parse(s.expiresAt)<Date.now()))return s}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),s=this.key(e,t,r);return s in o.overrides?(delete o.overrides[s],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),s=o.overrides[this.key(e,t,r)];if(!s||!s.summary||s.summaryConsumedAt)return;let a=s.summary;return s.summaryConsumedAt=new Date().toISOString(),this.save(o),a}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{readFileSync as Et,writeFileSync as Pe,appendFileSync as Xn,mkdirSync as er,existsSync as Mt,statSync as tr}from"fs";import{resolve as ne}from"path";var Wt="[Agent Memory \u2014 persistent facts from past conversations]",Vn=2400;function Nt(n,e){return n?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function Qn(n,e=Date.now()){let t=gt(n,e),r=n.undated?"UNVERIFIED (never checked) ":Nt(t,ut(n.verifiedAt,e));return{line:`- [wiki ${n.id}] ${r}${n.subject} \xB7 ${n.attribute}: ${n.value} (${n.source}, checked ${n.verifiedAt.slice(0,10)} by ${n.verifiedBy})`,unverified:t}}function Zn(n,e){let r=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,o=pt(n,e);return{line:`- [${n.category}] ${Nt(o,ct(n,e))}${n.content} (${r}, ${n.source.date})`,unverified:o}}function Dt(n,e=[],t=Date.now()){let r=[],o=new Set,s=Wt.length,a=!1;for(let i of n){let d=e.length>0?mt(i.content,e):null,l,p,c=d&&Date.parse(i.createdAt)>Date.parse(d.verifiedAt)&&!i.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!c){if(o.has(d.id))continue;o.add(d.id),l=Qn(d,t),p=d.id}else l=Zn(i,t),d&&(l.line+=` [differs from wiki ${d.id}]`);let f=l.unverified&&!a?Re.length:0;if(s+f+l.line.length>Vn)break;r.push({fact:i,...l,...p?{wikiRef:p}:{}}),s+=f+l.line.length,f&&(a=!0)}return r}function Ot(n){if(n.length===0)return"";let e=n.some(t=>t.unverified)?[Re]:[];return[Wt,...e,...n.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var Ft=200,nr=7,jt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=ne(e,".agentx/memory"),this.ledger=new ft(ne(e,".agentx/wiki")),Mt(this.memoryDir)||er(this.memoryDir,{recursive:!0})}filePath(e){return ne(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||$e(t.content))return!1;let r=t.source.trust??dt(t.source.channel),o=t.review??lt(r),s={...t,source:{...t.source,trust:r},...o?{review:o}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Xn(this.filePath(e),JSON.stringify(s)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!Mt(t))return[];try{let{mtimeMs:r,size:o}=tr(t),s=this.parsedCache.get(t);if(s&&s.mtimeMs===r&&s.size===o)return s.facts.slice();let i=Et(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:r,size:o,facts:i}),i.slice()}catch{return[]}}findRelevant(e,t,r=8){let o=this.getAll(t).filter(Ae);if(o.length===0)return[];let s=o.map(g=>`${g.keywords.join(" ")} ${g.content}`),a=ne(this.memoryDir,`${t}_bm25_cache.json`),i=it(s,a),d=ot(e,i),l=new Map(d.map(g=>[g.docIndex,g.score])),c=o.map((g,m)=>{let y=l.get(m)??0;return g.category==="commitment"&&(y+=1),{memory:g,score:y}}).filter(g=>g.score>0);if(c.length===0)return o.slice(-r);let f=c.sort((g,m)=>m.score-g.score).slice(0,r).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return Ot(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return Dt(e,t)}recordAccess(e,t){if(t.length===0)return;let r=this.getAll(e),o=new Set(t),s=!1;for(let a of r)if(o.has(a.id)){a.accessCount=(a.accessCount||0)+1,a.lastAccessed=new Date().toISOString();let i=a.intervalDays||1;a.intervalDays=Math.min(i*2,30),a.nextReview=new Date(Date.now()+a.intervalDays*864e5).toISOString(),s=!0}s&&Pe(this.filePath(e),r.map(a=>JSON.stringify(a)).join(`
|
|
@@ -38,4 +38,4 @@ ${n.text}`}async function me(n,e){let t=n.channels[e.channel],r={channel:e.chann
|
|
|
38
38
|
`).filter(Boolean),o=[];for(let s=r.length-1;s>=0&&o.length<t;s--)try{let a=JSON.parse(r[s]);(!e||a.person===e)&&o.push(a)}catch{}return o}load(){if(Xe(this.file))try{let e=JSON.parse(et(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Sn(xn(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${Tn(4).toString("hex")}.tmp`;Rn(t,JSON.stringify(e,null,2)+`
|
|
39
39
|
`,{encoding:"utf-8",mode:384}),An(t,this.file)}};import{extname as li}from"path";var Nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,Dn=/<agentx-artifact>[\s\S]*$/i;function ld(n,e=1/0,t=!1){let r=[],o=String(n??"");if(!/<agentx-artifact>/i.test(o))return{text:o,artifacts:r};let s=o.replace(Nn,(a,i)=>{try{let d=JSON.parse(i.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&r.length<e){let l=d.mime,p=l.startsWith("image/")?"image":l==="application/pdf"?"pdf":l.startsWith("text/")?"text":"file";r.push({type:p,filename:d.filename,mime:l})}}catch{}return""});return{text:(t?s.replace(Dn,""):s).trim(),artifacts:r}}function ud(n,e=!1){let t=String(n??""),r=t;if(/<agentx-artifact>/i.test(t)){let o=t.replace(Nn,(s,a)=>{try{let i=JSON.parse(a.trim());return i&&typeof i.filename=="string"?i.filename:""}catch{return""}});r=(e?o.replace(Dn,""):o).trim()}return r.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(o,s,a)=>s===void 0||a===void 0?o:`[${s||a}](${a})`)}var ui={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},cd={bytes:20*1024*1024,perMessage:20,pathChars:512};function pd(n){return ui[li(n).toLowerCase()]??null}var ci=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
40
40
|
`);function fd(n,e,t){return n==="app"&&e&&t!==!1?ci:void 0}import{lstatSync as nt,mkdirSync as pi,readdirSync as fi,realpathSync as tt,unlinkSync as gi}from"fs";import{join as be,resolve as On}from"path";var En=".agentx/outbox",mi=7*24*60*60*1e3;function hi(n,e){try{let t=tt(On(e,n)),r=be(t,En);return tt(r)===r&&nt(r).isDirectory()?r:null}catch{return null}}function wd(n,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let o=tt(On(t,n));nt(be(o,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||pi(be(o,En),{recursive:!0})}catch{return 0}let r=hi(n,t);return r?Mn(r,(e.now??Date.now())-(e.maxAgeMs??mi)):0}function Mn(n,e){let t=0;for(let r of fi(n)){let o=be(n,r);try{let s=nt(o);s.isDirectory()?t+=Mn(o,e):Math.max(s.mtimeMs,s.ctimeMs)<e&&(gi(o),t++)}catch{}}return t}export{Tt as a,jt as b,Ct as c,Di as d,ir as e,Oi as f,T as g,z as h,S as i,oe as j,Ir as k,Oe as l,F as m,Fe as n,Ce as o,Ge as p,To as q,Mo as r,Qe as s,_r as t,Go as u,Na as v,Da as w,Oa as x,Ea as y,Ma as z,Vo as A,Qo as B,Fa as C,ja as D,Ca as E,_a as F,Ha as G,Ka as H,Ba as I,qa as J,za as K,Ja as L,Ya as M,Ga as N,Va as O,Qa as P,Za as Q,ri as R,Xa as S,ed as T,td as U,nd as V,Wn as W,ld as X,ud as Y,cd as Z,pd as _,fd as $,En as aa,wd as ba};
|
|
41
|
-
//# sourceMappingURL=chunk-
|
|
41
|
+
//# sourceMappingURL=chunk-KW6SHOAN.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-LJ66OZYJ.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-MXDTLR45.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-
|
|
1
|
+
import{b as Y,c as I,d as O}from"./chunk-AQASR6KR.js";import{q as _,r as W}from"./chunk-2AXFYDWF.js";import{b as F}from"./chunk-MEFPXHQJ.js";import{a as E}from"./chunk-UVF3K5YS.js";import{b as L}from"./chunk-KEXBEUSU.js";import{createHash as ee}from"crypto";import{existsSync as H,readdirSync as te,readFileSync as re,writeFileSync as ne}from"fs";import{resolve as P}from"path";function be(n,r,s,t,o,i,c="",p="",m=""){return Z(r,s,t,o,i,c,p,m)}function Z(n,r,s,t,o,i="",c="",p=""){let m=r?`
|
|
2
2
|
## Worldview
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -249,4 +249,4 @@ ${u}`}var x="memory-promoter",oe=["project","reference","feedback"],K="_memory-p
|
|
|
249
249
|
Re-emit the FULL corrected JSON object \u2014 same structure, fixed issues, valid JSON only.`:n,y=await t(`${a}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r.viaAgent,message:h,freshSession:s===null,context:{channel:"api",chatId:r.chatId??"memory-promote"}}),signal:i.signal});if(!y.ok){let f=await y.text().catch(()=>"");throw new Error(`agent /task ${y.status}: ${f.slice(0,500)}`)}let w=await y.json();if(w.error)throw new Error(`agent reported error: ${w.error}`);let b=String(w.content??"").trim();if(!b)throw new Error("agent returned empty content");return b}if(!r.model)throw new Error("callPromotionLlm: viaAgent or model is required");let p=process.env.ANTHROPIC_API_KEY;if(!p)throw new Error("ANTHROPIC_API_KEY not set; use --via <agentId> instead");let m=[{role:"user",content:n}];s&&(m.push({role:"assistant",content:"(previous attempt; will retry with corrections)"}),m.push({role:"user",content:`Your previous response failed validation: ${s}
|
|
250
250
|
Re-emit the FULL corrected JSON object.`}));let u=await t(me,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":p,"anthropic-version":ge},body:JSON.stringify({model:r.model,max_tokens:8e3,messages:m}),signal:i.signal});if(!u.ok){let a=await u.text().catch(()=>"");throw new Error(`anthropic API ${u.status}: ${a.slice(0,500)}`)}let d=await u.json(),e=(Array.isArray(d.content)?d.content:[]).filter(a=>a?.type==="text").map(a=>a.text).join(`
|
|
251
251
|
`).trim();if(!e)throw new Error("anthropic API returned no text content");return e}finally{clearTimeout(c)}}async function Se(n={}){let r=n.wikiDir??P(process.cwd(),".agentx","wiki"),s=n.memoryRoot??P(process.cwd(),".agentx"),t=n.log??(()=>{}),o=n.now??Date.now(),i={candidates:[],clusters:[],proposed:[],skipped:[],gaps:[],warnings:[],errors:[],dryRun:!n.commit},c=new E(r,(...l)=>t(l.map(String).join(" "))),p=c.rebuildIndex(),m=z(r),u=[...ce(s),...n.extraCandidates??[]];if(i.candidates=de(u,p,m,{types:n.types,sinceMs:n.sinceMs,agentFilter:n.agentFilter,now:o,max:n.max}),i.candidates.length===0)return t("no unpromoted memories in window"),i;if(i.clusters=le(i.candidates),i.dryRun)return i;let d=p.articles.map(l=>({title:l.title,path:l.path,type:l.type})),g=c.getWorldview()??"",e=n.budgetTokens??ue,a=i.clusters,h=D(x,a,d,g);for(;R(h)>e&&a.length>1;)a=a.slice(0,-1),h=D(x,a,d,g);if(R(h)>e)return i.errors.push(`judge prompt (~${R(h)} tokens) exceeds the ${e}-token budget even with one cluster`),i;a.length<i.clusters.length&&i.warnings.push(`token budget: judged ${a.length} of ${i.clusters.length} clusters; the rest wait for the next run`);let y=a.flatMap(l=>l.candidates),w=new Set(y.map(l=>l.stamp)),b=n.chatId??`memory-promote-${new Date(o).toISOString().slice(0,10)}`,f=B(await G(h,{...n,chatId:b}),w);if("error"in f&&(t(`parse failed (${f.error}) \u2014 retrying with feedback`),f=B(await G(h,{...n,chatId:b},f.error),w)),"error"in f)return i.errors.push(`LLM response unusable after retry: ${f.error}`),i;i.warnings.push(...f.warnings),i.gaps=f.gaps;let v=new Date(o).toISOString(),k=[],T=new Map(y.map(l=>[l.stamp,l]));for(let l of f.articles){let A=c.readArticle(l.path);if(A&&!c.canWrite(A.meta,x)){i.errors.push(`write denied for "${l.path}" (owned by ${A.meta.owner??"?"})`);continue}let M=fe(l.promotedFrom,T),S={id:Y(o,l.path),createdAt:v,status:"pending",article:l,evidence:M,...A?{replaces:{lastUpdated:A.meta.lastUpdated,contentHash:V(A.content)}}:{}};I(r,S),i.proposed.push({id:S.id,path:l.path,title:l.title,type:l.type,stamps:l.promotedFrom,agents:M.agents,occurrences:M.occurrences});for(let X of l.promotedFrom)k.push({stamp:X,decision:"proposed",article:l.path,proposal:S.id,at:v})}for(let l of f.skipped)k.push({stamp:l.stamp,decision:"skipped",reason:l.reason,at:v}),i.skipped.push(l);return k.length&&C(r,k),i}var ue=6e4;function R(n){return Math.ceil(n.length/4)}function V(n){return ee("sha256").update(n).digest("hex").slice(0,16)}var he=600;function ye(n){return n.startsWith("review:")?"review":n.startsWith(j)?"failure":"memory"}function fe(n,r){let s=[];for(let t of n){let o=r.get(t);o&&s.push({stamp:t,kind:ye(t),agentId:o.agentId,type:o.memory.type,name:o.memory.name,description:o.memory.description,...o.occurrences?{occurrences:o.occurrences}:{},...o.sessions?.length?{sessions:o.sessions}:{},...o.tasks?.length?{tasks:o.tasks}:{},...o.failure?{failure:o.failure}:{},...o.memory.author?{author:o.memory.author}:{},...o.memory.taskId?{taskId:o.memory.taskId}:{},updatedAt:o.memory.updatedAt,excerpt:o.memory.body.slice(0,he)})}return{agents:[...new Set(s.map(t=>t.agentId))].sort(),occurrences:Math.max(1,...s.map(t=>t.occurrences??1)),sources:s}}function Ee(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=s.log??(()=>{}),i=new E(n,(...a)=>o(a.map(String).join(" "))),{article:c}=t,p=i.readArticle(c.path);if(!s.force){if(p&&!t.replaces)return{ok:!1,error:`"${c.path}" was created after this proposal; review it, then approve with --force`};if(p&&t.replaces&&V(p.content)!==t.replaces.contentHash)return{ok:!1,error:`"${c.path}" changed since this proposal; review it, then approve with --force`}}let m=s.now??Date.now(),u=new Date(m).toISOString().slice(0,10);if(!i.writeArticle(c.path,{title:c.title,type:L(c.type)?c.type:void 0,related:c.related,tags:c.tags,owner:x,access:"public",created:p?.meta.created??u,lastUpdated:u,sources:ae(p?.meta.sources,c.promotedFrom)},c.content,x))return{ok:!1,error:`write denied for "${c.path}" (owned by ${p?.meta.owner??"?"})`};let g=new Date(m).toISOString();C(n,c.promotedFrom.map(a=>({stamp:a,decision:"promoted",article:c.path,proposal:r,at:g}))),i.rebuildIndex();let e={...t,status:"approved",decidedBy:s.by??"operator",decidedAt:g};return I(n,e),{ok:!0,proposal:e}}function Oe(n,r,s={}){let t=O(n,r);if(!t)return{ok:!1,error:`no proposal "${r}"`};if(t.status!=="pending")return{ok:!1,error:`proposal "${r}" is already ${t.status}`};let o=new Date(s.now??Date.now()).toISOString();C(n,t.article.promotedFrom.map(c=>({stamp:c,decision:"rejected",article:t.article.path,proposal:r,reason:s.reason,at:o})));let i={...t,status:"rejected",decidedBy:s.by??"operator",decidedAt:o,...s.reason?{reason:s.reason}:{}};return I(n,i),{ok:!0,proposal:i}}export{be as a,x as b,oe as c,K as d,q as e,ie as f,$ as g,ae as h,ce as i,z as j,C as k,le as l,B as m,de as n,G as o,Se as p,R as q,ye as r,fe as s,Ee as t,Oe as u};
|
|
252
|
-
//# sourceMappingURL=chunk-
|
|
252
|
+
//# sourceMappingURL=chunk-P5BFFU4Y.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as S,c as O}from"./chunk-
|
|
1
|
+
import{b as S,c as O}from"./chunk-E7YHXMJG.js";import{h as B,j as J}from"./chunk-3UOTLMXD.js";import{a as I,b as P}from"./chunk-FCPTN6NF.js";import{a as X,b as le}from"./chunk-7I7IEX4S.js";import{d as F}from"./chunk-QIJLFPWE.js";import{execFile as ke}from"child_process";import{writeFileSync as ie,mkdirSync as x,existsSync as b,readFileSync as Ce}from"fs";import{resolve as v}from"path";var ge=["off","shadow","authoritative"],me={telegram:"INTENT_LEDGER_MODE_TELEGRAM",slack:"INTENT_LEDGER_MODE_SLACK",whatsapp:"INTENT_LEDGER_MODE_WHATSAPP",discord:"INTENT_LEDGER_MODE_DISCORD",gitlab:"INTENT_LEDGER_MODE_GITLAB",github:"INTENT_LEDGER_MODE_GITHUB",workflow:"INTENT_LEDGER_MODE_WORKFLOW",cron:"INTENT_LEDGER_MODE_CRON",mesh:"INTENT_LEDGER_MODE_MESH"},he="INTENT_LEDGER_MODE";function G(i,e=process.env){let t=U(e[me[i]]);if(t)return t;let n=U(e[he]);return n||"off"}function U(i){if(typeof i!="string")return null;let e=i.trim().toLowerCase();return ge.includes(e)?e:null}P();import fe from"better-sqlite3";import{existsSync as Ge,mkdirSync as pe}from"fs";import{dirname as Ee,resolve as ve}from"path";var T=class{db;path;constructor(e={}){this.path=ve(process.cwd(),e.path??".agentx/intent/ledger.sqlite"),pe(Ee(this.path),{recursive:!0}),this.db=new fe(this.path),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),Ie(this.db)}close(){this.db.close()}schemaVersion(){return this.db.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0}recordEvent(e){if(e.sourceEventId!==null){let n=this.findEventBySourceId(e.source,e.sourceEventId);if(n)return n}let t={id:e.id??I(e.ts),ts:e.ts,source:e.source,sourceEventId:e.sourceEventId,project:e.project,subject:e.subject,intent:e.intent,rawJson:e.rawJson};return this.db.prepare(`INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)
|
|
2
2
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.id,t.ts,t.source,t.sourceEventId,t.project,t.subject,t.intent,t.rawJson),t}findEventBySourceId(e,t){let n=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
3
3
|
FROM intent_events WHERE source = ? AND source_event_id = ?`).get(e,t);return n?Y(n):null}getEventById(e){let t=this.db.prepare(`SELECT id, ts, source, source_event_id, project, subject, intent, raw_json
|
|
4
4
|
FROM intent_events WHERE id = ?`).get(e);return t?Y(t):null}recordDecision(e){this.db.prepare(`INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)
|
|
@@ -125,4 +125,4 @@ ${oe(a.block,r.prompt)}`,r.maxOutputTokens),agentId:r.agent,autonomy:r.autonomy,
|
|
|
125
125
|
`);return t.length<=e?t.join(`
|
|
126
126
|
`):t.slice(-e).join(`
|
|
127
127
|
`)}function Pe(i,e,t){return new Promise((n,r)=>{ke("/bin/sh",["-c",i],{timeout:e,maxBuffer:8*1024*1024,...t?{env:t}:{}},(s,o,a)=>{if(s&&s.killed){r(new Error(`command timed out after ${Math.round(e/1e3)}s`));return}n({stdout:String(o??""),stderr:String(a??""),code:s?typeof s.code=="number"?s.code:1:0})})})}export{T as a,V as b,at as c,Le as d,ct as e,dt as f,L as g,ee as h,G as i,ze as j,z as k,Q as l,gt as m,Me as n,ae as o,ce as p,de as q,C as r,M as s};
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
128
|
+
//# sourceMappingURL=chunk-P6PFTNN4.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-UVF3K5YS.js";import{resolve as n}from"path";import{existsSync as c,readdirSync as u,mkdirSync as l,readFileSync as p,writeFileSync as f,renameSync as S}from"fs";var m=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=n(process.cwd(),".agentx/wiki"),r=console.error.bind(console,"[wiki-hub]"),t="graph"){this.baseDir=e,this.agentsDir=n(e,"agents"),this.mode=t,this.log=r,l(this.agentsDir,{recursive:!0}),this.sharedStore=new h(e,r)}getMode(){return this.mode}getAgentWiki(e){let r=`${e}:${this.mode}`;if(this.agentStores.has(r))return this.agentStores.get(r);let t=n(this.agentsDir,e,this.mode),s=new h(t,this.log);return this.agentStores.set(r,s),s}getBaseDir(){return this.baseDir}getSharedStore(){return this.sharedStore}sharedScope(e){return[...this.listAgentDirs().filter(t=>t!==e).map(t=>({id:t,store:this.getAgentWiki(t)})),{id:"shared",store:this.sharedStore,skip:t=>t.startsWith("agents/")}]}listAgentDirs(){return c(this.agentsDir)?u(this.agentsDir).filter(e=>!e.startsWith("_")&&!e.startsWith(".")&&c(n(this.agentsDir,e,this.mode))).sort():[]}listAgents(e=this.sharedStore.listEntries()){let r=new Set;for(let t of e)r.add(t.agentId);if(c(this.agentsDir))for(let t of u(this.agentsDir))!t.startsWith("_")&&!t.startsWith(".")&&r.add(t);return[...r].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){return this.classifyEntries(e).pending}markProcessed(e,r,t){let s=new Set(t),g=this.readLedger(e),d=new Date().toISOString();for(let i of r)g.entries[i]={at:d,cited:s.has(i)};let o=this.ledgerPath(e);l(n(o,".."),{recursive:!0});let a=`${o}.tmp`;f(a,`${JSON.stringify(g,null,2)}
|
|
2
2
|
`),S(a,o)}summary(){let e=this.sharedStore.listEntries(),r=new Map;for(let t of e){let s=r.get(t.agentId);s?s.push(t):r.set(t.agentId,[t])}return this.listAgents(e).map(t=>{let{all:s,cited:g,read:d,pending:o,articles:a}=this.classifyEntries(t,r.get(t)??[]);return{agentId:t,totalEntries:s.length,totalArticles:a.length,cited:g.length,readNotCited:d.length,unabsorbed:o.length,articles:a}})}classifyEntries(e,r=this.getAgentEntries(e)){let t=this.getAgentWiki(e).rebuildIndex().articles,s=new Set;for(let i of t)if(i.sources)for(let y of i.sources)s.add(y);let g=this.readLedger(e).entries,d=[],o=[],a=[];for(let i of r)s.has(i.id)?d.push(i):g[i.id]?o.push(i):a.push(i);return{all:r,cited:d,read:o,pending:a,articles:t}}syncedFrom(e){let r=n(this.agentsDir,e,"_synced.json");if(!c(r))return null;try{return JSON.parse(p(r,"utf-8"))}catch(t){return this.log(`synced marker ${r} is not valid JSON: ${t.message}`),{node:"unknown",peerUrl:"",at:""}}}markSynced(e,r){let t=n(this.agentsDir,e,"_synced.json");l(n(t,".."),{recursive:!0});let s=`${t}.tmp`;f(s,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),S(s,t)}ledgerPath(e){return n(this.agentsDir,e,"_absorbed.json")}readLedger(e){let r=this.ledgerPath(e);if(!c(r))return{entries:{}};try{return{entries:JSON.parse(p(r,"utf-8")).entries??{}}}catch(t){throw new Error(`absorb ledger ${r} is not valid JSON: ${t.message}`)}}};export{m as a};
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
4
|
+
//# sourceMappingURL=chunk-PUW4C6YO.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as w,
|
|
1
|
+
import{a as w,c as f}from"./chunk-KP7KDLZ2.js";import{randomUUID as _}from"crypto";function p(r){return r.status&&r.status!=="ringing"?", waiting_since=NULL, told_at=NULL":""}var E=["ringing","answered","later"],A=`id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,
|
|
2
2
|
ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,
|
|
3
3
|
ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`,y=class{constructor(t){this.db=t;t.exec(`CREATE TABLE IF NOT EXISTS calls (
|
|
4
4
|
id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,
|
|
@@ -8,4 +8,4 @@ import{a as w,b as f}from"./chunk-WBG6NA7R.js";import{randomUUID as _}from"crypt
|
|
|
8
8
|
CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`);let e=new Set(t.prepare("PRAGMA table_info(calls)").all().map(n=>n.name));e.has("kind")||t.exec("ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'"),e.has("channel")||t.exec("ALTER TABLE calls ADD COLUMN channel TEXT"),e.has("chat_id")||t.exec("ALTER TABLE calls ADD COLUMN chat_id TEXT"),e.has("waiting_since")||t.exec("ALTER TABLE calls ADD COLUMN waiting_since INTEGER"),e.has("told_at")||t.exec("ALTER TABLE calls ADD COLUMN told_at INTEGER")}waiting(){let t=this.db.prepare("SELECT id, waiting_since AS since, told_at AS toldAt FROM calls WHERE waiting_since IS NOT NULL AND status='ringing'").all();return new Map(t.map(({id:e,since:n,toldAt:i})=>[e,{since:n,toldAt:i??n}]))}setWaiting(t,e){this.db.prepare("UPDATE calls SET waiting_since=?, told_at=? WHERE id=?").run(e?.since??null,e?.toldAt??null,t)}insert(t){this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,
|
|
9
9
|
answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(t.id,t.agentId,t.kind,t.reason,t.urgency,t.status,t.createdAt,t.ringingSince,t.answeredAt,t.endedAt,t.ringAgainAt,t.note,t.summary,t.channel,t.chatId)}get(t){return this.db.prepare(`SELECT ${A} FROM calls WHERE id=?`).get(t)}update(t,e){let n={reason:"reason",urgency:"urgency",status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},i=Object.keys(e).filter(a=>a in n);if(i.length){let a=i.map(s=>`${n[s]}=?`).join(", ")+p(e);this.db.prepare(`UPDATE calls SET ${a} WHERE id=?`).run(...i.map(s=>e[s]??null),t)}return this.get(t)}transition(t,e,n){let i=Array.isArray(e)?e:[e],a={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},s=Object.keys(n).filter(l=>l in a),o=s.map(l=>`${a[l]}=?`).join(", ")+p(n),u=i.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${o} WHERE id=? AND status IN (${u})`).run(...s.map(l=>n[l]??null),t,...i).changes?this.get(t):void 0}list(t={}){let e=Math.min(Math.max(t.limit??50,1),200),n=[],i=[];t.status?.length&&(n.push(`status IN (${t.status.map(()=>"?").join(",")})`),i.push(...t.status)),t.kind&&(n.push("kind=?"),i.push(t.kind));let a=n.length?`WHERE ${n.join(" AND ")}`:"";return this.db.prepare(`SELECT ${A} FROM calls ${a} ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(...i,e)}countSince(t,e){return this.db.prepare("SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?").get(t,e).n}};var C=200,k=1e4,I=2*36e5,$=10,T=240;function D(r=process.env){return r.AGENTX_TASK_ID?{"X-AgentX-Task":r.AGENTX_TASK_ID}:r.AGENTX_CHANNEL&&r.AGENTX_CHAT_ID?{"X-AgentX-Channel":r.AGENTX_CHANNEL,"X-AgentX-Chat":r.AGENTX_CHAT_ID}:{}}function N(r){return`[Call answered] The owner just picked up the voice call you asked for. You called because: "${r.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var M="[Call ended] The owner hung up. In two or three plain sentences, summarise what was said and decided on this call, for your records. Reply with the summary only.",S=class{constructor(t){this.deps=t;this.waiting=t.store.waiting()}widgetSeenAt=0;widget={};waiting;setWaiting(t,e){if(e)this.waiting.set(t,e);else if(!this.waiting.delete(t))return;this.deps.store.setWaiting(t,e)}now(){return this.deps.now?.()??Date.now()}name(t){return this.deps.agentName(t)??t}async request(t,e={}){let n=String(t.agentId??"").trim(),i=String(t.reason??"").replace(/\s+/g," ").trim(),a=t.urgency==="urgent"?"urgent":"normal",s=t.kind==="camera"?"camera":"voice";if(t.kind!==void 0&&t.kind!=="voice"&&t.kind!=="camera")return{ok:!1,status:400,error:"kind must be voice or camera"};if(!n||!i)return{ok:!1,status:400,error:"Required: agentId and reason"};if(i.length>C)return{ok:!1,status:413,error:`reason is over ${C} characters; keep it to one line`};if(this.deps.agentName(n)===null)return{ok:!1,status:404,error:`Unknown agent: ${n}`};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} placed this call. An agent calls from inside its own run.`};let o=this.deps.config();if(!o.allow.includes("*")&&!o.allow.includes(n))return{ok:!1,status:403,error:`${n} ${s==="camera"?"may not ask to see through the owner's camera":"may not call the owner"}. Add it to calls.allow in agentx.json (or: agentx call allow ${n}).`};if(await this.sweep(),this.deps.store.list({status:E,limit:200}).some(m=>m.agentId===n))return{ok:!1,status:409,error:`${n} already has a call in progress`};let u=this.now();if(this.deps.store.countSince(n,u-36e5)>=o.maxPerHour)return{ok:!1,status:429,error:`${n} has placed ${o.maxPerHour} calls in the last hour (calls.maxPerHour)`};let g=s==="camera"?this.deps.turnSession?.(n,e)??e:{},l={id:`call-${_().slice(0,8)}`,agentId:n,kind:s,reason:i,urgency:a,status:"ringing",createdAt:u,ringingSince:u,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:g.channel&&g.chatId?g.channel:null,chatId:g.channel&&g.chatId?g.chatId:null};this.deps.store.insert(l),this.deps.log?.(`[calls] ${n} asks ${s==="camera"?"to see":"for a call"} (${a}): ${i}`);let d=await this.ring(l),h=this.deps.store.get(l.id);return d!=="waiting"?{ok:!0,call:h,rang:d}:this.waiting.has(l.id)?{ok:!0,call:h,rang:d,busy:this.busyInfo(l)}:{ok:!0,call:h,rang:"widget"}}async cancel(t,e={}){let n=String(t.agentId??"").trim();if(!n)return{ok:!1,status:400,error:"Required: agentId"};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} asked for this. An agent withdraws its own call from inside its run.`};let i=this.deps.store.list({status:["ringing","later"],kind:"voice",limit:200}).find(s=>s.agentId===n);if(!i)return{ok:!1,status:404,error:`${n} has no call waiting or ringing`};let a=this.deps.store.transition(i.id,["ringing","later"],{status:"ended",endedAt:this.now(),ringingSince:null,ringAgainAt:null,note:b});return a?(this.setWaiting(i.id,null),this.deps.log?.(`[calls] ${i.id} withdrawn by ${n}`),{ok:!0,call:a}):{ok:!1,status:409,error:`call is ${this.deps.store.get(i.id)?.status}`}}async ring(t){let e=(this.deps.focus??w)();return e.active&&t.urgency!=="urgent"?(this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:f(e)})&&await this.notice(t,this.missedTitle(t)),!1):t.kind==="camera"?(await this.notice(t,`${this.name(t.agentId)} wants to see through your camera`,`Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`),"notify"):this.widgetAlive()?!this.widget.busy&&!this.otherCalls(t).length?"widget":(this.startWaiting(t),await this.callWaiting(t),"waiting"):(await this.notice(t,`${this.name(t.agentId)} is calling`,`Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`),"notify")}async notice(t,e,n){try{await this.deps.alert({title:e,message:n?`${t.reason}
|
|
10
10
|
${n}`:t.reason,urgent:t.urgency==="urgent",from:t.agentId})}catch(i){this.deps.log?.(`[calls] notice for ${t.id} failed: ${i?.message??i}`)}}startWaiting(t){let e=this.now();this.setWaiting(t.id,{since:e,toldAt:e}),this.deps.log?.(`[calls] ${t.id} from ${t.agentId} waits: the widget is busy`)}otherCalls(t){return this.deps.store.list({status:["ringing","answered"],kind:"voice",limit:200}).filter(e=>e.id!==t.id).reverse()}async callWaiting(t){let e=this.deps.config().busy;await this.notice(t,e.title.replaceAll("{agent}",this.name(t.agentId)),e.notice)}busyInfo(t){let e=this.deps.config().busy,{since:n,toldAt:i}=this.waiting.get(t.id)??{since:this.now(),toldAt:this.now()},a=this.otherCalls(t),s=a.find(d=>d.status==="answered"),o=a.find(d=>d.id===this.widget.showing)??a.find(d=>!this.waiting.has(d.id)),u=n+e.maxWaitMinutes*6e4+this.deps.config().ringSeconds*1e3,g=i+e.retryMinutes*6e4,l=n+e.maxWaitMinutes*6e4;return{why:s?"call":o?"ringing":"voice",with:s?this.name(s.agentId):o?this.name(o.agentId):null,remindAt:g<l?g:null,waitsUntil:u}}missedTitle(t){return t.kind==="camera"?`${this.name(t.agentId)} asked to see through your camera`:`Missed call from ${this.name(t.agentId)}`}inCall(){if(this.widgetAlive()&&this.widget.busy)return"the widget is busy";let t=this.now()-I,e=this.deps.store.list({status:["answered"],limit:5}).find(n=>(n.answeredAt??0)>=t);return e?`on a call with ${this.name(e.agentId)}`:null}widgetAlive(){return this.now()-this.widgetSeenAt<k}async ringing(t={}){return this.widgetSeenAt=this.now(),this.widget=t,await this.hold(t),await this.sweep(),this.deps.store.list({status:["ringing"],kind:"voice",limit:20}).reverse()}async hold(t){let e=this.now(),n=this.deps.config().busy,i=[],a=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let s of[...this.waiting.keys()])a.some(o=>o.id===s)||this.setWaiting(s,null);for(let s of a){if(s.id===t.showing){this.waiting.has(s.id)&&(this.setWaiting(s.id,null),this.deps.store.transition(s.id,"ringing",{ringingSince:e}));continue}if(!t.busy)continue;let o=this.waiting.get(s.id);if(!(o&&e-o.since>=n.maxWaitMinutes*6e4)&&this.deps.store.transition(s.id,"ringing",{ringingSince:e})){if(!o)this.startWaiting(s);else if(e-o.toldAt>=n.retryMinutes*6e4)this.setWaiting(s.id,{since:o.since,toldAt:e});else continue;i.push(s)}}for(let s of i)await this.callWaiting(s)}async asking(){return await this.sweep(),this.deps.store.list({status:["ringing"],kind:"camera",limit:20}).reverse()}async sweep(){let t=this.now(),e=this.deps.config().ringSeconds*1e3,n=this.deps.config().maxCallMinutes*6e4;for(let i of this.deps.store.list({status:["ringing","later","answered"],limit:200}))if(i.status==="ringing"&&i.ringingSince!==null&&t-i.ringingSince>=e){if(!this.deps.store.transition(i.id,"ringing",{status:"missed",ringingSince:null,note:this.waiting.has(i.id)?"widget busy":"not answered"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} missed`),await this.notice(i,this.missedTitle(i))}else if(i.status==="answered"&&i.answeredAt!==null&&t-i.answeredAt>=n){if(!this.deps.store.transition(i.id,"answered",{status:"ended",endedAt:t,note:"no hang-up"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)}else if(i.status==="later"&&i.ringAgainAt!==null&&t>=i.ringAgainAt){let a=this.deps.store.transition(i.id,"later",{status:"ringing",ringingSince:t,ringAgainAt:null});if(!a)continue;this.setWaiting(i.id,null),await this.ring(a)}}answer(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"ringing",{status:"answered",answeredAt:this.now(),ringingSince:null});return n?(this.deps.log?.(`[calls] ${t} answered (${e.agentId})`),n.kind==="camera"?{ok:!0,call:n}:{ok:!0,call:n,opener:N(n)}):{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}decline(t){if(!this.deps.store.get(t))return c(t);let n=this.deps.store.transition(t,["ringing","later"],{status:"declined",endedAt:this.now(),ringingSince:null,ringAgainAt:null});return n?{ok:!0,call:n}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}`}}later(t,e){if(!this.deps.store.get(t))return c(t);let i=e===void 0?$:Number(e);if(!Number.isInteger(i)||i<1||i>T)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${T}`};let a=this.deps.store.transition(t,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+i*6e4});return a?{ok:!0,call:a}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}hangup(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now()});if(!n)return{ok:!1,status:409,error:`call is ${e.status}, not answered`};this.deps.log?.(`[calls] ${t} ended (${e.agentId})`);let i=this.deps.summarize;if(n.kind==="camera"||!this.deps.config().summary||!i)return{ok:!0,call:n};let a=(async()=>{try{let s=(await i(n))?.trim();if(!s)return;let o=this.deps.store.update(t,{summary:s});this.deps.file?.(o,s)}catch(s){this.deps.log?.(`[calls] summary for ${t} failed: ${s?.message??s}`)}})();return{ok:!0,call:n,summarized:a}}endCamera(t,e){let n=this.deps.store.get(t);if(!n||n.kind!=="camera")return!1;let i=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now(),note:e??null});return i&&this.deps.log?.(`[calls] ${t} ended (${n.agentId}): ${e??"share over"}`),!!i}get(t){return this.deps.store.get(t)}list(t={}){return this.deps.store.list(t)}},b="withdrawn by the caller";function W(r,t=Date.now(),e){let n=a=>`${new Date(a).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short",timeZone:e})} (in ${Math.max(1,Math.round((a-t)/6e4))} min)`;return`${r.why==="call"?`The owner is busy in another call${r.with?` (with ${r.with})`:""}.`:r.why==="ringing"?`The owner is busy: another call${r.with?` (from ${r.with})`:""} is ringing.`:"The owner is busy on the voice widget."} They were told you are calling, and why. Your call waits and rings by itself as soon as they are free: do not call again. `+(r.remindAt!==null?`Still busy at ${n(r.remindAt)}, they are told again that you are waiting. `:"")+`It waits until ${n(r.waitsUntil)} at most, then counts as a missed call.`}var c=r=>({ok:!1,status:404,error:`No such call: ${r}`});export{y as a,D as b,M as c,S as d,W as e};
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
11
|
+
//# sourceMappingURL=chunk-PYHR4HXO.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-TZVJP4H3.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
1
|
+
import{a as T,b as E,c as Y,d as j,e as G}from"./chunk-WPNRDEHW.js";import{v as R,y as O,z as U}from"./chunk-5TGY4RIQ.js";import{a as V,b as C,f as B}from"./chunk-72SZI2UW.js";import{a as W,b as se}from"./chunk-MCI3DIWW.js";import{o as z,p as re}from"./chunk-2PJKGZWP.js";B();var xe="wiki-rerank",Se=30,ne=900;function Ne(a){let e=a.excerptChars??ne;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ie(t.excerpt,e)}))}}function ke(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:V("Do any of the candidates answer the query?")}}function Ie(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ie(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},$={code:"Work on source code: review a PR or MR, fix a bug, build a feature, refactor, write a spec, or answer a question about code. Includes changes to AgentX's own code.",ops:"Running systems: deploy, roll back, monitor, scale, restart a service, or handle a production incident.",support:"A person talking to an agent: a greeting, casual chat, thanks, a question to answer, a request for help, a follow-up or complaint about an earlier request, or routing a request to someone else. The default for conversation that is not itself one of the other kinds of work.",admin:"Changing how the agents are set up: configuration, schedules, tokens, roles, adding an agent or a channel. Not a question about the setup or a complaint that something did not run.",knowledge:"Writing or gathering knowledge to keep: documentation, wiki articles, research, summarising a thread.",social:"Content made for an audience other than the agent: posts, announcements, daily briefs, weekly reports. Not a conversation with the agent.",system:"Internal sub-calls made by the platform itself, such as the intent classifier. A message from a person is almost never this."},M=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as _,appendFileSync as oe,existsSync as S,mkdirSync as D,renameSync as ae,statSync as Q}from"fs";import{resolve as A,dirname as Z}from"path";import{createHash as ce}from"crypto";var F=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),D(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{_(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{_(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);X(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),X(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let u=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){u=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=u;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,u=p+1;break}}if(!d&&u<r.levels.length&&(d=r.levels[u].id,u++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${u}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let g={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(g),o.push(g)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=E.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||D(Z(n),{recursive:!0}),oe(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=E.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=E.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[de(e.text),e.channel??""].join("");return ce("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=G.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=Y.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function X(a,e){D(Z(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;_(t,JSON.stringify(e,null,2)),ae(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of M)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category,description:$[r.category]},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of M)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function de(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}se();re();U();import{createHash as ye}from"crypto";B();U();var P="intent-path",le=.5,pe=.3,ue=.45;function ge(a){return{message:ve(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function ee(a,e){let t={};for(let r of a)t[r.id]=me(r);return C(t,e)}function he(a){let e=a.map(t=>{let r=$[t.id];return t.axes?.description?.trim()||!r?t:{...t,axes:{...t.axes,description:r}}});return{category:ee(e,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function fe(a){return{verb:ee(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function q(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=ge(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await O(P,n,he(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=le,b=[c.choice],u=e.filter(m=>m.parentId===c.choice);if(u.length>=2){let m=t.incumbent?.[0]===c.choice,d=await O(P,{...n,category:c.choice},fe(u),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;h=h&&f.pMax>=pe,(f.pMax>=ue||!h)&&(l=Math.min(l,f.pMax),b.push(f.choice))}else u.length===1&&b.push(u[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function me(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function ve(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=z(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:J(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},u=new Set(o.map(g=>g.id)),m=s.map((g,p)=>u.has(g)?-1:p).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=m.length===0,p=m.length===1&&m[0]===s.length-1;d=g||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:J(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await q(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&q(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
5
|
`),i=await this.callProvider(o),s=W(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=te(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??te(d);if(!v)continue;let g={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(g[p]=y);!g.name&&d!==v&&(g.name=d.trim()),b[v]=g}let u={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(u.input=s.leaf.input),typeof s.leaf.output=="string"&&(u.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:u}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function te(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return ye("sha1").update(a.join("")).digest("hex").slice(0,16)}function J(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function we(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{xe as a,Se as b,Ne as c,ke as d,Ie as e,x as f,F as g,L as h,J as i,we as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-Q2QU32JP.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-GJMYG53S.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-E7YHXMJG.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
2
|
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
3
|
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
4
|
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
5
|
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
6
|
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
7
|
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-QXPX2NGL.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-
|
|
1
|
+
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-Q2QU32JP.js";import{y as C,z as K}from"./chunk-5TGY4RIQ.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
|
|
4
4
|
`));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-UVF3K5YS.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{La as m,
|
|
1
|
+
import{La as m,Ua as b}from"./chunk-6UP5VD3H.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
2
|
|
|
3
3
|
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
4
|
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
-
//# sourceMappingURL=chunk-
|
|
5
|
+
//# sourceMappingURL=chunk-YE2X3AFU.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{a as v}from"./chunk-IMLAPB7G.js";import{i as y}from"./chunk-TJZGAKIB.js";import{b as J}from"./chunk-KP7KDLZ2.js";import{I as U,J as W,K as B,L as G,P as k,T as Se}from"./chunk-6UP5VD3H.js";import{existsSync as X,readFileSync as xe}from"node:fs";import{dirname as b,join as h}from"node:path";import{fileURLToPath as Ae}from"node:url";import{homedir as ke}from"node:os";var L="tn.acme.agentx.voice",it="AgentX Desktop.app",K="AgentX Helper.app";function ot(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function st(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function C(e){return`'${e.replace(/'/g,"'\\''")}'`}var V="/usr/bin:/bin:/usr/sbin:/sbin";function at(e,t){return t||[...new Set([...e?[b(e)]:[],...V.split(":")])].join(":")}function N(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function lt(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?N(t[1]):V}var ut=e=>/agentx\.voice.*\.plist$/.test(e);function ct(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,c)=>s.file<c.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],c=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!c||!N(c).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:N(s)}):n={file:o,label:N(s)})}return{keep:n??{file:h(e,`${L}.plist`),label:L},remove:r}}function z(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function pt(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${C(e.cwd)} && ${C(e.node)} ${C(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
|
+
<plist version="1.0"><dict>
|
|
4
|
+
<key>Label</key><string>${t(e.label??L)}</string>
|
|
5
|
+
<key>ProgramArguments</key><array><string>${t(e.executable)}</string></array>
|
|
6
|
+
<key>WorkingDirectory</key><string>${t(e.cwd)}</string>
|
|
7
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(n).map(([r,o])=>`<key>${r}</key><string>${t(o)}</string>`).join("")}</dict>
|
|
8
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
|
|
9
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
10
|
+
<key>StandardErrorPath</key><string>${t(e.log)}</string>
|
|
11
|
+
</dict></plist>
|
|
12
|
+
`}function dt(e){return e?["--icon",e]:[]}function ve(e){return h(e,"Applications",K,"Contents/MacOS/agentx-mac-helper")}function be(e=b(Ae(import.meta.url))){for(let t=e;;t=b(t)){try{if(JSON.parse(xe(h(t,"package.json"),"utf8")).name==="agentix-cli")return t}catch{}if(b(t)===t)return null}}function Ne(e,t,n){if(n)return n;let r=ve(t);return X(r)||!e?r:h(e,"apps/mac-helper/build",K,"Contents/MacOS/agentx-mac-helper")}function M(){let e=Ne(be(),ke(),process.env.AGENTX_MAC_HELPER);return X(e)?e:null}import{accessSync as Oe,constants as Ee}from"fs";import{execFile as T}from"child_process";var Z=5e3,R=(e,t)=>new Promise(n=>{try{T(e,t,{timeout:Z},r=>n(!r))}catch{n(!1)}}),Y=(e,t)=>new Promise(n=>{try{T(e,t,{timeout:Z},(r,o)=>n(r?null:String(o)))}catch{n(null)}}),Q=(e,t)=>new Promise((n,r)=>{T(e,t,{timeout:3e4,maxBuffer:8*1024*1024},(o,i,s)=>{o?r(new Error(`${e} ${t[0]}: ${(s||o.message).trim()}`)):n(i)})});var ee=e=>e.helper===void 0?M():e.helper;async function Re(e,t=Y){if(!e)return"missing";let n=await t(e,["notify-status"]),r=null;try{r=n?JSON.parse(n):null}catch{r=null}return r?r.authorization==="notDetermined"?"not-asked":r.authorization==="denied"?"not-allowed":r.alertStyle==="none"?"hidden":"ready":"outdated"}function te(e={}){let t=e.run??R;return{async post({title:n,message:r}){let o=ee(e);return o&&await t(o,["notify","--title",n,"--message",r])||await t("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",n,r])?"posted":"failed"},status:()=>Re(ee(e),e.capture)}}import{existsSync as $e,readdirSync as Pe}from"fs";var re="/System/Library/Sounds";function ne(e){if(!/^[\w -]+$/.test(e))return null;let t=`${re}/${e}.aiff`;return $e(t)?t:null}function ie(e={}){let t=e.run??R;return{async play(n,r){let o=ne(n);o&&await t("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,r))),o])},has:n=>ne(n)!==null,async names(){try{return Pe(re).filter(n=>n.endsWith(".aiff")).map(n=>n.slice(0,-5)).sort()}catch{return[]}}}}var ae="\u200B";function $(e){return e.startsWith("-")?ae+e:e}var oe=e=>e?.startsWith(ae+"-")?e.slice(1):e;function _(e){if(!e.trim()||e.startsWith("-"))throw new Error(`Reminders list name "${e}" is not usable: it must not be empty or start with "-"`);return e}var se=e=>new Date(Math.floor(e.getTime()/6e4)*6e4).toISOString().replace(/\.\d{3}Z$/,"Z");function le(e="remindctl",t=Q){return{async ensureList(n){let r=await t(e,["list","--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} list: expected a JSON array`);o.some(i=>i?.title===n)||await t(e,["list",_(n),"--create","--json","--no-input"])},async listOpen(n){let r=await t(e,["show","all","--list",_(n),"--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} show: expected a JSON array`);return o.filter(i=>i&&typeof i.id=="string"&&!i.isCompleted).map(i=>({...i,title:oe(i.title)??"",...i.notes!==void 0?{notes:oe(i.notes)}:{}}))},async add({list:n,title:r,notes:o,due:i,priority:s}){let c=["add","--title",$(r),"--list",_(n),"--notes",$(o)];i&&c.push("--due",se(i)),s&&s!=="none"&&c.push("--priority",s);let l=await t(e,[...c,"--json","--no-input"]),d;try{d=JSON.parse(l.trim())?.id}catch{d=void 0}if(typeof d!="string"||!d)throw new Error(`${e} add: no reminder id in its answer`);return{id:d}},async update(n,r){let o=["edit",n];r.title!==void 0&&o.push("--title",$(r.title)),r.notes!==void 0&&o.push("--notes",$(r.notes)),r.due===null?o.push("--clear-due"):r.due&&o.push("--due",se(r.due)),o.length!==2&&await t(e,[...o,"--json","--no-input"])},async complete(n){await t(e,["complete",n,"--json","--no-input"])},async remove(n){await t(e,["delete",n,"--force","--json","--no-input"])}}}var Ce=e=>{try{return Oe(e,Ee.X_OK),!0}catch{return!1}},Le={async active(){let e=J();return e.active?!0:e.reason==="no active Focus assertion"?!1:null}};function ue(e={},t={}){let n=e.reminders?.command||"remindctl";return{os:"macos",tasks:le(n,t.output),banner:te(t),sound:ie(t),focus:Le,async describe(){let r=["Apple Notes is not available yet."],o=t.isExecutable??Ce;return(n.includes("/")?o(n):!!z(n,process.env.PATH||"",o))||r.push(`Reminders: ${n} not found (brew install steipete/tap/remindctl, or set reminders.command).`),{os:"macos",tasks:!0,notes:!1,banner:!0,sound:!0,focus:!0,problems:r}}}}function P(e){return{os:"none",async describe(){return{os:"none",tasks:!1,notes:!1,banner:!1,sound:!1,focus:!1,problems:[e]}}}}var Me={darwin:ue};function I(e={},t={}){if(e.native?.adapter==="none")return P('Turned off: native.adapter is "none".');let n=t.platform??process.platform,r=(t.factories??Me)[n];return r?r(e,t.io??{}):P(`AgentX has no native adapter for ${n} yet.`)}import{existsSync as Te}from"fs";import{homedir as _e}from"os";import{isAbsolute as Ie}from"path";var De={banner:!0,sound:!0,soundName:"Glass",volume:.4};function jt(e){return{...De,...e??{}}}function Ut(e,t={}){let n=I({native:t.native},{platform:t.platform,io:{run:t.run,helper:t.helper}});return async(r,o)=>{let i=[];e.banner&&n.banner&&i.push(n.banner.post({title:r,message:o})),e.sound&&n.sound&&i.push(n.sound.play(e.soundName,e.volume)),await Promise.all(i)}}function Wt(e,t,n=process.platform){let r={...e??{}},o=I({},{platform:n});if("banner"in t&&(r.banner=!!t.banner),"sound"in t&&(r.sound=!!t.sound),"soundName"in t){let i=String(t.soundName).trim();if(!(o.sound?o.sound.has(i):/^[\w -]+$/.test(i)))throw new Error(`no system sound named "${i}" on this machine`);r.soundName=i}if("icon"in t){let i=String(t.icon??"").trim().replace(/^~(?=\/)/,_e());if(!i)delete r.icon;else{if(!Ie(i)||!/\.(png|jpe?g|icns)$/i.test(i))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(o.banner&&!Te(i))throw new Error(`no icon file at ${i}`);r.icon=i}}if("volume"in t){let i=Number(t.volume);if(!Number.isFinite(i)||i<0||i>1)throw new Error("volume must be between 0 and 1");r.volume=i}return r}import{existsSync as Be,mkdirSync as Ge,readFileSync as Je,renameSync as Xe,writeFileSync as Ke}from"fs";import{dirname as de,resolve as Ve}from"path";B();Se();B();var Kt=["owner","agent","person"],qe=36e5,Fe=e=>G.includes(e.state);function ce(e){return t=>!e||e.get(t)?.state!=="active"?null:e.steps(t).find(n=>n.state==="active")?.agentId??null}function D(e,t){return e.state==="waiting_owner"?{group:"owner",who:k}:e.promise&&e.owedTo&&e.owedTo!==k&&!t.isAgent(e.owedTo)?{group:"person",who:e.owedTo}:e.state==="needs_attention"?{group:"owner",who:k}:{group:"agent",who:t.activeStepAgent?.(e.id)??e.agentId}}function q(e,t,n){return Fe(e)?e.state==="needs_attention"?e.attentionReason??"needs attention":e.dueAt!==null?n>e.dueAt?`past its due time (${He(e.dueAt)})`:null:n-e.updatedAt>t*qe?`no activity for ${t} h or more`:null:null}function Vt(e,t,n,r){let o={owner:[],agent:[],person:[]};for(let i of e){let s=q(i,t,n);if(!s)continue;let{group:c,who:l}=D(i,r);o[c].push({request:i,group:c,who:l,why:s})}return o}function zt(e,t){return e==="owner"?"you":e==="agent"?`agent ${t}`:`${t} (outside person)`}var He=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function Zt(e){if(e==null||e==="")return;let t=typeof e=="number"?e:typeof e=="string"?Date.parse(e.trim()):NaN;return!Number.isFinite(t)||t<=0?"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds":t}function Yt(e){return t=>U(t,e())}var je=10;async function Qt(e,t,n){let r=e.dueForCheck(n.now-n.everyMinutes*6e4,je),o=0;return await Promise.all(r.map(async i=>{e.markChecked(i.id,i.verifyState,i.verifyDetail??"",n.now);let s=await t(i.closeWhen,i).catch(c=>({verdict:"unverifiable",detail:String(c?.message??c)}));if(s.verdict==="met"){e.closeVerified(i.id,s.detail,n.now)&&(o++,n.log(`[requests] ${i.id} closed by its check: ${s.detail}`));return}e.markChecked(i.id,s.verdict==="unverifiable"?"unverified":i.verifyState==="failed"?"failed":null,s.detail,n.now)})),{checked:r.length,closed:o}}var Ue=200,pe=4e3;function We(e){return e.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm,"").replace(/[*_~`]+/g,"").replace(/\s+/g," ").trim()}function g(e,t=Ue){let n=We(e);if(n.length<=t)return n;let r=n.slice(0,t),o=Math.max(r.lastIndexOf(". "),r.lastIndexOf("? "),r.lastIndexOf("! "));return o>t/2?r.slice(0,o+1):`${r.slice(0,t-1).trimEnd()}\u2026`}function on(e,t,n,r){let o=n?.get(e.id),i=r?q(e,r.staleAfterHours,r.now):null,s=t.lastAnswer(e.id),c=s&&s.text.length>pe?`${s.text.slice(0,pe)}
|
|
13
|
+
|
|
14
|
+
\u2026`:s?.text;return{...e,summary:g(e.text),textHtml:v(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?v(e.ownerNote):null,lastAnswer:s?{agentId:s.agentId,at:s.at,html:v(c)}:null,loop:e.promise||e.dueAt!==null||e.closeWhen?{owedTo:e.owedTo,promise:e.promise,dueAt:e.dueAt,check:e.closeWhen?W(e.closeWhen):null,verifyState:e.verifyState,verifyDetail:e.verifyDetail}:null,stall:r&&i?{...D(e,{isAgent:r.isAgent,activeStepAgent:ce(n)}),why:i}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(l=>({idx:l.idx,name:l.name,kind:l.kind,agentId:l.agentId,state:l.state,approval:l.needsApproval?l.approval:null,evidence:l.evidence,note:l.note,nudges:l.nudges}))}:null}}var F=3,ze=30*24*36e5;function ge(e){return Ve(e,".agentx","native-mirror.json")}function fe(e){try{let t=JSON.parse(Je(ge(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function me(e,t){let n=ge(e);Be(de(n))||Ge(de(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Ke(r,JSON.stringify(t,null,2)+`
|
|
15
|
+
`),Xe(r,n)}var Ze=5*6e4;function pn(e,t,n=Date.now()){let r=fe(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ze)?!1:r.items[`card:${t}`]?.state!=="failed"}var H=24*36e5;function ye(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function Ye(e,t,n,r){let o=Date.parse(e.expires),i=[g(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,c)=>`${c+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${g(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:g(e.title,y.title),notes:i.join(`
|
|
16
|
+
`),due:ye(r,t,o),priority:Number.isFinite(o)&&o-r<=H?"high":"none"}}function Qe(e,t,n,r){let o=[g(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:g(e.text,y.title),notes:o.join(`
|
|
17
|
+
`),due:ye(r,t,i),priority:i!==void 0&&i-r<=H?"high":"none"}}async function dn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),c={created:0,completed:0,dismissed:0,failed:0},l=fe(t);delete l.lastError;let d=a=>{l.lastError={at:s,message:a}},w=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&w.set(`card:${a.id}`,Ye(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&w.set(`request:${a.id}`,Qe(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),d(String(a?.message??a)),me(t,l),c}let j=!0,x=new Map,he=async a=>{if(!x.has(a))try{x.set(a,new Set((await r.listOpen(a)).map(u=>u.id)))}catch(u){o(`[mirror] could not read list "${a}": ${u?.message??u}`),d(String(u?.message??u)),x.set(a,null),j=!1}return x.get(a)};for(let[a,u]of Object.entries(l.items)){if(u.state!=="open"||!u.id)continue;let p=await he(u.list);if(p)if(w.has(a))p.has(u.id)||(l.items[a]={...u,state:"dismissed",at:s},c.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(p.has(u.id))try{await r.complete(u.id)}catch(f){o(`[mirror] ${a}: could not complete its task: ${f?.message??f}`),d(String(f?.message??f));continue}l.items[a]={...u,state:"completed",at:s},c.completed++}}let O=null,S=[];for(let[a,u]of w){let p=l.items[a];if(p&&(p.state==="open"||p.state==="dismissed")||p?.state==="failed"&&p.failures>=F)continue;if(O===null)try{await r.ensureList(n.list),O=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),d(String(m?.message??m)),O=!1}let f=p?.state==="failed"?p.failures:0;try{let{id:m}=await r.add({list:n.list,title:u.title,notes:u.notes,due:u.due,priority:u.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},c.created++}catch(m){let A=String(m?.message??m),E=f+1;l.items[a]={list:n.list,state:"failed",at:s,failures:E,lastError:A},d(A),c.failed++,o(`[mirror] ${a}: could not add to Reminders (${E}/${F}): ${A}`),E===F&&S.push({title:u.title,message:A})}}let we=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(S.length&&!(i-we<H)){let a=S[0],u=S.length>1?` (and ${S.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${u}: ${g(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(p){o(`[mirror] could not tell the owner: ${p?.message??p}`)}}j&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,u]of Object.entries(l.items))u.state!=="open"&&!w.has(a)&&i-Date.parse(u.at)>ze&&delete l.items[a];return me(t,l),c}export{it as a,K as b,ot as c,st as d,at as e,lt as f,ut as g,ct as h,z as i,pt as j,dt as k,ve as l,be as m,Ne as n,M as o,ne as p,I as q,De as r,jt as s,Ut as t,Wt as u,Kt as v,ce as w,D as x,Vt as y,zt as z,He as A,Zt as B,Yt as C,Qt as D,g as E,on as F,fe as G,pn as H,dn as I};
|
|
18
|
+
//# sourceMappingURL=chunk-Z3AI4KXT.js.map
|