agentix-cli 0.13.0 → 0.14.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.
Files changed (48) hide show
  1. package/README.md +50 -493
  2. package/dist/{agent-5KIMJI3F.js → agent-DW3NYIIL.js} +2 -2
  3. package/dist/board-dashboard-6TKE6NMV.js +1435 -0
  4. package/dist/board-dashboard-6TKE6NMV.js.map +1 -0
  5. package/dist/chunk-6U2XOQHU.js +7 -0
  6. package/dist/chunk-6U2XOQHU.js.map +1 -0
  7. package/dist/chunk-DYOBFJLX.js +11 -0
  8. package/dist/chunk-DYOBFJLX.js.map +1 -0
  9. package/dist/chunk-ITZEVXZ4.js +2 -0
  10. package/dist/chunk-ITZEVXZ4.js.map +1 -0
  11. package/dist/chunk-M33CB2H4.js +6 -0
  12. package/dist/chunk-M33CB2H4.js.map +1 -0
  13. package/dist/chunk-NJR5WF5E.js +5 -0
  14. package/dist/chunk-NJR5WF5E.js.map +1 -0
  15. package/dist/chunk-O72LPMBR.js +12 -0
  16. package/dist/chunk-O72LPMBR.js.map +1 -0
  17. package/dist/chunk-RB73FZXJ.js +133 -0
  18. package/dist/chunk-RB73FZXJ.js.map +1 -0
  19. package/dist/{chunk-VH23CDHL.js → chunk-UPT2UMF6.js} +42 -40
  20. package/dist/chunk-UPT2UMF6.js.map +1 -0
  21. package/dist/{chunk-D6EDMQRV.js → chunk-XVYMZ4M7.js} +3 -3
  22. package/dist/cli.js +54 -48
  23. package/dist/cli.js.map +1 -1
  24. package/dist/config-7QJ2QJIC.js +2 -0
  25. package/dist/config-mutator-GAEVGHDD.js +2 -0
  26. package/dist/index.d.ts +670 -69
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/registry-YVAG4EO5.js +2 -0
  30. package/dist/registry-YVAG4EO5.js.map +1 -0
  31. package/dist/{usage-dashboard-2TJQBFSH.js → usage-dashboard-M7AFIGMJ.js} +2 -2
  32. package/package.json +9 -1
  33. package/dist/chunk-34UAFPK4.js +0 -10
  34. package/dist/chunk-34UAFPK4.js.map +0 -1
  35. package/dist/chunk-CJ45Y2IR.js +0 -12
  36. package/dist/chunk-CJ45Y2IR.js.map +0 -1
  37. package/dist/chunk-T25UEXVK.js +0 -126
  38. package/dist/chunk-T25UEXVK.js.map +0 -1
  39. package/dist/chunk-VH23CDHL.js.map +0 -1
  40. package/dist/chunk-WJ6ZF6EZ.js +0 -6
  41. package/dist/chunk-WJ6ZF6EZ.js.map +0 -1
  42. package/dist/config-HAD5E4YX.js +0 -2
  43. package/dist/registry-CDWY7CLL.js +0 -2
  44. /package/dist/{agent-5KIMJI3F.js.map → agent-DW3NYIIL.js.map} +0 -0
  45. /package/dist/{chunk-D6EDMQRV.js.map → chunk-XVYMZ4M7.js.map} +0 -0
  46. /package/dist/{config-HAD5E4YX.js.map → config-7QJ2QJIC.js.map} +0 -0
  47. /package/dist/{registry-CDWY7CLL.js.map → config-mutator-GAEVGHDD.js.map} +0 -0
  48. /package/dist/{usage-dashboard-2TJQBFSH.js.map → usage-dashboard-M7AFIGMJ.js.map} +0 -0
@@ -1,28 +1,28 @@
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(`
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
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(`
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
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=`
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
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
16
  `+a;if(n+o.length>t)break;s.push(o),n+=o.length}return s.push(`
17
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}
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
20
 
21
- `;x(s)||v(s,`# Wiki Log
21
+ `;S(s)||$(s,`# Wiki Log
22
22
 
23
23
  Chronological record of all wiki operations.
24
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
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
26
 
27
27
  A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
28
28
  structure emerges from data. The wiki is a compounding artifact.
@@ -103,29 +103,29 @@ Clients: ClientA (enterprise), ClientB (startup).
103
103
  Infrastructure: local dev machine, cloud server.
104
104
  We use GitLab for version control.
105
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(`
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
108
 
109
109
  `);return`/wiki absorb
110
110
 
111
111
  There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
112
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(`
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
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(`
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
123
  `)+`
124
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(`
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
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.
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
129
 
130
130
  Extract patterns like:
131
131
  - "When asked about X, the approach that works is Y"
@@ -141,17 +141,19 @@ SKIP:
141
141
  Output a JSON array:
142
142
  [{"pattern":"the behavioral lesson","context":"when this applies","confidence":0.5}]
143
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(`
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
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(`
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
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)}
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
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}
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
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
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