agentix-cli 0.14.0 → 0.15.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 +64 -34
- package/dist/agent-LRSSVFDR.js +2 -0
- package/dist/board-dashboard-DAPHL6W2.js +4508 -0
- package/dist/board-dashboard-DAPHL6W2.js.map +1 -0
- package/dist/chunk-3XULOWYB.js +199 -0
- package/dist/chunk-3XULOWYB.js.map +1 -0
- package/dist/{chunk-ZRYBSI5G.js → chunk-7MBTMCKY.js} +2 -2
- package/dist/{chunk-XVYMZ4M7.js → chunk-AU37OREL.js} +5 -5
- package/dist/chunk-B4Q4X7D5.js +6 -0
- package/dist/chunk-B4Q4X7D5.js.map +1 -0
- package/dist/chunk-CXY2RYNI.js +11 -0
- package/dist/chunk-CXY2RYNI.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/chunk-HLRVDCNH.js +5 -0
- package/dist/{chunk-NJR5WF5E.js.map → chunk-HLRVDCNH.js.map} +1 -1
- package/dist/chunk-IEVEMKAI.js +168 -0
- package/dist/chunk-IEVEMKAI.js.map +1 -0
- package/dist/{chunk-O72LPMBR.js → chunk-RB7265LO.js} +2 -2
- package/dist/chunk-RGUYBH77.js +7 -0
- package/dist/chunk-RGUYBH77.js.map +1 -0
- package/dist/chunk-WVNSWBCU.js +138 -0
- package/dist/chunk-WVNSWBCU.js.map +1 -0
- package/dist/cli.js +34 -24
- package/dist/cli.js.map +1 -1
- package/dist/{compaction-7I3E5QUO.js → compaction-JBZZ7I7Y.js} +4 -4
- package/dist/config-DCJYECL4.js +2 -0
- package/dist/config-mutator-6EJHSP3Y.js +2 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{heal-OTGT5HHJ.js → heal-WKY5I4KB.js} +2 -2
- package/dist/index.d.ts +224 -1
- package/dist/index.js +11 -11
- package/dist/index.js.map +1 -1
- package/dist/loader-PTCXLJEX.js +2 -0
- package/dist/memory-extract-AD7KMRPC.js +2 -0
- package/dist/{providers-G3WZ4RVJ.js → providers-VUIWO3ZK.js} +2 -2
- package/dist/registry-5ND7GLFJ.js +2 -0
- package/dist/scheduler-FCXOXCN5.js +2 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{usage-dashboard-M7AFIGMJ.js → usage-dashboard-QX3CF6KK.js} +8 -8
- package/dist/usage-dashboard-QX3CF6KK.js.map +1 -0
- package/dist/whatsapp-state-6D6FHHD2.js +2 -0
- package/dist/whatsapp-state-6D6FHHD2.js.map +1 -0
- package/dist/workspace-setup-ZWTT42XT.js +2 -0
- package/dist/workspace-setup-ZWTT42XT.js.map +1 -0
- package/package.json +2 -1
- package/dist/agent-DW3NYIIL.js +0 -2
- package/dist/board-dashboard-6TKE6NMV.js +0 -1435
- package/dist/board-dashboard-6TKE6NMV.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-DYOBFJLX.js +0 -11
- package/dist/chunk-DYOBFJLX.js.map +0 -1
- package/dist/chunk-ITZEVXZ4.js +0 -2
- package/dist/chunk-ITZEVXZ4.js.map +0 -1
- package/dist/chunk-M33CB2H4.js +0 -6
- package/dist/chunk-M33CB2H4.js.map +0 -1
- package/dist/chunk-NJR5WF5E.js +0 -5
- package/dist/chunk-RB73FZXJ.js +0 -133
- package/dist/chunk-RB73FZXJ.js.map +0 -1
- package/dist/chunk-UPT2UMF6.js +0 -159
- package/dist/chunk-UPT2UMF6.js.map +0 -1
- package/dist/config-7QJ2QJIC.js +0 -2
- package/dist/config-mutator-GAEVGHDD.js +0 -2
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/loader-YQE6XJBT.js +0 -2
- package/dist/memory-extract-RGPUPMKU.js +0 -2
- package/dist/registry-YVAG4EO5.js +0 -2
- package/dist/usage-dashboard-M7AFIGMJ.js.map +0 -1
- package/dist/workspace-setup-QQTCJY4B.js +0 -2
- /package/dist/{agent-DW3NYIIL.js.map → agent-LRSSVFDR.js.map} +0 -0
- /package/dist/{chunk-ZRYBSI5G.js.map → chunk-7MBTMCKY.js.map} +0 -0
- /package/dist/{chunk-XVYMZ4M7.js.map → chunk-AU37OREL.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{chunk-O72LPMBR.js.map → chunk-RB7265LO.js.map} +0 -0
- /package/dist/{compaction-7I3E5QUO.js.map → compaction-JBZZ7I7Y.js.map} +0 -0
- /package/dist/{config-7QJ2QJIC.js.map → config-DCJYECL4.js.map} +0 -0
- /package/dist/{config-mutator-GAEVGHDD.js.map → config-mutator-6EJHSP3Y.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-OTGT5HHJ.js.map → heal-WKY5I4KB.js.map} +0 -0
- /package/dist/{loader-YQE6XJBT.js.map → loader-PTCXLJEX.js.map} +0 -0
- /package/dist/{memory-extract-RGPUPMKU.js.map → memory-extract-AD7KMRPC.js.map} +0 -0
- /package/dist/{providers-G3WZ4RVJ.js.map → providers-VUIWO3ZK.js.map} +0 -0
- /package/dist/{registry-YVAG4EO5.js.map → registry-5ND7GLFJ.js.map} +0 -0
- /package/dist/{workspace-setup-QQTCJY4B.js.map → scheduler-FCXOXCN5.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
package/dist/chunk-UPT2UMF6.js
DELETED
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
import{a as V,b as z,d as Z}from"./chunk-HI24KAEY.js";import{a as X}from"./chunk-DYOBFJLX.js";import{a as Y}from"./chunk-ZRYBSI5G.js";import{c as C,d as M}from"./chunk-QOYAX2FT.js";import{execa as $e}from"execa";import{execFile as Ae}from"child_process";function q(c,e,t){let s=[];if(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 ee(c,e,t,s,n,r){let i=["-p",e,"--output-format",t?"stream-json":"json"];t&&i.push("--verbose"),s&&i.push("--resume",s);let a=n||c.model;return a&&i.push("--model",a),c.permissionMode==="bypassPermissions"&&i.push("--dangerously-skip-permissions"),r&&r.trim().length>0&&i.push("--append-system-prompt",r),i}function De(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,s=typeof e.model=="string"&&e.model||typeof e.message?.model=="string"&&e.message.model||void 0;return{text:e.result||e.content||"",sessionId:e.session_id,usage:t,billedModel:s}}catch{return{text:c}}}async function Ie(c,e,t,s){let n=Date.now(),r=q(c,e,t),i=ee(c,r,!1,s,e.model,e.systemPromptAppend);try{let a=Math.max(6e4,(c.maxExecutionMinutes??20)*6e4),{stdout:o,stderr:l,exitCode:d}=await new Promise((g,u)=>{Ae("claude",i,{cwd:c.workspace,timeout:a,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"user")}},(b,P,W)=>{g({stdout:P||"",stderr:W||"",exitCode:b?b.code??1:0})}).stdin?.end()});if(!o&&d!==0){let g;return d===143?g=`Claude Code timed out after ${Math.round(a/6e4)}m (SIGTERM). Bump agent.maxExecutionMinutes for "${c.name||"this agent"}" if tasks need longer.`:g=l?.trim()||`Claude Code exited with code ${d}`,{content:"",error:g.slice(0,300),duration:Date.now()-n}}let p=De(o);return{content:p.text,duration:Date.now()-n,claudeSessionId:p.sessionId,usage:p.usage,billedModel:p.billedModel}}catch(a){return console.error(`[runtime] execFile threw: ${a.message}`),{content:"",error:a.message||"Claude Code failed",duration:Date.now()-n}}}async function Te(c,e,t,s,n){let r=Date.now(),i=q(c,e,s),a=ee(c,i,!0,n,e.model,e.systemPromptAppend),o="",l,d,p;try{let g=Math.max(6e4,(c.maxExecutionMinutes??20)*6e4),u=$e("claude",a,{cwd:c.workspace,timeout:g,reject:!1,env:process.env,buffer:!1,stdin:"ignore"});if(u.stdout){let b="";u.stdout.on("data",P=>{b+=P.toString();let W=b.split(`
|
|
4
|
-
`);b=W.pop()||"";for(let D of W)if(D.trim())try{let m=JSON.parse(D);if(m.type==="assistant"&&m.message?.content){for(let v of m.message.content)if(v.type==="text"&&v.text){let T=v.text.slice(o.length);T&&(o=v.text,t(T,o))}}if(m.type==="content_block_delta"&&m.delta?.text&&(o+=m.delta.text,t(m.delta.text,o)),m.type==="result"&&m.result){let v=(typeof m.result=="string",m.result);if(typeof v=="string"&&v.length>o.length){let T=v.slice(o.length);o=v,T&&t(T,o)}m.usage&&(d={inputTokens:m.usage.input_tokens||0,outputTokens:m.usage.output_tokens||0,cacheReadTokens:m.usage.cache_read_input_tokens||0,cacheCreateTokens:m.usage.cache_creation_input_tokens||0}),typeof m.model=="string"&&(l=m.model),typeof m.session_id=="string"&&(p=m.session_id)}m.type==="system"&&m.subtype==="init"&&(typeof m.model=="string"&&(l=m.model),typeof m.session_id=="string"&&(p=m.session_id))}catch{D.trim()&&!D.startsWith("{")&&(o+=D+`
|
|
5
|
-
`,t(D+`
|
|
6
|
-
`,o))}})}let f=await u;return!o&&f.stdout&&(o=typeof f.stdout=="string"?f.stdout:""),f.exitCode!==0&&!o?{content:"",error:(typeof f.stderr=="string"?f.stderr:"")||`Claude Code exited with code ${f.exitCode}`,duration:Date.now()-r}:{content:o,duration:Date.now()-r,usage:d,billedModel:l,claudeSessionId:p}}catch(g){return{content:o||"",error:g.message,duration:Date.now()-r,usage:d,billedModel:l,claudeSessionId:p}}}async function Ce(c,e,t,s){let n=Date.now();try{let r=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=r,a=q(c,e,s),o="",l=i({prompt:a,options:{model:e.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 Me(c,e,t,s){let n=Date.now();try{let{generate:r}=await import("./agent-DW3NYIIL.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:e.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 te(c,e,t,s,n,r){switch(c.tier){case"claude-code":return s?Te(c,e,s,n,r):Ie(c,e,n,r);case"sdk":{let i=c.provider||"claude",a=t[i]?.apiKey;return a?Ce(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 Me(c,e,a,n)}default:return{content:"",error:`Unknown tier: ${c.tier}`}}}import{readFileSync as se,writeFileSync as We,mkdirSync as Re,existsSync as ne,readdirSync as Pe}from"fs";import{resolve as Q}from"path";var Oe=12e3,re=30,_e=120,Le="[Compacted conversation summary";function je(c){let e=c.slice(11,16),t=e.slice(0,2),s=parseInt(e.slice(3,5),10);if(Number.isNaN(s))return e;let n=Math.floor(s/15)*15;return`${t}:${n.toString().padStart(2,"0")}`}var L=class{sessionsDir;cache=new Map;staleMinutes;constructor(e=process.cwd(),t={}){this.sessionsDir=Q(e,".agentx/sessions"),ne(this.sessionsDir)||Re(this.sessionsDir,{recursive:!0}),this.staleMinutes=Math.max(1,t.staleMinutes??_e)}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 Q(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(ne(r))try{let o=JSON.parse(se(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})]`],i="";for(let a of n.messages){let o=je(a.timestamp);o!==i&&(r.push(`\u2014 ${o} \u2014`),i=o);let l=a.name||(a.role==="user"?"User":"Agent");r.push(`${l}: ${a.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()>this.staleMinutes*60*1e3:!1}getCrossSessionSummary(e,t,s){let n=new Date().toISOString().slice(0,10),r=this.sessionKey(e,t,s);try{let i=Pe(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(se(Q(this.sessionsDir,o),"utf-8"));if(l.id===r||l.messages.length===0)continue;let d=l.messages.slice(-4),g=!l.chatId.startsWith("-")&&/^\d+$/.test(l.chatId)?"DM":l.chatId,u=d.map(f=>` [${f.timestamp.slice(11,16)}] ${f.name||f.role}: ${f.content.slice(0,200)}`);a.push(`From ${g} (${l.channel}):
|
|
10
|
-
${u.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(Le)}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>re&&(e.messages=e.messages.slice(-re));let t=e.messages.reduce((s,n)=>s+n.content.length,0);for(;t>Oe&&e.messages.length>2;){let s=e.messages.shift();t-=s.content.length}}save(e){try{let t=this.sessionFile(e.id);We(t,JSON.stringify(e,null,2))}catch{}}};import{readFileSync as I,writeFileSync as $,appendFileSync as Ee,existsSync as S,mkdirSync as j,readdirSync as E,statSync as Ne}from"fs";import{resolve as y,join as Fe,relative as A,dirname as Ue}from"path";var R=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,j(this.rawDir,{recursive:!0}),j(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),$(s,n.join(`
|
|
13
|
-
`)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!S(this.rawDir))return[];let t=E(this.rawDir).filter(n=>n.endsWith(".md")).sort(),s=[];for(let n of t){let r=I(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),j(Ue(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),$(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(!S(t))return;let s=I(t,"utf-8"),n=new Date().toISOString().replace(/[:.]/g,"-"),r=y(this.baseDir,"_versions",e.replace(/\.md$/,""));j(r,{recursive:!0}),$(y(r,`${n}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!S(t))return[];try{return E(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=I(n.path,"utf-8"),i=y(this.baseDir,e);return this.saveVersion(e,i),$(i,r),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!S(t))return null;let s=I(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=A(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,g=>{if(!g.endsWith(".md"))return;let u=A(this.baseDir,g);if(u.startsWith("raw/")||u.startsWith("_"))return;let f=this.readArticle(u);!f||!this.canRead(f.meta,t)||r.push(f)}),r.length===0)return[];let i=r.map(g=>g.content),a=y(this.baseDir,"_bm25_cache.json"),o=M(i,a),l=C(e,o),d=new Map(l.map(g=>[g.docIndex,g.score]));return r.map((g,u)=>{let f=d.get(u)??0;return g.meta.title.toLowerCase().includes(n)&&(f+=10),g.meta.tags?.some(b=>b.toLowerCase().includes(n))&&(f+=5),{article:g,score:f}}).filter(g=>g.score>0).sort((g,u)=>u.score-g.score).slice(0,s).map(g=>g.article)}findRelevant(e,t,s=3){let n=[];if(this.walkDir(this.baseDir,l=>{if(!l.endsWith(".md"))return;let d=A(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=M(r,i);return C(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=A(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 g=p.replace(/\[\[|\]\]/g,"");t.set(g,(t.get(g)||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()};$(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 $(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=A(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=S(this.rawDir)?E(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
|
-
`;S(s)||$(s,`# Wiki Log
|
|
22
|
-
|
|
23
|
-
Chronological record of all wiki operations.
|
|
24
|
-
|
|
25
|
-
`),Ee(s,r)}getLog(e=20){let t=y(this.baseDir,"log.md");return S(t)?I(t,"utf-8").split(/^## /m).filter(r=>r.startsWith("[")).slice(-e).map(r=>r.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if(S(e))return;$(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=A(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let n=I(t,"utf-8"),r=this.extractWikilinks(n);for(let i of r)e[i]||(e[i]=[]),e[i].push(s)}),$(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!S(t))return[];try{return JSON.parse(I(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=A(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(u=>u.toLowerCase()),d=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(f=>f.trim().toLowerCase())),p=[...l,...d],g=n.filter(u=>p.includes(u)).length;g>0&&r.push({article:o,score:g})}),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=A(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 S(e)?I(e,"utf-8"):null}setWorldview(e){$(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=A(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=A(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(S(e))for(let s of E(e)){let n=Fe(e,s);Ne(n).isDirectory()?this.walkDir(n,t):t(n)}}};import{resolve as K}from"path";import{existsSync as Be,readdirSync as He,mkdirSync as qe}from"fs";var O=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=K(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki-hub]"),s="graph"){this.baseDir=e,this.agentsDir=K(e,"agents"),this.mode=s,this.log=t,qe(this.agentsDir,{recursive:!0}),this.sharedStore=new R(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=K(this.agentsDir,e,this.mode),n=new R(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(Be(this.agentsDir))for(let s of He(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 N=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 Qe={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}},ie=4;function oe(c,e=Qe){let t=Ke(c,e);t.sort((i,a)=>i.priority-a.priority);let s=[],n=0,r=e.totalBudget*ie;for(let i of t){if(!i.content)continue;let a=i.maxTokens*ie,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 Ke(c,e){let t=(a,o)=>e.layerBudgets?.[a]??o,s=[];s.push(Je(c,t("channel",200))),s.push(Ge(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=Ye(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 Je(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 Ge(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 Ye(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 Xe,writeFileSync as ae,appendFileSync as Ve,mkdirSync as ze,existsSync as ce}from"fs";import{resolve as J}from"path";var le=200,Ze=7,F=class{memoryDir;constructor(e=process.cwd()){this.memoryDir=J(e,".agentx/memory"),ce(this.memoryDir)||ze(this.memoryDir,{recursive:!0})}filePath(e){return J(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()};Ve(this.filePath(e),JSON.stringify(s)+`
|
|
120
|
-
`)}getAll(e){let t=this.filePath(e);if(!ce(t))return[];try{return Xe(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(u=>`${u.keywords.join(" ")} ${u.content}`),i=J(this.memoryDir,`${t}_bm25_cache.json`),a=M(r,i),o=C(e,a),l=new Map(o.map(u=>[u.docIndex,u.score])),p=n.map((u,f)=>{let b=l.get(f)??0;return u.category==="secret"&&(b+=2),u.category==="commitment"&&(b+=1),{memory:u,score:b}}).filter(u=>u.score>0);if(p.length===0)return n.slice(-s);let g=p.sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.memory);if(g.length>0)try{this.recordAccess(t,g.map(u=>u.id))}catch{}return g}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&&ae(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=Ze*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>le&&(t=t.slice(-le));let r=this.filePath(e);ae(r,t.map(i=>JSON.stringify(i)).join(`
|
|
126
|
-
`)+`
|
|
127
|
-
`)}};var U=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 et,writeFileSync as de,appendFileSync as tt,mkdirSync as st,existsSync as ge}from"fs";import{resolve as G}from"path";var ue=50,nt="claude-haiku-4-20250514",rt=`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: []`,B=class{patternsDir;constructor(e=process.cwd()){this.patternsDir=G(e,".agentx/patterns"),ge(this.patternsDir)||st(this.patternsDir,{recursive:!0})}filePath(e){return G(this.patternsDir,`${e}.jsonl`)}getAll(e){let t=this.filePath(e);if(!ge(t))return[];try{return et(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()};tt(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=G(this.patternsDir,`${t}_bm25_cache.json`),a=M(r,i),l=C(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&&de(this.filePath(e),s.map(i=>JSON.stringify(i)).join(`
|
|
148
|
-
`)+`
|
|
149
|
-
`)}prune(e){let t=this.getAll(e);t.length<=ue||(t.sort((s,n)=>n.confidence*n.accessCount-s.confidence*s.accessCount),t=t.slice(0,ue),de(this.filePath(e),t.map(s=>JSON.stringify(s)).join(`
|
|
150
|
-
`)+`
|
|
151
|
-
`))}};async function he(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:rt},{role:"user",content:`User: ${e.slice(0,500)}
|
|
152
|
-
|
|
153
|
-
Agent: ${t.slice(0,1e3)}`}],{model:nt,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 pe;function Jt(c){pe=c}function Gt(){return pe}var me=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 L(process.cwd(),{staleMinutes:e.session.staleMinutes}),this.wikiHub=new O(void 0,void 0,"unified"),this.memoryStore=new F,this.patternStore=new B,this.rateLimiter=new N,this.tokenTracker=new X,this.messageQueue=new U;for(let[s,n]of Object.entries(e.agents))this.agents.set(s,{id:s,def:n,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let s=e.toLowerCase(),n,r=0;for(let[i,a]of this.agents)for(let o of a.def.mentions){if(t.atMentionsOnly&&!o.startsWith("@"))continue;let l=o.toLowerCase();s.includes(l)&&l.length>r&&(n=i,r=l.length)}return n}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 h=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 x=this.messageQueue.pendingCount(e.agentId,n,r);return this.log(`[${e.agentId}] busy, message queued (mode: ${w}, pending: ${x})`),{content:"",error:`__queued__:${w}:${x}`}}}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;let a={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};s.runningTasks.push(a),this.messageQueue.markRunning(e.agentId,n,r),this.log(`[${e.agentId}] executing task (${s.activeTasks}/${s.def.maxConcurrent})`);let o=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,o,l,d,e.message);let p=this.wikiHub.getAgentWiki(e.agentId),g=p.findRelevant(e.message,e.agentId,3),u=p.buildContext(g),f=this.memoryStore.findRelevant(e.message,e.agentId,8),b=this.memoryStore.buildContext(f),P=this.patternStore.findRelevant(e.message,e.agentId,5),W=this.patternStore.buildContext(P),D="";try{let{loadLocalSkills:h,getAutoInjectSkills:w}=await import("./loader-YQE6XJBT.js"),x=await h(s.def.workspace);D=w(x,e.message)}catch{}let m=s.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,o,l):void 0;m&&this.sessions.isSessionStale(e.agentId,o,l)&&(this.log(`[${e.agentId}] session stale for ${o}:${l}, starting fresh`),this.sessions.clearClaudeSessionId(e.agentId,o,l),m=void 0);try{let h=await this.sessions.compactIfNeeded(e.agentId,o,l,this.memoryStore);if(h.compacted){let w=h.qualityScore??"?",x=h.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${o}:${l} (quality: ${w}%, ${x} entities lost)`),h.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${h.lostEntities.slice(0,5).join(", ")}`),h.drift){let k=h.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${k.overallScore} (lexicon=${k.lexiconDecay}, tools=${k.toolShift}, semantic=${k.semanticDrift})`),k.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${k.lostWords.slice(0,5).join(", ")}`)}m=void 0}}catch(h){this.log(`[${e.agentId}] compaction failed (non-fatal): ${h.message}`)}let v=m?void 0:this.sessions.buildHistoryContext(e.agentId,o,l),T=this.sessions.getCrossSessionSummary(e.agentId,o,l),H=`${e.agentId}:${o}:${l}`,_=Z(e.message);_&&(_==="default"?(this.activeSouls.delete(H),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(H,_),this.log(`[${e.agentId}] Soul switched to: ${_}`)));let fe=this.activeSouls.get(H),ye=V(s.def.workspace,fe),we=z(ye),be=[s.def.systemPrompt||"",we||""].filter(h=>h.trim().length>0).join(`
|
|
155
|
-
|
|
156
|
-
`)||void 0,xe={channel:o,channelScope:e.context?.group?"group":o==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:s.def.name,agentHandle:this.getChannelHandle(e.agentId,o),systemPrompt:s.def.systemPrompt,sender:d,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,patternContext:W||void 0,skillInjection:D||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:v,memoryContext:b||void 0,crossChatContext:T||void 0,wikiContext:u,message:e.message},ve=oe(xe),Se={...e,systemPromptAppend:be};try{let h=await te(s.def,Se,this.providers,t,ve,m);if(h.error)s.errors++,this.log(`[${e.agentId}] error: ${h.error}`);else{if(this.sessions.addAgentMessage(e.agentId,o,l,h.content),h.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,o,l,h.claudeSessionId),h.content.length>50){try{let ke=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:ke,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:o,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
157
|
-
|
|
158
|
-
Agent: ${h.content}`})}catch{}Y(e.agentId,e.message,h.content,{channel:o,chatId:l,sender:d},this.memoryStore).catch(()=>{}),he(e.agentId,e.message,h.content,{channel:o,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let w=h.billedModel||e.model||s.def.model,x=e.context?.channel,k=x&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${x}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,h.duration||0,h.usage,e.message.length,h.content.length,!1,w,x,k),this.log(`[${e.agentId}] completed in ${h.duration}ms`+(h.tokensUsed?` (${h.tokensUsed} tokens)`:""))}return h}catch(h){return s.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`),{content:"",error:h.message}}finally{s.activeTasks--;let h=s.runningTasks.findIndex(w=>w.id===a.id);h!==-1&&s.runningTasks.splice(h,1),this.messageQueue.markDone(e.agentId,n,r).then(w=>{if(w.length!==0){this.log(`[${e.agentId}] flushing ${w.length} queued message(s)`);for(let x of w)this.execute({message:x.text,agentId:e.agentId,context:x.originalContext||{channel:x.channel,sender:x.sender,chatId:x.chatId}}).catch(k=>{this.log(`[${e.agentId}] queued message failed: ${k.message}`)})}}).catch(w=>{this.log(`[${e.agentId}] queue flush failed: ${w.message}`)})}}list(){return Array.from(this.agents.values()).map(e=>({id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks}))}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{Ie as a,Ce as b,Me as c,te as d,R as e,O as f,Jt as g,Gt as h,me as i};
|
|
159
|
-
//# sourceMappingURL=chunk-UPT2UMF6.js.map
|