agentix-cli 0.8.0 → 0.13.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/README.md +387 -116
- package/dist/agent-5KIMJI3F.js +2 -0
- package/dist/chunk-34UAFPK4.js +10 -0
- package/dist/chunk-34UAFPK4.js.map +1 -0
- package/dist/{chunk-X7UN6JAA.js → chunk-6MKAXEE5.js} +2 -2
- package/dist/chunk-CJ45Y2IR.js +12 -0
- package/dist/chunk-CJ45Y2IR.js.map +1 -0
- package/dist/chunk-D6EDMQRV.js +108 -0
- package/dist/chunk-D6EDMQRV.js.map +1 -0
- package/dist/chunk-DSYKYZMT.js +2 -0
- package/dist/chunk-DSYKYZMT.js.map +1 -0
- package/dist/chunk-HI24KAEY.js +54 -0
- package/dist/chunk-HI24KAEY.js.map +1 -0
- package/dist/{chunk-MGMZNJCE.js → chunk-KXZMYLHQ.js} +27 -27
- package/dist/chunk-KXZMYLHQ.js.map +1 -0
- package/dist/chunk-MCJUAE6V.js +6 -0
- package/dist/chunk-MCJUAE6V.js.map +1 -0
- package/dist/chunk-QOYAX2FT.js +2 -0
- package/dist/chunk-QOYAX2FT.js.map +1 -0
- package/dist/chunk-QZP65I2H.js +45 -0
- package/dist/chunk-QZP65I2H.js.map +1 -0
- package/dist/chunk-T25UEXVK.js +126 -0
- package/dist/chunk-T25UEXVK.js.map +1 -0
- package/dist/chunk-VH23CDHL.js +157 -0
- package/dist/chunk-VH23CDHL.js.map +1 -0
- package/dist/chunk-WJ6ZF6EZ.js +6 -0
- package/dist/chunk-WJ6ZF6EZ.js.map +1 -0
- package/dist/chunk-ZRYBSI5G.js +23 -0
- package/dist/chunk-ZRYBSI5G.js.map +1 -0
- package/dist/cli.js +277 -36
- package/dist/cli.js.map +1 -1
- package/dist/compaction-7I3E5QUO.js +28 -0
- package/dist/compaction-7I3E5QUO.js.map +1 -0
- package/dist/config-HAD5E4YX.js +2 -0
- package/dist/debug-N3B5NVJU.js +2 -0
- package/dist/heal-OTGT5HHJ.js +2 -0
- package/dist/index.d.ts +1849 -368
- package/dist/index.js +39 -35
- package/dist/index.js.map +1 -1
- package/dist/loader-YQE6XJBT.js +2 -0
- package/dist/loader-YQE6XJBT.js.map +1 -0
- package/dist/memory-extract-RGPUPMKU.js +2 -0
- package/dist/memory-extract-RGPUPMKU.js.map +1 -0
- package/dist/{providers-AVYG63KK.js → providers-G3WZ4RVJ.js} +2 -2
- package/dist/providers-G3WZ4RVJ.js.map +1 -0
- package/dist/registry-CDWY7CLL.js +2 -0
- package/dist/registry-CDWY7CLL.js.map +1 -0
- package/dist/subagent-WV7QKQ3L.js +3 -0
- package/dist/subagent-WV7QKQ3L.js.map +1 -0
- package/dist/usage-dashboard-2TJQBFSH.js +404 -0
- package/dist/usage-dashboard-2TJQBFSH.js.map +1 -0
- package/dist/workspace-setup-QQTCJY4B.js +2 -0
- package/dist/workspace-setup-QQTCJY4B.js.map +1 -0
- package/package.json +4 -1
- package/dist/agent-K2YOEOJ5.js +0 -2
- package/dist/chunk-F73GPYCO.js +0 -106
- package/dist/chunk-F73GPYCO.js.map +0 -1
- package/dist/chunk-FRFR27IN.js +0 -3
- package/dist/chunk-FRFR27IN.js.map +0 -1
- package/dist/chunk-MGMZNJCE.js.map +0 -1
- package/dist/chunk-NGKOM4ZZ.js +0 -137
- package/dist/chunk-NGKOM4ZZ.js.map +0 -1
- package/dist/chunk-Z4GC5D6D.js +0 -12
- package/dist/chunk-Z4GC5D6D.js.map +0 -1
- package/dist/heal-UV5A6B5T.js +0 -2
- package/dist/loader-6VSM6FSY.js +0 -2
- /package/dist/{agent-K2YOEOJ5.js.map → agent-5KIMJI3F.js.map} +0 -0
- /package/dist/{chunk-X7UN6JAA.js.map → chunk-6MKAXEE5.js.map} +0 -0
- /package/dist/{heal-UV5A6B5T.js.map → config-HAD5E4YX.js.map} +0 -0
- /package/dist/{loader-6VSM6FSY.js.map → debug-N3B5NVJU.js.map} +0 -0
- /package/dist/{providers-AVYG63KK.js.map → heal-OTGT5HHJ.js.map} +0 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import{a as G,b as Y,d as X}from"./chunk-HI24KAEY.js";import{a as J}from"./chunk-34UAFPK4.js";import{a as K}from"./chunk-ZRYBSI5G.js";import{c as D,d as C}from"./chunk-QOYAX2FT.js";import{execa as xe}from"execa";import{execFile as ve}from"child_process";function U(c,e,t){let s=[];if(c.systemPrompt&&s.push(c.systemPrompt),e.context&&!t){let n=e.context,r=["","[Environment]"],i=n.channel==="gitlab"||n.channel?.startsWith("webhook:"),a=n.channel==="telegram";if(n.channel&&r.push(`Channel: ${n.channel}`),n.group&&r.push(`Group: ${n.group}`),n.sender&&r.push(`Message from: ${n.sender}`),n.myHandle&&r.push(`Your handle on this channel: ${n.myHandle}`),i&&(r.push(""),r.push("[IMPORTANT: You are responding to a GitLab comment/event]"),r.push("- Keep it short \u2014 3-5 lines for the main message. Humans scan, not read"),r.push("- Lead with the result or action, not a narration of what you plan to do"),r.push("- Use <details><summary>Details</summary>\\n\\ncontent\\n</details> for verbose output (logs, full commands, step-by-step)"),r.push("- Do NOT mention Telegram handles \u2014 they don't work on GitLab"),r.push("- Do NOT try to delegate to other agents \u2014 reply directly"),r.push("- Reference issues with #IID and MRs with !IID")),a&&n.peers?.length){r.push(""),r.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let o of n.peers){let l=o.handle?` (mention: ${o.handle})`:"",d=o.role?` \u2014 ${o.role}`:"";r.push(`\u2022 ${o.name}${l}${d}`)}r.push(""),r.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(r.join(`
|
|
2
|
+
`))}return e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
|
|
3
|
+
`)}function V(c,e,t,s){let n=["-p",e,"--output-format",t?"stream-json":"json"];return t&&n.push("--verbose"),s&&n.push("--resume",s),c.model&&n.push("--model",c.model),c.permissionMode==="bypassPermissions"&&n.push("--dangerously-skip-permissions"),n}function Se(c){try{let e=JSON.parse(c),t=e.usage?{inputTokens:e.usage.input_tokens||0,outputTokens:e.usage.output_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreateTokens:e.usage.cache_creation_input_tokens||0}:void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t}}catch{return{text:c}}}async function ke(c,e,t,s){let n=Date.now(),r=U(c,e,t),i=V(c,r,!1,s);try{let{stdout:a,stderr:o,exitCode:l}=await new Promise((p,h)=>{let g=ve("claude",i,{cwd:c.workspace,timeout:6e5,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"user")}},(m,f,b)=>{p({stdout:f||"",stderr:b||"",exitCode:m?m.code??1:0})})});if(!a&&l!==0)return{content:"",error:(o?.trim()||`Claude Code exited with code ${l}`).slice(0,300),duration:Date.now()-n};let d=Se(a);return{content:d.text,duration:Date.now()-n,claudeSessionId:d.sessionId,usage:d.usage}}catch(a){return console.error(`[runtime] execFile threw: ${a.message}`),{content:"",error:a.message||"Claude Code failed",duration:Date.now()-n}}}async function $e(c,e,t,s,n){let r=Date.now(),i=U(c,e,s),a=V(c,i,!0,n),o="";try{let l=xe("claude",a,{cwd:c.workspace,timeout:6e5,reject:!1,env:process.env,buffer:!1});if(l.stdout){let p="";l.stdout.on("data",h=>{p+=h.toString();let g=p.split(`
|
|
4
|
+
`);p=g.pop()||"";for(let m of g)if(m.trim())try{let f=JSON.parse(m);if(f.type==="assistant"&&f.message?.content){for(let b of f.message.content)if(b.type==="text"&&b.text){let k=b.text.slice(o.length);k&&(o=b.text,t(k,o))}}if(f.type==="content_block_delta"&&f.delta?.text&&(o+=f.delta.text,t(f.delta.text,o)),f.type==="result"&&f.result){let b=(typeof f.result=="string",f.result);if(typeof b=="string"&&b.length>o.length){let k=b.slice(o.length);o=b,k&&t(k,o)}}}catch{m.trim()&&!m.startsWith("{")&&(o+=m+`
|
|
5
|
+
`,t(m+`
|
|
6
|
+
`,o))}})}let d=await l;return!o&&d.stdout&&(o=typeof d.stdout=="string"?d.stdout:""),d.exitCode!==0&&!o?{content:"",error:(typeof d.stderr=="string"?d.stderr:"")||`Claude Code exited with code ${d.exitCode}`,duration:Date.now()-r}:{content:o,duration:Date.now()-r}}catch(l){return{content:o||"",error:l.message,duration:Date.now()-r}}}async function Ae(c,e,t,s){let n=Date.now();try{let r=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=r,a=U(c,e,s),o="",l=i({prompt:a,options:{model:c.model,cwd:c.workspace,permissionMode:"bypassPermissions"}});for await(let d of l)d.type==="result"&&d.subtype==="success"&&(o=d.result||"");return{content:o,duration:Date.now()-n}}catch(r){return{content:"",error:`SDK error: ${r.message}`,duration:Date.now()-n}}}async function De(c,e,t,s){let n=Date.now();try{let{generate:r}=await import("./agent-5KIMJI3F.js"),i=c.provider||"claude-code",a=s?`${s}
|
|
7
|
+
|
|
8
|
+
${e.message}`:e.message,o=await r({task:a,cwd:c.workspace,provider:i,model:c.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:o.content||"Done.",tokensUsed:o.tokensUsed,duration:Date.now()-n}}catch(r){return{content:"",error:`Orchestrator error: ${r.message}`,duration:Date.now()-n}}}async function z(c,e,t,s,n,r){switch(c.tier){case"claude-code":return s?$e(c,e,s,n,r):ke(c,e,n,r);case"sdk":{let i=c.provider||"claude",a=t[i]?.apiKey;return a?Ae(c,e,a,n):{content:"",error:`No API key for provider "${i}". Configure providers.${i}.apiKey`}}case"orchestrator":{let i=c.provider||"claude-code",a=t[i]?.apiKey;return De(c,e,a,n)}default:return{content:"",error:`Unknown tier: ${c.tier}`}}}import{readFileSync as Z,writeFileSync as Ce,mkdirSync as Ie,existsSync as ee,readdirSync as Te}from"fs";import{resolve as H}from"path";var We=12e3,te=30,Me=15,Pe="[Compacted conversation summary",R=class{sessionsDir;cache=new Map;constructor(e=process.cwd()){this.sessionsDir=H(e,".agentx/sessions"),ee(this.sessionsDir)||Ie(this.sessionsDir,{recursive:!0})}sessionKey(e,t,s){let n=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${n}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return H(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let n=this.sessionKey(e,t,s);if(this.cache.has(n))return this.cache.get(n);let r=this.sessionFile(n);if(ee(r))try{let o=JSON.parse(Z(r,"utf-8"));return this.cache.set(n,o),o}catch{}let i=new Date().toISOString().slice(0,10),a={id:n,agentId:e,channel:t,chatId:s,day:i,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(n,a),this.save(a),a}addUserMessage(e,t,s,n,r){let i=this.getSession(e,t,s);i.messages.push({role:"user",name:n,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i)}addAgentMessage(e,t,s,n){let r=this.getSession(e,t,s);r.messages.push({role:"agent",name:e,content:n,timestamp:new Date().toISOString()}),this.trim(r),r.updatedAt=new Date().toISOString(),this.save(r)}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,n){let r=this.getSession(e,t,s);r.claudeSessionId=n,r.updatedAt=new Date().toISOString(),this.save(r)}buildHistoryContext(e,t,s){let n=this.getSession(e,t,s);if(n.messages.length===0)return"";let r=[`[Conversation history for today (${n.day})]`];for(let i of n.messages){let a=i.timestamp.slice(11,16);i.role==="user"?r.push(`[${a}] ${i.name||"User"}: ${i.content}`):r.push(`[${a}] ${i.name||"Agent"}: ${i.content}`)}return r.push("[End of history \u2014 respond to the latest message above]"),r.push(""),r.join(`
|
|
9
|
+
`)}isSessionStale(e,t,s){let n=this.getSession(e,t,s);return n.claudeSessionId?Date.now()-new Date(n.updatedAt).getTime()>Me*60*1e3:!1}getCrossSessionSummary(e,t,s){let n=new Date().toISOString().slice(0,10),r=this.sessionKey(e,t,s);try{let i=Te(this.sessionsDir).filter(o=>o.startsWith(e.replace(/[^a-zA-Z0-9_:-]/g,"_"))&&o.includes(n)&&o.endsWith(".json")),a=[];for(let o of i)try{let l=JSON.parse(Z(H(this.sessionsDir,o),"utf-8"));if(l.id===r||l.messages.length===0)continue;let d=l.messages.slice(-4),h=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,g=d.map(m=>` [${m.timestamp.slice(11,16)}] ${m.name||m.role}: ${m.content.slice(0,200)}`);a.push(`From ${h} (${l.channel}):
|
|
10
|
+
${g.join(`
|
|
11
|
+
`)}`)}catch{}return a.length===0?"":["[Cross-chat context \u2014 recent activity from your other conversations today]",...a,"[End cross-chat context \u2014 the user in THIS chat may be referring to actions from above]",""].join(`
|
|
12
|
+
`)}catch{return""}}async compactIfNeeded(e,t,s,n){let r=this.getSession(e,t,s),{needsCompaction:i,compactSession:a,applyCompaction:o}=await import("./compaction-7I3E5QUO.js");if(!i(r.messages))return{compacted:!1};let l=await a(r.messages,e,n);return l.compactedCount===0?{compacted:!1}:(r.messages=o(r.messages,l),r.updatedAt=new Date().toISOString(),delete r.claudeSessionId,this.save(r),{compacted:!0,qualityScore:l.qualityScore,lostEntities:l.lostEntities,drift:l.drift})}hasCompaction(e,t,s){let n=this.getSession(e,t,s);return n.messages.length>0&&n.messages[0].content.startsWith(Pe)}clearClaudeSessionId(e,t,s){let n=this.getSession(e,t,s);delete n.claudeSessionId,n.updatedAt=new Date().toISOString(),this.save(n)}trim(e){e.messages.length>te&&(e.messages=e.messages.slice(-te));let t=e.messages.reduce((s,n)=>s+n.content.length,0);for(;t>We&&e.messages.length>2;){let s=e.messages.shift();t-=s.content.length}}save(e){try{let t=this.sessionFile(e.id);Ce(t,JSON.stringify(e,null,2))}catch{}}};import{readFileSync as A,writeFileSync as v,appendFileSync as Re,existsSync as x,mkdirSync as O,readdirSync as L,statSync as Oe}from"fs";import{resolve as y,join as Le,relative as S,dirname as je}from"path";var T=class{baseDir;rawDir;log;constructor(e=y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=y(e,"raw/entries"),this.log=t,O(this.rawDir,{recursive:!0}),O(y(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return e.access==="public"?!0:t?!!(e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t)):!1}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=y(this.rawDir,t),n=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&n.push(`context: ${e.sourceContext}`),e.meta)for(let[r,i]of Object.entries(e.meta))n.push(`${r}: ${JSON.stringify(i)}`);return n.push("---","",e.content),v(s,n.join(`
|
|
13
|
+
`)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!x(this.rawDir))return[];let t=L(this.rawDir).filter(n=>n.endsWith(".md")).sort(),s=[];for(let n of t){let r=A(y(this.rawDir,n),"utf-8"),i=this.parseEntry(r,n);i&&(e?.agentId&&i.agentId!==e.agentId||e?.after&&i.date<e.after||e?.before&&i.date>e.before||s.push(i))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let n=s[1],r=s[2].trim(),i=a=>n.match(new RegExp(`^${a}:\\s*(.+)$`,"m"))?.[1]?.trim()||"";return{id:i("id")||t.replace(".md",""),date:i("date"),agentId:i("agent"),source:i("source"),sourceContext:i("context")||void 0,content:r}}writeArticle(e,t,s,n){let r=this.readArticle(e);if(r&&!this.canWrite(r.meta,n))return this.log(`Permission denied: "${n}" cannot write "${e}" (owner: ${r.meta.owner})`),!1;let i=y(this.baseDir,e);r&&this.saveVersion(e,i),O(je(i),{recursive:!0});let a=["---",`title: "${t.title}"`,`tags: [${(t.tags||[]).map(l=>`"${l}"`).join(", ")}]`,`owner: ${t.owner}`,`access: ${t.access}`];t.sharedWith?.length&&a.push(`shared_with: [${t.sharedWith.map(l=>`"${l}"`).join(", ")}]`),a.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`sources: [${t.sources.map(l=>`"${l}"`).join(", ")}]`),a.push("---","",s),v(i,a.join(`
|
|
14
|
+
`));let o=r?"update":"create";return this.appendLog(o,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${n} at ${e}`),!0}saveVersion(e,t){try{if(!x(t))return;let s=A(t,"utf-8"),n=new Date().toISOString().replace(/[:.]/g,"-"),r=y(this.baseDir,"_versions",e.replace(/\.md$/,""));O(r,{recursive:!0}),v(y(r,`${n}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!x(t))return[];try{return L(t).filter(s=>s.endsWith(".md")).sort().reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(n,r)=>r<19?r===10?"T":r===13||r===16?":":"-":n),path:y(t,s)}))}catch{return[]}}restoreVersion(e,t){let n=this.getVersions(e).find(r=>r.timestamp.startsWith(t));if(!n)return!1;try{let r=A(n.path,"utf-8"),i=y(this.baseDir,e);return this.saveVersion(e,i),v(i,r),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!x(t))return null;let s=A(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let n=s[1],r=s[2].trim(),i=l=>n.match(new RegExp(`^${l}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=l=>{let d=n.match(new RegExp(`^${l}:\\s*\\[(.*)\\]$`,"m"));return d?d[1].split(",").map(p=>p.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},o=[...a("tags"),...i("kind")?[i("kind")]:[],...i("type")?[i("type")]:[]].filter((l,d,p)=>l&&p.indexOf(l)===d);return{meta:{title:i("title"),tags:o,owner:i("owner"),access:i("access")||"public",sharedWith:a("shared_with"),created:i("created"),lastUpdated:i("last_updated"),sources:a("sources")},content:r,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=S(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_"))return;let r=this.readArticle(n);r&&this.canRead(r.meta,e)&&t.push(r)}),t}search(e,t,s=10){let n=e.toLowerCase(),r=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let g=S(this.baseDir,h);if(g.startsWith("raw/")||g.startsWith("_"))return;let m=this.readArticle(g);!m||!this.canRead(m.meta,t)||r.push(m)}),r.length===0)return[];let i=r.map(h=>h.content),a=y(this.baseDir,"_bm25_cache.json"),o=C(i,a),l=D(e,o),d=new Map(l.map(h=>[h.docIndex,h.score]));return r.map((h,g)=>{let m=d.get(g)??0;return h.meta.title.toLowerCase().includes(n)&&(m+=10),h.meta.tags?.some(f=>f.toLowerCase().includes(n))&&(m+=5),{article:h,score:m}}).filter(h=>h.score>0).sort((h,g)=>g.score-h.score).slice(0,s).map(h=>h.article)}findRelevant(e,t,s=3){let n=[];if(this.walkDir(this.baseDir,l=>{if(!l.endsWith(".md"))return;let d=S(this.baseDir,l);if(d.startsWith("raw/")||d.startsWith("_"))return;let p=this.readArticle(d);!p||!this.canRead(p.meta,t)||n.push(p)}),n.length===0)return[];let r=n.map(l=>`${l.meta.title} ${(l.meta.tags||[]).join(" ")} ${l.content}`),i=y(this.baseDir,"_bm25_relevance_cache.json"),a=C(r,i);return D(e,a).slice(0,s).map(l=>n[l.docIndex])}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],n=0;for(let r of e){let i=`
|
|
15
|
+
## ${r.meta.title} [${(r.meta.tags||[]).slice(0,3).join(", ")}]`,a=r.content.length>600?r.content.slice(0,600)+"...":r.content,o=i+`
|
|
16
|
+
`+a;if(n+o.length>t)break;s.push(o),n+=o.length}return s.push(`
|
|
17
|
+
[End Wiki Knowledge]`),s.join(`
|
|
18
|
+
`)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=S(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(!o)return;let l=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let p of l){let h=p.replace(/\[\[|\]\]/g,"");t.set(h,(t.get(h)||0)+1)}let d=[o.meta.title.toLowerCase()];o.meta.tags&&d.push(...o.meta.tags.map(p=>p.toLowerCase())),e.push({path:a,title:o.meta.title,tags:o.meta.tags||[],owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:d,backlinks:t.get(o.meta.title)||0,sources:o.meta.sources,lastUpdated:o.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};v(y(this.baseDir,"_index.json"),JSON.stringify(s,null,2));let n=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],r=new Map;for(let i of e){let a=i.type||i.access||"public",o=r.get(a)||[];o.push(i),r.set(a,o)}for(let[i,a]of Array.from(r.entries()).sort()){n.push(`## ${i}`,"");for(let o of a.sort((l,d)=>l.title.localeCompare(d.title))){let l=o.access==="private"?" (private)":o.access==="shared"?" (shared)":"";n.push(`- [${o.title}](${o.path})${l} \u2014 owner: ${o.owner}`)}n.push("")}return v(y(this.baseDir,"WIKI.md"),n.join(`
|
|
19
|
+
`)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),s}stats(){let e=0,t={},s={},n={};this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=S(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_")||a==="WIKI.md")return;let o=this.readArticle(a);if(o){e++;for(let l of o.meta.tags||[])t[l]=(t[l]||0)+1;s[o.meta.access]=(s[o.meta.access]||0)+1,n[o.meta.owner]=(n[o.meta.owner]||0)+1}});let r=x(this.rawDir)?L(this.rawDir).filter(i=>i.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:r,articlesByType:t,articlesByAccess:s,articlesByOwner:n}}appendLog(e,t){let s=y(this.baseDir,"log.md"),r=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
|
|
20
|
+
|
|
21
|
+
`;x(s)||v(s,`# Wiki Log
|
|
22
|
+
|
|
23
|
+
Chronological record of all wiki operations.
|
|
24
|
+
|
|
25
|
+
`),Re(s,r)}getLog(e=20){let t=y(this.baseDir,"log.md");return x(t)?A(t,"utf-8").split(/^## /m).filter(r=>r.startsWith("[")).slice(-e).map(r=>r.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if(x(e))return;v(e,`# Wiki Schema
|
|
26
|
+
|
|
27
|
+
A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
|
|
28
|
+
structure emerges from data. The wiki is a compounding artifact.
|
|
29
|
+
|
|
30
|
+
## Structure
|
|
31
|
+
|
|
32
|
+
\`\`\`
|
|
33
|
+
wiki/
|
|
34
|
+
_schema.md # This file
|
|
35
|
+
worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
|
|
36
|
+
raw/entries/ # Immutable raw sources (conversations, imports, anything)
|
|
37
|
+
[LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
|
|
38
|
+
\`\`\`
|
|
39
|
+
|
|
40
|
+
The LLM decides how to organize articles. You describe YOUR world in worldview.md.
|
|
41
|
+
|
|
42
|
+
## Article Format
|
|
43
|
+
|
|
44
|
+
\`\`\`yaml
|
|
45
|
+
---
|
|
46
|
+
title: "Staging Deployment Process"
|
|
47
|
+
tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
|
|
48
|
+
owner: devops-agent
|
|
49
|
+
access: public
|
|
50
|
+
created: 2026-04-06
|
|
51
|
+
last_updated: 2026-04-06
|
|
52
|
+
sources: ["entry-id-1", "entry-id-2"]
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
Article content with [[wikilinks]] and section tags.
|
|
56
|
+
|
|
57
|
+
## Deploy Steps
|
|
58
|
+
<!-- tags: process, runbook, staging -->
|
|
59
|
+
Content specific to this section...
|
|
60
|
+
\`\`\`
|
|
61
|
+
|
|
62
|
+
## Tags
|
|
63
|
+
|
|
64
|
+
Tags are the primary context-narrowing mechanism. The more tags, the better.
|
|
65
|
+
|
|
66
|
+
Tag aggressively:
|
|
67
|
+
- **Who**: people, agents, teams involved
|
|
68
|
+
- **What**: project, client, topic, technology
|
|
69
|
+
- **When**: dates, periods, milestones
|
|
70
|
+
- **Where**: server, environment, channel
|
|
71
|
+
- **How**: process, decision, pattern
|
|
72
|
+
- **Your terms**: whatever vocabulary makes sense in YOUR world
|
|
73
|
+
|
|
74
|
+
Section tags (\`<!-- tags: ... -->\`) let different parts of an article
|
|
75
|
+
match different queries. A deploy article might have sections tagged
|
|
76
|
+
"runbook" and "incident" separately.
|
|
77
|
+
|
|
78
|
+
## Operations
|
|
79
|
+
|
|
80
|
+
### Absorb
|
|
81
|
+
Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
|
|
82
|
+
Also identify GAPS: "We mention X but have no article for it."
|
|
83
|
+
|
|
84
|
+
### Query
|
|
85
|
+
Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
|
|
86
|
+
If agent is working on a specific project, only send content tagged for that project.
|
|
87
|
+
|
|
88
|
+
### Lint
|
|
89
|
+
Check for: orphan articles, broken [[wikilinks]], untagged articles,
|
|
90
|
+
articles over 100 lines that should split, mentioned-but-missing topics.
|
|
91
|
+
|
|
92
|
+
## Worldview
|
|
93
|
+
|
|
94
|
+
Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
|
|
95
|
+
mental model. The LLM reads it during absorb to understand where things go.
|
|
96
|
+
|
|
97
|
+
Example worldview.md:
|
|
98
|
+
\`\`\`
|
|
99
|
+
I'm the founder of Acme Corp.
|
|
100
|
+
We build software products.
|
|
101
|
+
Our agents: Marketing Bot, DevOps Bot, Coordinator.
|
|
102
|
+
Clients: ClientA (enterprise), ClientB (startup).
|
|
103
|
+
Infrastructure: local dev machine, cloud server.
|
|
104
|
+
We use GitLab for version control.
|
|
105
|
+
\`\`\`
|
|
106
|
+
`),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let n=A(t,"utf-8"),r=this.extractWikilinks(n);for(let i of r)e[i]||(e[i]=[]),e[i].push(s)}),v(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!x(t))return[];try{return JSON.parse(A(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let n=e.map(i=>i.toLowerCase()),r=[];return this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=S(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(!o||t&&!this.canRead(o.meta,t))return;let l=(o.meta.tags||[]).map(g=>g.toLowerCase()),d=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(g=>g.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(m=>m.trim().toLowerCase())),p=[...l,...d],h=n.filter(g=>p.includes(g)).length;h>0&&r.push({article:o,score:h})}),r.sort((i,a)=>a.score-i.score).slice(0,s).map(i=>i.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_"))return;let n=this.readArticle(s);if(n?.meta.tags)for(let r of n.meta.tags)e.set(r,(e.get(r)||0)+1)}),e}getWorldview(){let e=y(this.baseDir,"worldview.md");return x(e)?A(e,"utf-8"):null}setWorldview(e){v(y(this.baseDir,"worldview.md"),e),this.appendLog("worldview","Updated worldview")}lint(){let e=[],t=new Set,s=new Map,n=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=S(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_")||a==="WIKI.md"||a==="log.md")return;let o=this.readArticle(a);if(!o)return;t.add(o.meta.title),n.set(o.meta.title,a);let l=this.extractWikilinks(o.content);s.set(a,l);let d=o.content.split(`
|
|
107
|
+
`).length;d>100&&e.push({type:"bloated",article:a,message:`${d} lines \u2014 consider splitting`}),o.meta.sources?.length||e.push({type:"unsourced",article:a,message:"No sources listed in frontmatter"}),d<10&&o.content.trim().length<100&&e.push({type:"stub",article:a,message:"Very short article \u2014 needs enrichment"})});for(let[i,a]of s)for(let o of a)t.has(o)||e.push({type:"broken-link",article:i,message:`[[${o}]] \u2014 target article not found`});let r=this.buildBacklinks();for(let[i,a]of n)(!r[i]||r[i].length===0)&&e.push({type:"orphan",article:a,message:`No other articles link to "${i}"`});return this.appendLog("lint",`Found ${e.length} issues`),e}getUnabsorbedEntries(){let e=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=S(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_"))return;let r=this.readArticle(n);if(r?.meta.sources)for(let i of r.meta.sources)e.add(i)}),this.listEntries().filter(s=>!e.has(s.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let s=t.map(n=>`[${n.date} ${n.agentId} via ${n.source}] ${n.content.slice(0,200)}`).join(`
|
|
108
|
+
|
|
109
|
+
`);return`/wiki absorb
|
|
110
|
+
|
|
111
|
+
There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
112
|
+
|
|
113
|
+
${s}`}walkDir(e,t){if(x(e))for(let s of L(e)){let n=Le(e,s);Oe(n).isDirectory()?this.walkDir(n,t):t(n)}}};import{resolve as B}from"path";import{existsSync as _e,readdirSync as Ee,mkdirSync as Fe}from"fs";var M=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=B(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki-hub]"),s="graph"){this.baseDir=e,this.agentsDir=B(e,"agents"),this.mode=s,this.log=t,Fe(this.agentsDir,{recursive:!0}),this.sharedStore=new T(e,t)}getMode(){return this.mode}getAgentWiki(e){let t=`${e}:${this.mode}`;if(this.agentStores.has(t))return this.agentStores.get(t);let s=B(this.agentsDir,e,this.mode),n=new T(s,this.log);return this.agentStores.set(t,n),n}getSharedStore(){return this.sharedStore}listAgents(){let e=new Set,t=this.sharedStore.listEntries();for(let s of t)e.add(s.agentId);if(_e(this.agentsDir))for(let s of Ee(this.agentsDir))!s.startsWith("_")&&!s.startsWith(".")&&e.add(s);return[...e].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){let t=this.getAgentWiki(e),s=this.getAgentEntries(e),n=new Set,r=t.rebuildIndex();for(let i of r.articles)if(i.sources)for(let a of i.sources)n.add(a);return s.filter(i=>!n.has(i.id))}summary(){return this.listAgents().map(t=>{let s=this.getAgentEntries(t),r=this.getAgentWiki(t).rebuildIndex(),i=this.getUnabsorbedEntries(t);return{agentId:t,totalEntries:s.length,totalArticles:r.articles.length,unabsorbed:i.length,articles:r.articles}})}};var j=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),s=this.windows.get(e)||[],n=t-36e5,r=s.filter(o=>o>n),i=t-6e4,a=r.filter(o=>o>i).length;return a>=this.maxPerMinute?{allowed:!1,reason:`Rate limit: ${a}/${this.maxPerMinute} per minute`}:r.length>=this.maxPerHour?{allowed:!1,reason:`Rate limit: ${r.length}/${this.maxPerHour} per hour`}:(r.push(t),this.windows.set(e,r),{allowed:!0})}usage(e){let t=Date.now(),s=this.windows.get(e)||[];return{lastMinute:s.filter(n=>n>t-6e4).length,lastHour:s.filter(n=>n>t-36e5).length}}};var Ne={totalBudget:6e3,layerBudgets:{channel:200,scope:200,landscape:800,identity:200,bootstrap:500,intent:200,artifacts:500,memory:600,history:1200,"cross-chat":800,wiki:1e3}},se=4;function ne(c,e=Ne){let t=Ue(c,e);t.sort((i,a)=>i.priority-a.priority);let s=[],n=0,r=e.totalBudget*se;for(let i of t){if(!i.content)continue;let a=i.maxTokens*se,o=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(n+o.length>r){let l=r-n;l>100&&s.push(o.slice(0,l)+"...");break}s.push(o),n+=o.length}return s.join(`
|
|
114
|
+
|
|
115
|
+
`)}function Ue(c,e){let t=(a,o)=>e.layerBudgets?.[a]??o,s=[];s.push(He(c,t("channel",200))),s.push(Be(c,t("scope",200))),c.landscape&&s.push({name:"landscape",priority:3,maxTokens:t("landscape",350),content:c.landscape,tags:["landscape","world-model"]}),c.systemPrompt&&s.push({name:"identity",priority:4,maxTokens:t("identity",200),content:c.systemPrompt.split(`
|
|
116
|
+
`)[0],tags:["identity",c.agentId]}),c.bootstrapContext&&s.push({name:"bootstrap",priority:4.5,maxTokens:t("bootstrap",500),content:c.bootstrapContext,tags:["bootstrap","identity","personality"]});let n=qe(c.message);n.length&&s.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${n.join(", ")}]`,tags:n});let r=[];c.replyToText&&r.push(`[Replying to]: ${c.replyToText.slice(0,300)}`),c.mediaPath&&(r.push(`[Attached file: ${c.mediaPath}]`),r.push(`[File type: ${c.mediaType||"unknown"}]`),c.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):c.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),c.issueMR&&r.push(`[${c.issueMR.type} #${c.issueMR.iid}: ${c.issueMR.title}]`),r.length&&s.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
117
|
+
`),tags:["artifacts",...c.mediaType?["media"]:[]]}),c.skillInjection&&s.push({name:"skills",priority:6.2,maxTokens:t("skills",2e3),content:c.skillInjection,tags:["skills","auto-inject"]}),c.patternContext&&s.push({name:"patterns",priority:6.3,maxTokens:t("patterns",400),content:c.patternContext,tags:["patterns","behavioral","self-improving"]}),c.memoryContext&&s.push({name:"memory",priority:6.5,maxTokens:t("memory",600),content:c.memoryContext,tags:["memory","persistent"]});let i=c.groupHistory||c.sessionHistory;return i&&s.push({name:"history",priority:7,maxTokens:t("history",1200),content:i,tags:["history","conversation"]}),c.crossChatContext&&s.push({name:"cross-chat",priority:7,maxTokens:t("cross-chat",800),content:c.crossChatContext,tags:["history","cross-chat"]}),c.wikiContext&&s.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:c.wikiContext,tags:["wiki","knowledge"]}),s}function He(c,e){let t=[`Channel: ${c.channel}`],s=[],n=[c.channel];switch(c.channel){case"telegram":c.agentHandle&&t.push(`Your handle: ${c.agentHandle}`),t.push(`From: ${c.sender}`),c.senderId&&t.push(`Telegram user ID: ${c.senderId}`),c.senderUsername&&t.push(`Username: @${c.senderUsername}`),s.push("Format responses using Telegram-compatible markdown"),s.push("Be brief \u2014 2-4 sentences max for the main point. Humans scan, not read"),s.push("Lead with the action or answer, skip preamble");break;case"whatsapp":t.push(`From: ${c.sender}`),s.push("Be brief \u2014 2-3 sentences max. WhatsApp is mobile-first"),s.push("No rich formatting \u2014 plain text only"),s.push("Lead with the action or answer, skip preamble");break;case"gitlab":t.push(`From: ${c.sender}`),s.push("Reply as a short, actionable GitLab comment \u2014 3-5 lines for the main message"),s.push("Do NOT mention Telegram handles \u2014 they don't work on GitLab"),s.push("Do NOT delegate to other agents"),s.push("Reference issues with #IID and merge requests with !IID"),s.push("Put verbose details (logs, full commands, step-by-step) inside collapsible sections: <details><summary>Title</summary>\\n\\ncontent\\n</details>"),s.push("Never narrate what you are about to do \u2014 just do it and report the result"),n.push("code-review");break;case"discord":t.push(`From: ${c.sender}`),s.push("Use Discord markdown for formatting"),s.push("Be brief \u2014 2-4 sentences for the main point");break;default:c.channel.startsWith("webhook:")&&(s.push("This is an automated event \u2014 respond with actionable steps"),n.push("webhook","automated"))}return s.length&&(t.push(""),t.push("[Rules]"),t.push(...s.map(r=>`- ${r}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
118
|
+
`),tags:n,rules:s}}function Be(c,e){let t=[],s=[];if(c.channelScope==="group"&&c.groupName?(t.push(`Group: ${c.groupName}`),s.push("group",c.groupName)):c.channelScope==="project"&&c.projectPath?(t.push(`Project: ${c.projectPath}`),s.push("project",c.projectPath)):c.channelScope==="personal"&&(t.push("Direct message"),s.push("dm")),c.channelMeta){let n=c.channelMeta;if(n.agents?.length&&(t.push(`[Verified bots in this chat: ${n.agents.map(r=>r.handle||r.name||r.id).join(", ")}]`),t.push("Only mention these agents as group members \u2014 do NOT assume others are present.")),n.project&&t.push(`Project: ${n.project}`),n.issue&&t.push(`${n.issue.type} #${n.issue.iid}${n.issue.title?`: ${n.issue.title}`:""}`),n.facts?.length)for(let r of n.facts)t.push(`\u2022 ${r}`)}return{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
119
|
+
`),tags:s}}function qe(c){let e=[],t=c.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}import{readFileSync as Qe,writeFileSync as re,appendFileSync as Ke,mkdirSync as Je,existsSync as ie}from"fs";import{resolve as q}from"path";var oe=200,Ge=7,_=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=q(e,".agentx/memory"),ie(this.memoryDir)||Je(this.memoryDir,{recursive:!0})}filePath(e){return q(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};Ke(this.filePath(e),JSON.stringify(s)+`
|
|
120
|
+
`)}getAll(e){let t=this.filePath(e);if(!ie(t))return[];try{return Qe(t,"utf-8").split(`
|
|
121
|
+
`).filter(n=>n.trim()).map(n=>{try{return JSON.parse(n)}catch{return null}}).filter(n=>n!==null)}catch{return[]}}findRelevant(e,t,s=8){let n=this.getAll(t);if(n.length===0)return[];let r=n.map(g=>`${g.keywords.join(" ")} ${g.content}`),i=q(this.memoryDir,`${t}_bm25_cache.json`),a=C(r,i),o=D(e,a),l=new Map(o.map(g=>[g.docIndex,g.score])),p=n.map((g,m)=>{let f=l.get(m)??0;return g.category==="secret"&&(f+=2),g.category==="commitment"&&(f+=1),{memory:g,score:f}}).filter(g=>g.score>0);if(p.length===0)return n.slice(-s);let h=p.sort((g,m)=>m.score-g.score).slice(0,s).map(g=>g.memory);if(h.length>0)try{this.recordAccess(t,h.map(g=>g.id))}catch{}return h}buildContext(e){if(e.length===0)return"";let t=["[Agent Memory \u2014 persistent facts from past conversations]"],s=t[0].length;for(let n of e){let i=!n.source.chatId.startsWith("-")&&/^\d+$/.test(n.source.chatId)?"DM":n.source.chatId,a=`- [${n.category}] ${n.content} (${i}, ${n.source.date})`;if(s+a.length>2400)break;t.push(a),s+=a.length}return t.push("[End Memory]"),t.join(`
|
|
122
|
+
`)}recordAccess(e,t){if(t.length===0)return;let s=this.getAll(e),n=new Set(t),r=!1;for(let i of s)if(n.has(i.id)){i.accessCount=(i.accessCount||0)+1,i.lastAccessed=new Date().toISOString();let a=i.intervalDays||1;i.intervalDays=Math.min(a*2,30),i.nextReview=new Date(Date.now()+i.intervalDays*864e5).toISOString(),r=!0}r&&re(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
|
|
123
|
+
`)+`
|
|
124
|
+
`)}getDueForReview(e,t=5){let s=this.getAll(e),n=Date.now();return s.filter(r=>r.category==="task-state"?!1:r.nextReview?new Date(r.nextReview).getTime()<=n:!0).sort((r,i)=>!r.nextReview&&i.nextReview?-1:r.nextReview&&!i.nextReview?1:r.nextReview&&i.nextReview?new Date(r.nextReview).getTime()-new Date(i.nextReview).getTime():(r.accessCount||0)-(i.accessCount||0)).slice(0,t)}buildRecallContext(e){let t=this.getDueForReview(e,5);if(t.length===0)return"";let s=["[Memory Recall \u2014 facts due for review, verify they are still accurate]"];for(let n of t){let r=Math.round((Date.now()-new Date(n.createdAt).getTime())/864e5);s.push(`- [${n.category}] ${n.content} (${r}d old, accessed ${n.accessCount||0}x)`)}return s.push("[If any fact is outdated, note the correction. Otherwise, acknowledge recall.]"),s.join(`
|
|
125
|
+
`)}hasSimilar(e,t){let s=this.getAll(e),r=t.toLowerCase().split(/\s+/).filter(i=>i.length>3);return s.some(i=>{let a=i.content.toLowerCase();return r.filter(l=>a.includes(l)).length>=r.length*.7})}prune(e){let t=this.getAll(e);if(t.length===0)return;let s=Date.now(),n=Ge*24*60*60*1e3;t=t.filter(i=>i.category==="task-state"&&i.expiresAt?new Date(i.expiresAt).getTime()>s:i.category==="task-state"&&!i.expiresAt?s-new Date(i.createdAt).getTime()<n:!0),t.length>oe&&(t=t.slice(-oe));let r=this.filePath(e);re(r,t.map(i=>JSON.stringify(i)).join(`
|
|
126
|
+
`)+`
|
|
127
|
+
`)}};var E=class{queues=new Map;defaultMode;constructor(e="collect"){this.defaultMode=e}key(e,t,s){return`${e}:${t}:${s}`}getOrCreate(e,t,s){let n=this.key(e,t,s);return this.queues.has(n)||this.queues.set(n,{mode:this.defaultMode,pending:[],running:!1}),this.queues.get(n)}setMode(e,t,s,n){this.getOrCreate(e,t,s).mode=n}onFlush(e,t,s,n){this.getOrCreate(e,t,s).onFlush=n}isBusy(e,t,s){return this.getOrCreate(e,t,s).running}markRunning(e,t,s){let n=this.getOrCreate(e,t,s);return n.running?!1:(n.running=!0,!0)}enqueue(e,t,s,n){let r=this.getOrCreate(e,t,s);if(!r.running)return null;switch(r.mode){case"drop":return"drop";case"collect":case"followup":return r.pending.push(n),r.mode}}async markDone(e,t,s){let n=this.getOrCreate(e,t,s);if(n.running=!1,n.pending.length===0)return[];let r=[...n.pending];switch(n.pending=[],n.mode){case"collect":{let i={text:r.map(a=>`[${a.sender}, ${new Date(a.timestamp).toISOString().slice(11,16)}]: ${a.text}`).join(`
|
|
128
|
+
`),sender:r[r.length-1].sender,timestamp:Date.now(),channel:r[0].channel,chatId:r[0].chatId,originalContext:r[r.length-1].originalContext};return n.onFlush&&await n.onFlush([i]),[i]}case"followup":return n.onFlush&&await n.onFlush(r),r;case"drop":return[];default:return r}}pendingCount(e,t,s){return this.getOrCreate(e,t,s).pending.length}clear(e,t,s){let n=this.key(e,t,s);this.queues.delete(n)}stats(){return Array.from(this.queues.entries()).map(([e,t])=>({key:e,mode:t.mode,pending:t.pending.length,running:t.running}))}};import{readFileSync as Ye,writeFileSync as ae,appendFileSync as Xe,mkdirSync as Ve,existsSync as ce}from"fs";import{resolve as Q}from"path";var le=50,ze="claude-haiku-4-20250514",Ze=`You are a behavioral pattern extractor. Given a conversation between a user and an AI agent, extract behavioral patterns \u2014 lessons about HOW to approach tasks, not facts about the world.
|
|
129
|
+
|
|
130
|
+
Extract patterns like:
|
|
131
|
+
- "When asked about X, the approach that works is Y"
|
|
132
|
+
- "User prefers Z style of communication"
|
|
133
|
+
- "For deployment tasks, always check A before doing B"
|
|
134
|
+
- "This codebase uses pattern X, so generate code following X"
|
|
135
|
+
|
|
136
|
+
SKIP:
|
|
137
|
+
- Factual information (names, dates, URLs)
|
|
138
|
+
- Routine task completions
|
|
139
|
+
- Greetings or small talk
|
|
140
|
+
|
|
141
|
+
Output a JSON array:
|
|
142
|
+
[{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
|
|
143
|
+
|
|
144
|
+
If nothing worth extracting, output: []`,F=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=Q(e,".agentx/patterns"),ce(this.patternsDir)||Ve(this.patternsDir,{recursive:!0})}filePath(e){return Q(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ce(t))return[];try{return Ye(t,"utf-8").split(`
|
|
145
|
+
`).filter(s=>s.trim()).map(s=>{try{return JSON.parse(s)}catch{return null}}).filter(s=>s!==null)}catch{return[]}}addPattern(e,t){let s={...t,id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,accessCount:0,createdAt:new Date().toISOString()};Xe(this.filePath(e),JSON.stringify(s)+`
|
|
146
|
+
`)}findRelevant(e,t,s=5){let n=this.getAll(t);if(n.length===0)return[];let r=n.map(d=>`${d.context} ${d.pattern}`),i=Q(this.patternsDir,`${t}_bm25_cache.json`),a=C(r,i),l=D(e,a).slice(0,s).map(d=>n[d.docIndex]).filter(d=>d.confidence>=.3);return l.length>0&&this.recordAccess(t,l.map(d=>d.id)),l}buildContext(e){if(e.length===0)return"";let t=["[Learned Patterns \u2014 behavioral lessons from past interactions]"];for(let s of e)t.push(`- ${s.pattern} (context: ${s.context}, confidence: ${Math.round(s.confidence*100)}%)`);return t.push("[Apply these patterns when relevant to the current task]"),t.join(`
|
|
147
|
+
`)}hasSimilar(e,t){let s=this.getAll(e),n=t.toLowerCase().split(/\s+/).filter(r=>r.length>3);return s.some(r=>{let i=r.pattern.toLowerCase();return n.filter(o=>i.includes(o)).length>=n.length*.6})}recordAccess(e,t){let s=this.getAll(e),n=new Set(t),r=!1;for(let i of s)n.has(i.id)&&(i.accessCount++,i.lastUsed=new Date().toISOString(),i.confidence=Math.min(1,i.confidence+.05),r=!0);r&&ae(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
|
|
148
|
+
`)+`
|
|
149
|
+
`)}prune(e){let t=this.getAll(e);t.length<=le||(t.sort((s,n)=>n.confidence*n.accessCount-s.confidence*s.accessCount),t=t.slice(0,le),ae(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
|
|
150
|
+
`)+`
|
|
151
|
+
`))}};async function de(c,e,t,s,n){if(e.length<30&&t.length<100)return;let{createProvider:r}=await import("./providers-G3WZ4RVJ.js"),o=(await r("claude").generate([{role:"system",content:Ze},{role:"user",content:`User: ${e.slice(0,500)}
|
|
152
|
+
|
|
153
|
+
Agent: ${t.slice(0,1e3)}`}],{model:ze,maxTokens:512})).content.trim().match(/\[[\s\S]*\]/);if(!o)return;let l=JSON.parse(o[0]);if(!(!Array.isArray(l)||l.length===0)){for(let d of l)n.hasSimilar(c,d.pattern)||n.addPattern(c,{agentId:c,pattern:d.pattern,context:d.context,confidence:d.confidence||.5,source:s});Math.random()<.05&&n.prune(c)}}var ue;function Ht(c){ue=c}function Bt(){return ue}var ge=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;patternStore;rateLimiter;tokenTracker;landscape;messageQueue;activeSouls=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){this.log=t,this.config=e,this.providers=e.providers,this.sessions=new R,this.wikiHub=new M(void 0,void 0,"unified"),this.memoryStore=new _,this.patternStore=new F,this.rateLimiter=new j,this.tokenTracker=new J,this.messageQueue=new E;for(let[s,n]of Object.entries(e.agents))this.agents.set(s,{id:s,def:n,activeTasks:0,totalTasks:0,errors:0})}setLandscape(e){this.landscape=e}getAgent(e){return this.agents.get(e)?.def}findByMention(e){let t=e.toLowerCase(),s,n=0;for(let[r,i]of this.agents)for(let a of i.def.mentions){let o=a.toLowerCase();t.includes(o)&&o.length>n&&(s=r,n=o.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[n,r]of this.agents)for(let i of r.def.mentions)if(t.includes(i.toLowerCase())){s.push(n);break}return s}getWikiHub(){return this.wikiHub}buildPeerList(e,t){let s=[];for(let[n,r]of this.agents)n!==e&&s.push({name:r.def.name,handle:this.getChannelHandle(n,t),role:r.def.systemPrompt?.split(`
|
|
154
|
+
`)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(n=>n.startsWith("@")):s.mentions[0]}async execute(e,t){let s=this.agents.get(e.agentId);if(!s)return{content:"",error:`Unknown agent: ${e.agentId}`};let n=e.context?.channel||"api",r=e.context?.chatId||e.context?.group||e.context?.sender||"default";if(s.activeTasks>=s.def.maxConcurrent){let u=s.def.queueMode||"collect",w=this.messageQueue.enqueue(e.agentId,n,r,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:n,chatId:r,originalContext:e.context});if(w==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(w){let $=this.messageQueue.pendingCount(e.agentId,n,r);return this.log(`[${e.agentId}] busy, message queued (mode: ${w}, pending: ${$})`),{content:"",error:`__queued__:${w}:${$}`}}}let i=this.rateLimiter.check(e.agentId);if(!i.allowed)return this.log(`[${e.agentId}] ${i.reason}`),{content:"",error:i.reason};s.activeTasks++,s.totalTasks++,s.lastActive=new Date,this.messageQueue.markRunning(e.agentId,n,r),this.log(`[${e.agentId}] executing task (${s.activeTasks}/${s.def.maxConcurrent})`);let a=e.context?.channel||"api",o=e.context?.chatId||e.context?.group||e.context?.sender||"default",l=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,a,o,l,e.message);let d=this.wikiHub.getAgentWiki(e.agentId),p=d.findRelevant(e.message,e.agentId,3),h=d.buildContext(p),g=this.memoryStore.findRelevant(e.message,e.agentId,8),m=this.memoryStore.buildContext(g),f=this.patternStore.findRelevant(e.message,e.agentId,5),b=this.patternStore.buildContext(f),k="";try{let{loadLocalSkills:u,getAutoInjectSkills:w}=await import("./loader-YQE6XJBT.js"),$=await u(s.def.workspace);k=w($,e.message)}catch{}let W=s.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,a,o):void 0;W&&this.sessions.isSessionStale(e.agentId,a,o)&&(this.log(`[${e.agentId}] session stale for ${a}:${o}, starting fresh`),this.sessions.clearClaudeSessionId(e.agentId,a,o),W=void 0);try{let u=await this.sessions.compactIfNeeded(e.agentId,a,o,this.memoryStore);if(u.compacted){let w=u.qualityScore??"?",$=u.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${a}:${o} (quality: ${w}%, ${$} entities lost)`),u.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${u.lostEntities.slice(0,5).join(", ")}`),u.drift){let I=u.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${I.overallScore} (lexicon=${I.lexiconDecay}, tools=${I.toolShift}, semantic=${I.semanticDrift})`),I.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${I.lostWords.slice(0,5).join(", ")}`)}W=void 0}}catch(u){this.log(`[${e.agentId}] compaction failed (non-fatal): ${u.message}`)}let he=W?void 0:this.sessions.buildHistoryContext(e.agentId,a,o),me=this.sessions.getCrossSessionSummary(e.agentId,a,o),N=`${e.agentId}:${a}:${o}`,P=X(e.message);P&&(P==="default"?(this.activeSouls.delete(N),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(N,P),this.log(`[${e.agentId}] Soul switched to: ${P}`)));let pe=this.activeSouls.get(N),fe=G(s.def.workspace,pe),ye=Y(fe),we={channel:a,channelScope:e.context?.group?"group":a==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:s.def.name,agentHandle:this.getChannelHandle(e.agentId,a),systemPrompt:s.def.systemPrompt,sender:l,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,bootstrapContext:ye||void 0,patternContext:b||void 0,skillInjection:k||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:he,memoryContext:m||void 0,crossChatContext:me||void 0,wikiContext:h,message:e.message},be=ne(we);try{let u=await z(s.def,e,this.providers,t,be,W);if(u.error)s.errors++,this.log(`[${e.agentId}] error: ${u.error}`);else{if(this.sessions.addAgentMessage(e.agentId,a,o,u.content),u.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,a,o,u.claudeSessionId),u.content.length>50){try{let w=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:w,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:a,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
155
|
+
|
|
156
|
+
Agent: ${u.content}`})}catch{}K(e.agentId,e.message,u.content,{channel:a,chatId:o,sender:l},this.memoryStore).catch(()=>{}),de(e.agentId,e.message,u.content,{channel:a,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}this.tokenTracker.record(e.agentId,u.duration||0,u.usage,e.message.length,u.content.length,!1,s.def.model),this.log(`[${e.agentId}] completed in ${u.duration}ms`+(u.tokensUsed?` (${u.tokensUsed} tokens)`:""))}return u}catch(u){return s.errors++,this.log(`[${e.agentId}] unexpected error: ${u.message}`),{content:"",error:u.message}}finally{s.activeTasks--,this.messageQueue.markDone(e.agentId,n,r).then(u=>{if(u.length!==0){this.log(`[${e.agentId}] flushing ${u.length} queued message(s)`);for(let w of u)this.execute({message:w.text,agentId:e.agentId,context:w.originalContext||{channel:w.channel,sender:w.sender,chatId:w.chatId}}).catch($=>{this.log(`[${e.agentId}] queued message failed: ${$.message}`)})}}).catch(u=>{this.log(`[${e.agentId}] queue flush failed: ${u.message}`)})}}list(){return Array.from(this.agents.values()).map(e=>({id:e.id,name:e.def.name,tier:e.def.tier,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive}))}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{ke as a,Ae as b,De as c,z as d,T as e,M as f,Ht as g,Bt as h,ge as i};
|
|
157
|
+
//# sourceMappingURL=chunk-VH23CDHL.js.map
|