agentix-cli 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -195,8 +195,22 @@ Total budget: 4000 tokens. Lower layers truncated if over budget.
195
195
  | `/task` | POST | `{ "agent": "id", "message": "..." }` |
196
196
  | `/mesh/task` | POST | `{ "peer": "name", "message": "..." }` |
197
197
  | `/webhook/:agentId[/:source]` | POST | Webhook callback (GitLab, GitHub, Stripe, Sentry) |
198
+ | `/v1/chat/completions` | POST | OpenAI-compatible endpoint (ElevenLabs, Cursor, any client) |
199
+ | `/llm/:agentId/v1/chat/completions` | POST | OpenAI-compatible with explicit agent |
198
200
  | `/.well-known/agent-card.json` | GET | A2A agent discovery |
199
201
 
202
+ ## OpenAI-Compatible Endpoint
203
+
204
+ Any agent can be used as an LLM backend for ElevenLabs Conversational AI, Cursor, or any OpenAI-compatible client.
205
+
206
+ ```bash
207
+ curl -X POST http://your-server:18800/v1/chat/completions \
208
+ -H "Content-Type: application/json" \
209
+ -d '{"model": "atlas", "messages": [{"role": "user", "content": "Hello"}]}'
210
+ ```
211
+
212
+ Supports streaming (`"stream": true`) with SSE. The `model` field maps to the agent ID.
213
+
200
214
  ## Three execution tiers
201
215
 
202
216
  | Tier | How | Auth | Best for |
@@ -0,0 +1,137 @@
1
+ import{i as ke,j as ve}from"./chunk-Z4GC5D6D.js";import{b as J}from"./chunk-4YCH6IZV.js";var F=class{baseUrl;token;constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.token=t}async getAgentCard(){let e=await fetch(`${this.baseUrl}/.well-known/agent-card.json`,{headers:this.headers()});if(!e.ok)throw new Error(`Failed to fetch agent card: ${e.status}`);return e.json()}async sendTask(e,t){let n=await this.rpc("tasks/send",{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t});if(n.error)throw new Error(`A2A error: ${n.error.message}`);return n.result}async*sendTaskStream(e,t){let n=JSON.stringify({jsonrpc:"2.0",id:1,method:"tasks/sendSubscribe",params:{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t}}),s=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json",Accept:"text/event-stream"},body:n});if(!s.ok||!s.body)throw new Error(`A2A stream error: ${s.status}`);let r=s.body.getReader(),i=new TextDecoder,a="";for(;;){let{done:o,value:l}=await r.read();if(o)break;a+=i.decode(l,{stream:!0});let g=a.split(`
2
+ `);a=g.pop()||"";for(let u of g)if(u.startsWith("data: "))try{let f=JSON.parse(u.slice(6));yield{state:f.state,message:f.message?.parts?.[0]?.text,final:f.final}}catch{}}}async getTask(e){let t=await this.rpc("tasks/get",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async cancelTask(e){let t=await this.rpc("tasks/cancel",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async rpc(e,t){let n=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:e,params:t})});if(!n.ok)throw new Error(`A2A HTTP error: ${n.status}`);return n.json()}headers(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};var K=class{peers=new Map;healthTimer;config;log;constructor(e,t=console.error.bind(console,"[mesh]")){this.config=e,this.log=t;for(let n of e.mesh.peers)this.peers.set(n.name,{peer:n,client:new F(n.url,n.token),healthy:!1,agents:[]})}async start(){this.log(`Mesh starting with ${this.peers.size} peer(s)`),await this.discoverAll();let e=this.config.mesh.healthCheck.interval*1e3;this.healthTimer=setInterval(()=>this.discoverAll(),e)}async stop(){this.healthTimer&&clearInterval(this.healthTimer)}async discoverAll(){let e=await Promise.allSettled(Array.from(this.peers.entries()).map(([n,s])=>this.discoverPeer(n,s))),t=Array.from(this.peers.values()).filter(n=>n.healthy).length;this.log(`Discovery complete: ${t}/${this.peers.size} peers healthy`)}async discoverPeer(e,t){let n=this.config.mesh.healthCheck.timeout*1e3;try{let s=new AbortController,r=setTimeout(()=>s.abort(),n),i=await t.client.getAgentCard();clearTimeout(r),t.healthy=!0,t.lastCheck=new Date,t.agentCard=i,t.agents=i.skills||[],this.log(`Peer "${e}" healthy: ${i.name} (${t.agents.length} skills)`)}catch(s){t.healthy=!1,t.lastCheck=new Date,this.log(`Peer "${e}" unreachable: ${s.message}`)}}async sendTask(e,t,n){let s=this.peers.get(e);if(!s)throw new Error(`Unknown peer: ${e}`);if(!s.healthy)throw new Error(`Peer "${e}" is not healthy`);let r=n||s.agents[0]?.id;if(!r)throw new Error(`Peer "${e}" has no agents`);let i=`${s.peer.url}/task`,a={"Content-Type":"application/json"};s.peer.token&&(a.Authorization=`Bearer ${s.peer.token}`);let o=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({agent:r,message:t})});if(!o.ok)throw new Error(`Peer "${e}" /task error: ${o.status}`);let l=await o.json();if(l.error)throw new Error(`Peer "${e}" agent error: ${l.error}`);return l.content||"No response"}findPeerWithSkill(e){for(let t of this.peers.values())if(t.healthy&&t.agents.some(n=>n.id===e))return t}directory(){return Array.from(this.peers.entries()).map(([e,t])=>({peer:e,peerUrl:t.peer.url,healthy:t.healthy,skills:t.agents,lastCheck:t.lastCheck}))}};import{z as h}from"zod";import{readFileSync as $e,existsSync as z}from"fs";import{resolve as q}from"path";function Je(c){let e=q(c,".env");if(!z(e))return;let t=$e(e,"utf-8");for(let n of t.split(`
3
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let i=s.slice(0,r).trim(),a=s.slice(r+1).trim();process.env[i]||(process.env[i]=a)}}var Fe=h.object({apiKey:h.string().optional(),defaultModel:h.string().optional(),baseUrl:h.string().optional()}),Ke=h.object({name:h.string(),workspace:h.string(),tier:h.enum(["claude-code","sdk","orchestrator"]).default("claude-code"),provider:h.string().optional(),model:h.string().optional(),systemPrompt:h.string().optional(),mentions:h.array(h.string()).default([]),maxConcurrent:h.number().default(1),permissionMode:h.string().default("default")}),ze=h.object({token:h.string(),agentBinding:h.string()}),qe=h.object({telegram:h.object({enabled:h.boolean().default(!1),accounts:h.record(h.string(),ze).default({}),policy:h.object({dm:h.enum(["pair","block"]).default("pair"),group:h.enum(["mention-required","all"]).default("mention-required")}).default({})}).default({}),whatsapp:h.object({enabled:h.boolean().default(!1),sessionDir:h.string().default(".agentx/whatsapp-sessions"),defaultAgent:h.string().optional(),allowFrom:h.array(h.string()).optional(),routes:h.array(h.object({contact:h.string().optional(),group:h.string().optional(),agent:h.string()})).default([])}).default({}),discord:h.object({enabled:h.boolean().default(!1),token:h.string().optional(),agentBinding:h.string().optional()}).default({}),gitlab:h.object({enabled:h.boolean().default(!1),webhookPort:h.number().default(18810),webhookSecret:h.string().optional(),host:h.string().default("https://gitlab.com"),token:h.string().optional(),routes:h.array(h.object({project:h.string(),agent:h.string()})).default([]),agentMappings:h.array(h.object({agentId:h.string(),gitlabUsernames:h.array(h.string()).default([]),keywords:h.array(h.string()).default([])})).default([])}).default({})}),Ve=h.object({enabled:h.boolean().default(!0),schedule:h.string(),timezone:h.string().default("UTC"),agent:h.string(),prompt:h.string(),timeout:h.number().default(600),model:h.string().optional(),onError:h.enum(["log","notify","disable"]).default("log")}),Xe=h.object({url:h.string(),name:h.string(),token:h.string().optional()}),Qe=h.object({enabled:h.boolean().default(!1),peers:h.array(Xe).default([]),discovery:h.enum(["static","mdns"]).default("static"),healthCheck:h.object({interval:h.number().default(60),timeout:h.number().default(10)}).default({})}),Ye=h.object({node:h.object({id:h.string(),name:h.string(),bind:h.string().default("127.0.0.1:18800")}),providers:h.record(h.string(),Fe).default({}),agents:h.record(h.string(),Ke).default({}),channels:qe.default({}),crons:h.record(h.string(),Ve).default({}),mesh:Qe.default({})});function de(c){if(typeof c=="string")return c.replace(/\$\{(\w+)\}/g,(e,t)=>process.env[t]||"");if(Array.isArray(c))return c.map(de);if(c!==null&&typeof c=="object"){let e={};for(let[t,n]of Object.entries(c))e[t]=de(n);return e}return c}function xe(c){let e=c?[c]:[q(process.cwd(),"agentx.json"),q(process.cwd(),".agentx/config.json")];Je(process.cwd());let t,n;for(let a of e)if(z(a)){t=$e(a,"utf-8"),n=a;break}if(!t||!n)throw new Error(`No config found. Create agentx.json or .agentx/config.json
4
+ Searched: ${e.join(", ")}`);let s;try{s=JSON.parse(t)}catch(a){throw new Error(`Invalid JSON in ${n}: ${a.message}`)}let r=de(s),i=Ye.safeParse(r);if(!i.success){let a=i.error.issues.map(o=>` ${o.path.join(".")}: ${o.message}`).join(`
5
+ `);throw new Error(`Config validation failed (${n}):
6
+ ${a}`)}return i.data}function Ae(c){let e=[];for(let[t,n]of Object.entries(c.agents)){if(!z(n.workspace)){e.push(`Agent "${t}": workspace not found at ${n.workspace}`);continue}if(n.tier==="claude-code"){let i=q(n.workspace,".claude");z(i)||e.push(`Agent "${t}": no .claude/ directory in workspace ${n.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let s=n.provider||"claude",r=c.providers[s];n.tier!=="claude-code"&&(!r||!r.apiKey)&&e.push(`Agent "${t}": provider "${s}" has no API key configured. Set providers.${s}.apiKey in config or use tier "claude-code" for subscription.`)}for(let[t,n]of Object.entries(c.crons))c.agents[n.agent]||e.push(`Cron "${t}": references unknown agent "${n.agent}"`);if(c.channels.telegram.enabled)for(let[t,n]of Object.entries(c.channels.telegram.accounts))c.agents[n.agentBinding]||e.push(`Telegram account "${t}": references unknown agent "${n.agentBinding}"`);return e}import{execa as Ze}from"execa";import{execFile as et}from"child_process";function Te(c,e,t){let n=[];if(c.systemPrompt&&n.push(c.systemPrompt),e.context){let s=e.context,r=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),a=s.channel==="telegram";if(s.channel&&r.push(`Channel: ${s.channel}`),s.group&&r.push(`Group: ${s.group}`),s.sender&&r.push(`Message from: ${s.sender}`),s.myHandle&&r.push(`Your handle on this channel: ${s.myHandle}`),i&&(r.push(""),r.push("[IMPORTANT: You are responding to a GitLab comment/event]"),r.push("- Reply with a focused, actionable GitLab comment"),r.push("- Use markdown (GitLab flavored) for formatting"),r.push("- Do NOT mention Telegram handles (@noqta_*) \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&&s.peers?.length){r.push(""),r.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let o of s.peers){let l=o.handle?` (mention: ${o.handle})`:"",g=o.role?` \u2014 ${o.role}`:"";r.push(`\u2022 ${o.name}${l}${g}`)}r.push(""),r.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(r.join(`
7
+ `))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
8
+ `)}function Se(c,e,t,n){let s=["-p",e,"--output-format",t?"stream-json":"json"];return t&&s.push("--verbose"),n&&s.push("--resume",n),c.model&&s.push("--model",c.model),c.permissionMode==="bypassPermissions"&&s.push("--dangerously-skip-permissions"),s}function tt(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 nt(c,e,t,n){let s=Date.now(),r=Te(c,e,n?void 0:t),i=Se(c,r,!1,n);try{let{stdout:a,stderr:o,exitCode:l}=await new Promise((u,f)=>{let m=et("claude",i,{cwd:c.workspace,timeout:6e5,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"clawd")}},(y,p,d)=>{u({stdout:p||"",stderr:d||"",exitCode:y?y.code??1:0})})});if(!a&&l!==0)return{content:"",error:(o?.trim()||`Claude Code exited with code ${l}`).slice(0,300),duration:Date.now()-s};let g=tt(a);return{content:g.text,duration:Date.now()-s,claudeSessionId:g.sessionId,usage:g.usage}}catch(a){return console.error(`[runtime] execFile threw: ${a.message}`),{content:"",error:a.message||"Claude Code failed",duration:Date.now()-s}}}async function st(c,e,t,n,s){let r=Date.now(),i=Te(c,e,s?void 0:n),a=Se(c,i,!0,s),o="";try{let l=Ze("claude",a,{cwd:c.workspace,timeout:6e5,reject:!1,env:process.env,buffer:!1});if(l.stdout){let u="";l.stdout.on("data",f=>{u+=f.toString();let m=u.split(`
9
+ `);u=m.pop()||"";for(let y of m)if(y.trim())try{let p=JSON.parse(y);if(p.type==="assistant"&&p.message?.content){for(let d of p.message.content)if(d.type==="text"&&d.text){let b=d.text.slice(o.length);b&&(o=d.text,t(b,o))}}if(p.type==="content_block_delta"&&p.delta?.text&&(o+=p.delta.text,t(p.delta.text,o)),p.type==="result"&&p.result){let d=(typeof p.result=="string",p.result);if(typeof d=="string"&&d.length>o.length){let b=d.slice(o.length);o=d,b&&t(b,o)}}}catch{y.trim()&&!y.startsWith("{")&&(o+=y+`
10
+ `,t(y+`
11
+ `,o))}})}let g=await l;return!o&&g.stdout&&(o=typeof g.stdout=="string"?g.stdout:""),g.exitCode!==0&&!o?{content:"",error:(typeof g.stderr=="string"?g.stderr:"")||`Claude Code exited with code ${g.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 rt(c,e,t){let n=Date.now();try{let s=await import("@anthropic-ai/claude-agent-sdk"),{query:r}=s,i=c.systemPrompt?`${c.systemPrompt}
12
+
13
+ ${e.message}`:e.message,a="",o=r({prompt:i,options:{model:c.model,cwd:c.workspace,permissionMode:"bypassPermissions"}});for await(let l of o)l.type==="result"&&l.subtype==="success"&&(a=l.result||"");return{content:a,duration:Date.now()-n}}catch(s){return{content:"",error:`SDK error: ${s.message}`,duration:Date.now()-n}}}async function it(c,e,t){let n=Date.now();try{let{generate:s}=await import("./agent-K2YOEOJ5.js"),r=c.provider||"claude-code",i=await s({task:e.message,cwd:c.workspace,provider:r,model:c.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:i.content||"Done.",tokensUsed:i.tokensUsed,duration:Date.now()-n}}catch(s){return{content:"",error:`Orchestrator error: ${s.message}`,duration:Date.now()-n}}}async function Ce(c,e,t,n,s,r){switch(c.tier){case"claude-code":return n?st(c,e,n,s,r):nt(c,e,s,r);case"sdk":{let i=c.provider||"claude",a=t[i]?.apiKey;return a?rt(c,e,a):{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 it(c,e,a)}default:return{content:"",error:`Unknown tier: ${c.tier}`}}}import{readFileSync as L,writeFileSync as D,appendFileSync as ot,existsSync as I,mkdirSync as ue,readdirSync as pe,statSync as at}from"fs";import{resolve as v,join as ct,relative as R,dirname as lt}from"path";var E=class{baseDir;rawDir;log;constructor(e=v(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=v(e,"raw/entries"),this.log=t,ue(this.rawDir,{recursive:!0}),ue(v(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return!!(e.access==="public"||e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t))}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,n=v(this.rawDir,t),s=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&s.push(`context: ${e.sourceContext}`),e.meta)for(let[r,i]of Object.entries(e.meta))s.push(`${r}: ${JSON.stringify(i)}`);return s.push("---","",e.content),D(n,s.join(`
14
+ `)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!I(this.rawDir))return[];let t=pe(this.rawDir).filter(s=>s.endsWith(".md")).sort(),n=[];for(let s of t){let r=L(v(this.rawDir,s),"utf-8"),i=this.parseEntry(r,s);i&&(e?.agentId&&i.agentId!==e.agentId||e?.after&&i.date<e.after||e?.before&&i.date>e.before||n.push(i))}return n}parseEntry(e,t){let n=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!n)return null;let s=n[1],r=n[2].trim(),i=a=>s.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,n,s){let r=this.readArticle(e);if(r&&!this.canWrite(r.meta,s))return this.log(`Permission denied: "${s}" cannot write "${e}" (owner: ${r.meta.owner})`),!1;let i=v(this.baseDir,e);ue(lt(i),{recursive:!0});let a=["---",`title: "${t.title}"`,`type: ${t.type}`,`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}`,`related: [${t.related.map(l=>`"${l}"`).join(", ")}]`,`sources: [${t.sources.map(l=>`"${l}"`).join(", ")}]`),t.tags?.length&&a.push(`tags: [${t.tags.map(l=>`"${l}"`).join(", ")}]`),a.push("---","",n),D(i,a.join(`
15
+ `));let o=r?"update":"create";return this.appendLog(o,`${t.title} (${t.type}) by ${s} at ${e}`),!0}readArticle(e){let t=v(this.baseDir,e);if(!I(t))return null;let n=L(t,"utf-8");return this.parseArticle(n,e)}readArticleAs(e,t){let n=this.readArticle(e);return!n||!this.canRead(n.meta,t)?null:n}parseArticle(e,t){let n=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!n)return null;let s=n[1],r=n[2].trim(),i=o=>s.match(new RegExp(`^${o}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=o=>{let l=s.match(new RegExp(`^${o}:\\s*\\[(.*)\\]$`,"m"));return l?l[1].split(",").map(g=>g.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]};return{meta:{title:i("title"),type:i("type"),owner:i("owner"),access:i("access")||"public",sharedWith:a("shared_with"),created:i("created"),lastUpdated:i("last_updated"),related:a("related"),sources:a("sources"),tags:a("tags")},content:r,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let s=R(this.baseDir,n);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);r&&this.canRead(r.meta,e)&&t.push(r)}),t}search(e,t,n=10){let s=e.toLowerCase(),r=[];return this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=R(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(!o||!this.canRead(o.meta,t))return;let l=0,g=o.meta.title.toLowerCase(),u=o.content.toLowerCase();g.includes(s)&&(l+=10),o.meta.tags?.some(m=>m.toLowerCase().includes(s))&&(l+=5);let f=(u.match(new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length;l+=Math.min(f,5),l>0&&r.push({article:o,score:l})}),r.sort((i,a)=>a.score-i.score).slice(0,n).map(i=>i.article)}findRelevant(e,t,n=3){let s=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","can","shall","to","of","in","for","on","with","at","by","from","as","into","about","through","and","but","or","not","no","if","then","so","what","how","when","where","who","which","that","this","it","i","you","we","they","he","she","me","my","your","our","their","please","just","also","very","much","some","any","all"]),r=e.toLowerCase().replace(/[^a-z0-9\s@_-]/g," ").split(/\s+/).filter(a=>a.length>2&&!s.has(a));if(r.length===0)return[];let i=new Map;for(let a of r){let o=this.search(a,t,5);for(let l of o){let g=i.get(l.path);g?g.score+=1:i.set(l.path,{article:l,score:1})}}return Array.from(i.values()).sort((a,o)=>o.score-a.score).slice(0,n).map(a=>a.article)}buildContext(e,t=4e3){if(e.length===0)return"";let n=["[Wiki Knowledge]"],s=0;for(let r of e){let i=`
16
+ ## ${r.meta.title} (${r.meta.type})`,a=r.content.length>600?r.content.slice(0,600)+"...":r.content,o=i+`
17
+ `+a;if(s+o.length>t)break;n.push(o),s+=o.length}return n.push(`
18
+ [End Wiki Knowledge]`),n.join(`
19
+ `)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=R(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 u of l){let f=u.replace(/\[\[|\]\]/g,"");t.set(f,(t.get(f)||0)+1)}let g=[o.meta.title.toLowerCase()];o.meta.tags&&g.push(...o.meta.tags.map(u=>u.toLowerCase())),e.push({path:a,title:o.meta.title,type:o.meta.type,owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:g,backlinks:t.get(o.meta.title)||0})});let n={articles:e,lastRebuilt:new Date().toISOString()};D(v(this.baseDir,"_index.json"),JSON.stringify(n,null,2));let s=["# Wiki Index","",`Last rebuilt: ${n.lastRebuilt}`,""],r=new Map;for(let i of e){let a=r.get(i.type)||[];a.push(i),r.set(i.type,a)}for(let[i,a]of Array.from(r.entries()).sort()){s.push(`## ${i}`,"");for(let o of a.sort((l,g)=>l.title.localeCompare(g.title))){let l=o.access==="private"?" (private)":o.access==="shared"?" (shared)":"";s.push(`- [${o.title}](${o.path})${l} \u2014 owner: ${o.owner}`)}s.push("")}return D(v(this.baseDir,"WIKI.md"),s.join(`
20
+ `)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),n}stats(){let e=0,t={},n={},s={};this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=R(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_")||a==="WIKI.md")return;let o=this.readArticle(a);o&&(e++,t[o.meta.type]=(t[o.meta.type]||0)+1,n[o.meta.access]=(n[o.meta.access]||0)+1,s[o.meta.owner]=(s[o.meta.owner]||0)+1)});let r=I(this.rawDir)?pe(this.rawDir).filter(i=>i.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:r,articlesByType:t,articlesByAccess:n,articlesByOwner:s}}appendLog(e,t){let n=v(this.baseDir,"log.md"),r=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
21
+
22
+ `;I(n)||D(n,`# Wiki Log
23
+
24
+ Chronological record of all wiki operations.
25
+
26
+ `),ot(n,r)}getLog(e=20){let t=v(this.baseDir,"log.md");return I(t)?L(t,"utf-8").split(/^## /m).filter(r=>r.startsWith("[")).slice(-e).map(r=>r.trim()):[]}ensureSchema(){let e=v(this.baseDir,"_schema.md");if(I(e))return;D(e,`# Wiki Schema
27
+
28
+ This file defines how agents operate on this wiki. Read this before any wiki operation.
29
+
30
+ ## Structure
31
+
32
+ \`\`\`
33
+ .agentx/wiki/
34
+ _schema.md # This file \u2014 conventions and workflows
35
+ _index.json # Machine-readable index
36
+ WIKI.md # Human-readable index
37
+ log.md # Chronological operation log (append-only)
38
+ raw/entries/ # Immutable raw sources (conversations, imports)
39
+ projects/ # Project knowledge
40
+ people/ # People and relationships
41
+ decisions/ # Key decisions with reasoning
42
+ patterns/ # Recurring patterns and insights
43
+ concepts/ # Technical concepts
44
+ {new dirs}/ # Create as needed \u2014 directories emerge from data
45
+ \`\`\`
46
+
47
+ ## Conventions
48
+
49
+ - Articles use YAML frontmatter: title, type, owner, access, related, sources, tags
50
+ - Use \`[[wikilinks]]\` to link between articles
51
+ - Every article must trace back to raw sources via the \`sources:\` field
52
+ - Articles are organized by theme, not chronology
53
+ - One topic per article \u2014 split when an article exceeds 100 lines
54
+ - Quotes carry the voice; article text stays neutral and factual
55
+
56
+ ## Access Levels
57
+
58
+ - \`public\` \u2014 all agents can read, owner writes (default)
59
+ - \`shared\` \u2014 listed agents can read, owner writes
60
+ - \`private\` \u2014 only owner reads and writes
61
+
62
+ ## Operations
63
+
64
+ ### Ingest
65
+ Raw sources land in \`raw/entries/\`. Never modify raw sources.
66
+
67
+ ### Absorb
68
+ Read raw entries, understand meaning, create or update articles.
69
+ For each entry: match against index \u2192 update existing articles \u2192 create new ones \u2192 add wikilinks.
70
+ Every 10 entries: rebuild index, check for bloated articles, audit new article count.
71
+
72
+ ### Query
73
+ Read index first \u2192 find relevant articles \u2192 follow wikilinks 2-3 deep \u2192 synthesize.
74
+ Never read raw entries for queries \u2014 the wiki IS the knowledge.
75
+
76
+ ### Lint
77
+ Check for: contradictions, stale claims, orphan pages, missing wikilinks,
78
+ articles over 100 lines that should split, concepts mentioned but lacking pages.
79
+
80
+ ### Log
81
+ Every operation appends to log.md with timestamp and action type.
82
+ `),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(n=>n.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let n=R(this.baseDir,t);if(n.startsWith("raw/")||n.startsWith("_")||n==="WIKI.md"||n==="log.md")return;let s=L(t,"utf-8"),r=this.extractWikilinks(s);for(let i of r)e[i]||(e[i]=[]),e[i].push(n)}),D(v(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=v(this.baseDir,"_backlinks.json");if(!I(t))return[];try{return JSON.parse(L(t,"utf-8"))[e]||[]}catch{return[]}}lint(){let e=[],t=new Set,n=new Map,s=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=R(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),s.set(o.meta.title,a);let l=this.extractWikilinks(o.content);n.set(a,l);let g=o.content.split(`
83
+ `).length;g>100&&e.push({type:"bloated",article:a,message:`${g} lines \u2014 consider splitting`}),o.meta.sources?.length||e.push({type:"unsourced",article:a,message:"No sources listed in frontmatter"}),g<10&&o.content.trim().length<100&&e.push({type:"stub",article:a,message:"Very short article \u2014 needs enrichment"})});for(let[i,a]of n)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 s)(!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,n=>{if(!n.endsWith(".md"))return;let s=R(this.baseDir,n);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);if(r?.meta.sources)for(let i of r.meta.sources)e.add(i)}),this.listEntries().filter(n=>!e.has(n.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let n=t.map(s=>`[${s.date} ${s.agentId} via ${s.source}] ${s.content.slice(0,200)}`).join(`
84
+
85
+ `);return`/wiki absorb
86
+
87
+ There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
88
+
89
+ ${n}`}walkDir(e,t){if(I(e))for(let n of pe(e)){let s=ct(e,n);at(s).isDirectory()?this.walkDir(s,t):t(s)}}};import{resolve as Ee}from"path";import{readFileSync as gt,writeFileSync as ht,mkdirSync as dt,existsSync as Me}from"fs";import{resolve as Ie}from"path";var ut=12e3,Pe=30,V=class{sessionsDir;cache=new Map;constructor(e=process.cwd()){this.sessionsDir=Ie(e,".agentx/sessions"),Me(this.sessionsDir)||dt(this.sessionsDir,{recursive:!0})}sessionKey(e,t,n){let s=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${s}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ie(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let s=this.sessionKey(e,t,n);if(this.cache.has(s))return this.cache.get(s);let r=this.sessionFile(s);if(Me(r))try{let o=JSON.parse(gt(r,"utf-8"));return this.cache.set(s,o),o}catch{}let i=new Date().toISOString().slice(0,10),a={id:s,agentId:e,channel:t,chatId:n,day:i,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(s,a),this.save(a),a}addUserMessage(e,t,n,s,r){let i=this.getSession(e,t,n);i.messages.push({role:"user",name:s,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i)}addAgentMessage(e,t,n,s){let r=this.getSession(e,t,n);r.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(r),r.updatedAt=new Date().toISOString(),this.save(r)}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let r=this.getSession(e,t,n);r.claudeSessionId=s,r.updatedAt=new Date().toISOString(),this.save(r)}buildHistoryContext(e,t,n){let s=this.getSession(e,t,n);if(s.messages.length===0)return"";let r=[`[Conversation history for today (${s.day})]`];for(let i of s.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(`
90
+ `)}trim(e){e.messages.length>Pe&&(e.messages=e.messages.slice(-Pe));let t=e.messages.reduce((n,s)=>n+s.content.length,0);for(;t>ut&&e.messages.length>2;){let n=e.messages.shift();t-=n.content.length}}save(e){try{let t=this.sessionFile(e.id);ht(t,JSON.stringify(e,null,2))}catch{}}};var X=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],s=t-36e5,r=n.filter(o=>o>s),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(),n=this.windows.get(e)||[];return{lastMinute:n.filter(s=>s>t-6e4).length,lastHour:n.filter(s=>s>t-36e5).length}}};import{readFileSync as De,writeFileSync as pt,existsSync as Re,mkdirSync as mt}from"fs";import{resolve as _e}from"path";var Q=class{dir;cache=null;constructor(e=_e(process.cwd(),".agentx/usage")){this.dir=e,mt(this.dir,{recursive:!0})}record(e,t,n,s,r,i){let a=this.today(),o=a.agents[e]||{tasks:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreateTokens:0,totalDuration:0,errors:0};o.tasks++,o.totalDuration+=t,n?(o.inputTokens+=n.inputTokens,o.outputTokens+=n.outputTokens,o.cacheReadTokens+=n.cacheReadTokens,o.cacheCreateTokens+=n.cacheCreateTokens):s!==void 0&&r!==void 0&&(o.inputTokens+=Math.ceil(s/4),o.outputTokens+=Math.ceil(r/4)),i&&o.errors++,a.agents[e]=o,this.save(a)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(Re(t))try{return this.cache=JSON.parse(De(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Re(t))return null;try{return JSON.parse(De(t,"utf-8"))}catch{return null}}summary(e=7){let t=0,n=0,s=0,r=0,i=0,a=0,o={};for(let u=0;u<e;u++){let f=new Date(Date.now()-u*864e5).toISOString().slice(0,10),m=this.getDate(f);if(m)for(let[y,p]of Object.entries(m.agents)){t+=p.tasks,n+=p.inputTokens||0,s+=p.outputTokens||0,r+=p.cacheReadTokens||0,i+=p.cacheCreateTokens||0,a+=p.errors;let d=o[y]||{tasks:0,input:0,output:0,cacheRead:0,cacheCreate:0,total:0,avgDuration:0,totalDuration:0};d.tasks+=p.tasks,d.input+=p.inputTokens||0,d.output+=p.outputTokens||0,d.cacheRead+=p.cacheReadTokens||0,d.cacheCreate+=p.cacheCreateTokens||0,d.total=d.input+d.output+d.cacheRead+d.cacheCreate,d.totalDuration+=p.totalDuration,d.avgDuration=d.totalDuration/d.tasks,o[y]=d}}let l=n+s+r+i,g=r+i>0?r/(r+i):0;return{totalTasks:t,totalTokens:l,totalInput:n,totalOutput:s,totalCacheRead:r,totalCacheCreate:i,cacheHitRatio:g,totalErrors:a,byAgent:o}}filePath(e){return _e(this.dir,`${e}.json`)}save(e){try{pt(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};var ft={totalBudget:4e3,layerBudgets:{channel:200,scope:200,identity:300,peers:400,intent:200,artifacts:500,history:1200,wiki:1e3}},je=4;function Le(c,e=ft){let t=yt(c,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,r=e.totalBudget*je;for(let i of t){if(!i.content)continue;let a=i.maxTokens*je,o=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(s+o.length>r){let l=r-s;l>100&&n.push(o.slice(0,l)+"...");break}n.push(o),s+=o.length}return n.join(`
91
+
92
+ `)}function yt(c,e){let t=(a,o)=>e.layerBudgets?.[a]??o,n=[];n.push(wt(c,t("channel",200))),n.push(bt(c,t("scope",200))),c.systemPrompt&&n.push({name:"identity",priority:3,maxTokens:t("identity",300),content:c.systemPrompt.split(`
93
+ `)[0],tags:["identity",c.agentId]}),c.peers?.length&&$t(c.channel)&&n.push(kt(c,t("peers",400)));let s=vt(c.message);s.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${s.join(", ")}]`,tags:s});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&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
94
+ `),tags:["artifacts",...c.mediaType?["media"]:[]]});let i=c.groupHistory||c.sessionHistory;return i&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:i,tags:["history","conversation"]}),c.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:c.wikiContext,tags:["wiki","knowledge"]}),n}function wt(c,e){let t=[`Channel: ${c.channel}`],n=[],s=[c.channel];switch(c.channel){case"telegram":c.agentHandle&&t.push(`Your handle: ${c.agentHandle}`),t.push(`From: ${c.sender}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Keep responses concise for mobile reading");break;case"whatsapp":t.push(`From: ${c.sender}`),n.push("Keep responses concise \u2014 WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only");break;case"gitlab":t.push(`From: ${c.sender}`),n.push("Reply as a GitLab comment with GitLab-flavored markdown"),n.push("Do NOT mention Telegram handles (@noqta_*)"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Be specific and actionable \u2014 this is a code review context"),s.push("code-review");break;case"discord":t.push(`From: ${c.sender}`),n.push("Use Discord markdown for formatting");break;default:c.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(r=>`- ${r}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
95
+ `),tags:s,rules:n}}function bt(c,e){let t=[],n=[];return c.channelScope==="group"&&c.groupName?(t.push(`Group: ${c.groupName}`),n.push("group",c.groupName)):c.channelScope==="project"&&c.projectPath?(t.push(`Project: ${c.projectPath}`),n.push("project",c.projectPath)):c.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),{name:"scope",priority:2,maxTokens:e,content:t.join(`
96
+ `),tags:n}}function kt(c,e){let t=["[Team \u2014 mention to delegate]"];for(let n of c.peers||[]){let s=n.handle?` (${n.handle})`:"",r=n.role?` \u2014 ${n.role}`:"";t.push(`\u2022 ${n.name}${s}${r}`)}return t.push("Mention their handle to involve them."),{name:"peers",priority:4,maxTokens:e,content:t.join(`
97
+ `),tags:["peers","team"]}}function vt(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}function $t(c){return c==="telegram"}var Y=class{agents=new Map;config;providers={};sessions;wikis=new Map;rateLimiter;tokenTracker;log;constructor(e,t=console.error.bind(console,"[agents]")){this.log=t,this.config=e,this.providers=e.providers,this.sessions=new V,this.rateLimiter=new X,this.tokenTracker=new Q;for(let[n,s]of Object.entries(e.agents))this.agents.set(n,{id:n,def:s,activeTasks:0,totalTasks:0,errors:0})}getAgent(e){return this.agents.get(e)?.def}findByMention(e){let t=e.toLowerCase(),n,s=0;for(let[r,i]of this.agents)for(let a of i.def.mentions){let o=a.toLowerCase();t.includes(o)&&o.length>s&&(n=r,s=o.length)}return n}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,r]of this.agents)for(let i of r.def.mentions)if(t.includes(i.toLowerCase())){n.push(s);break}return n}getWiki(e){if(this.wikis.has(e))return this.wikis.get(e);let t=this.agents.get(e)?.def,n=t?Ee(t.workspace,".wiki"):Ee(process.cwd(),".agentx/wiki"),s=new E(n);return this.wikis.set(e,s),s}buildPeerList(e,t){let n=[];for(let[s,r]of this.agents)s!==e&&n.push({name:r.def.name,handle:this.getChannelHandle(s,t),role:r.def.systemPrompt?.split(`
98
+ `)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(s=>s.startsWith("@")):n.mentions[0]}async execute(e,t){let n=this.agents.get(e.agentId);if(!n)return{content:"",error:`Unknown agent: ${e.agentId}`};if(n.activeTasks>=n.def.maxConcurrent)return{content:"",error:`Agent "${e.agentId}" is busy (${n.activeTasks}/${n.def.maxConcurrent} tasks)`};let s=this.rateLimiter.check(e.agentId);if(!s.allowed)return this.log(`[${e.agentId}] ${s.reason}`),{content:"",error:s.reason};n.activeTasks++,n.totalTasks++,n.lastActive=new Date,this.log(`[${e.agentId}] executing task (${n.activeTasks}/${n.def.maxConcurrent})`);let r=e.context?.channel||"api",i=e.context?.group||e.context?.sender||"default",a=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,r,i,a,e.message);let o=this.getWiki(e.agentId),l=o.findRelevant(e.message,e.agentId,3),g=o.buildContext(l),u=n.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,r,i):void 0,f=u?void 0:this.sessions.buildHistoryContext(e.agentId,r,i),m=this.buildPeerList(e.agentId,r),y={channel:r,channelScope:e.context?.group?"group":r==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:n.def.name,agentHandle:this.getChannelHandle(e.agentId,r),systemPrompt:n.def.systemPrompt,sender:a,peers:m,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,groupHistory:(e.context?.group,void 0),sessionHistory:f,wikiContext:g,message:e.message},p=Le(y);try{let d=await Ce(n.def,e,this.providers,t,p,u);if(d.error)n.errors++,this.log(`[${e.agentId}] error: ${d.error}`);else{if(this.sessions.addAgentMessage(e.agentId,r,i,d.content),d.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,r,i,d.claudeSessionId),d.content.length>50)try{let b=`${e.agentId}-${Date.now().toString(36)}`;o.addEntry({id:b,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:r,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
99
+
100
+ Agent: ${d.content}`})}catch{}this.tokenTracker.record(e.agentId,d.duration||0,d.usage,e.message.length,d.content.length),this.log(`[${e.agentId}] completed in ${d.duration}ms`+(d.tokensUsed?` (${d.tokensUsed} tokens)`:""))}return d}catch(d){return n.errors++,this.log(`[${e.agentId}] unexpected error: ${d.message}`),{content:"",error:d.message}}finally{n.activeTasks--}}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()}};import{readFileSync as xt,writeFileSync as At,existsSync as Tt,mkdirSync as St}from"fs";import{resolve as We}from"path";var Ct=30,Mt=6e3,Z=class{dir;cache=new Map;constructor(e=We(process.cwd(),".agentx/groups")){this.dir=e,St(this.dir,{recursive:!0})}add(e,t,n){let s=this.load(e);for(s.push({sender:t,text:n.slice(0,500),timestamp:Date.now()});s.length>Ct;)s.shift();this.cache.set(e,s),this.save(e,s)}buildContext(e){let t=this.load(e);if(t.length<=1)return"";let n=["[Recent group conversation]"],s=0;for(let r=t.length-2;r>=0;r--){let i=t[r],o=`[${new Date(i.timestamp).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1})}] ${i.sender}: ${i.text}`;if(s+o.length>Mt)break;n.splice(1,0,o),s+=o.length}return n.length<=1?"":(n.push("[End of conversation \u2014 respond to the latest message]"),n.join(`
101
+ `))}getEntries(e){return[...this.load(e)]}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return We(this.dir,`${t}.json`)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.filePath(e);if(!Tt(t))return this.cache.set(e,[]),[];try{let n=JSON.parse(xt(t,"utf-8")),s=Array.isArray(n)?n:[];return this.cache.set(e,s),s}catch{return this.cache.set(e,[]),[]}}save(e,t){try{At(this.filePath(e),JSON.stringify(t))}catch{}}};var It=1500,Pt=4e3,me=class{registry;config;channels=new Map;hooks;mesh;groupLog;log;constructor(e,t,n,s=console.error.bind(console,"[router]")){this.registry=e,this.config=t,this.hooks=n,this.log=s,this.groupLog=new Z}setMesh(e){this.mesh=e}addChannel(e){this.channels.set(e.name,e),e.onMessage(t=>this.handleMessage(e,t))}async startAll(){for(let[e,t]of this.channels)this.log(`Starting channel: ${e}`),await t.start()}async stopAll(){for(let[e,t]of this.channels)this.log(`Stopping channel: ${e}`),await t.stop()}async handleMessage(e,t){if(this.hooks?.has("pre:channel-message")){let w=await this.hooks.execute("pre:channel-message",{event:"pre:channel-message",channel:t.channel,sender:t.sender.name,text:t.text,group:t.group?.name});if(w.blocked){this.log(`Message blocked by hook: ${w.message}`);return}w.modified?.text&&(t={...t,text:w.modified.text})}if(t.group){let w=t.group.id;this.groupLog.add(w,t.sender.name,t.text)}let n=this.resolveAgent(t);if(!n)return;if(t.group&&t.channel==="telegram"){let w=this.getAccountForAgent(n);if(w&&w!==t.accountId)return}let s=t.group?.id||t.sender.id,i=this.registry.getAgent(n)?.name||n,a=this.getAccountForAgent(n)||t.accountId;this.log(`Routing [${t.channel}/${t.sender.name}] -> "${i}": ${t.text.slice(0,80)}`),this.adapterReact(e,s,t.id,"\u{1F440}",a);let o=this.startTypingLoop(e,s,a),l=typeof e.editMessage=="function",g,u=0,f=l?async(w,k)=>{let A=Date.now();if(!(A-u<It))if(g)try{await this.adapterEdit(e,s,g,k,void 0,a),u=A}catch{}else{let $=k.length>20?k:`_${i} is writing..._
102
+
103
+ ${k}`;try{g=await this.adapterSend(e,{channel:t.channel,chatId:s,text:$,replyTo:t.id,accountId:a}),u=A}catch{}}}:void 0,m=t.group?this.groupLog.buildContext(s):"",y=m?`${m}
104
+
105
+ ${t.sender.name}: ${t.text}`:t.text,p=await this.registry.execute({message:y,agentId:n,context:{channel:t.channel,sender:t.sender.name,group:t.group?.name,mediaPath:t.media?.path,mediaType:t.media?.type,replyToText:t.replyToText}},f);if(clearInterval(o),p.error){this.log(`Agent error: ${p.error}`);let w=`Error: ${p.error}`;g?await this.adapterEdit(e,s,g,w,"plain",a):await this.adapterSend(e,{channel:t.channel,chatId:s,text:w,replyTo:t.id,parseMode:"plain",accountId:a});return}let d=p.content;if(this.hooks?.has("post:channel-message")){let w=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:d,agentId:n});if(w.blocked){this.log(`Response blocked by hook: ${w.message}`);return}w.modified?.response&&(d=w.modified.response)}let b;d&&(g?(await this.adapterEdit(e,s,g,d,void 0,a),b=g):b=await this.adapterSend(e,{channel:t.channel,chatId:s,text:d,replyTo:t.id,accountId:a})),t.group&&d&&this.groupLog.add(s,i,d),d&&b&&t.channel==="telegram"&&this.handleBotToBotChain(e,t,n,d,b,0).catch(w=>{this.log(`Bot-to-bot error: ${w.message}`)})}async handleBotToBotChain(e,t,n,s,r,i,a=new Set){if(i>=me.MAX_BOT_CHAIN_DEPTH){this.log(`Bot-to-bot: max depth (${i}) reached, stopping`);return}a.add(n);for(let[o,l]of Object.entries(this.config.agents)){if(o===n)continue;if(a.has(o)){this.log(`Bot-to-bot: "${o}" already participated, stopping chain`);continue}if(!l.mentions.some(y=>s.toLowerCase().includes(y.toLowerCase())))continue;this.log(`Bot-to-bot [${i+1}]: "${n}" -> "${o}"`);let u=t.group?.id||t.sender.id,f=this.getAccountForAgent(o),m=this.getAccountForAgent(n);try{this.adapterReact(e,u,r,"\u{1F440}",f);let y=this.startTypingLoop(e,u,f),p=i===0?`[Original from ${t.sender.name}]: ${t.text}
106
+
107
+ [${n} said]: ${s}`:s,d=await this.registry.execute({message:p,agentId:o,context:{channel:t.channel,sender:`agent:${n}`,group:t.group?.name}});if(clearInterval(y),d.content&&!d.error){let b=await this.adapterSend(e,{channel:t.channel,chatId:u,text:d.content,accountId:f});b&&d.content&&await this.handleBotToBotChain(e,t,o,d.content,b,i+1,a)}else d.error&&this.log(`Bot-to-bot "${o}" error: ${d.error}`)}catch(y){this.log(`Bot-to-bot "${o}" failed: ${y.message}`)}break}}async adapterSend(e,t){return e.name==="telegram"&&t.accountId?e.send({...t,parseMode:t.parseMode,accountId:t.accountId}):e.send(t)||""}async adapterEdit(e,t,n,s,r,i){return e.name==="telegram"&&i?e.editMessage(t,n,s,r,i):e.editMessage?.(t,n,s,r)??!1}adapterReact(e,t,n,s,r){e.name==="telegram"&&r?e.react(t,n,s,r):e.react?.(t,n,s)}startTypingLoop(e,t,n){let s=()=>{e.name==="telegram"&&n?e.sendTyping(t,n):e.sendTyping?.(t)};return s(),setInterval(s,Pt)}async handleViaMesh(e,t){if(!this.mesh)return!1;let n=t.text.toLowerCase(),s=this.mesh.directory();for(let r of s)if(r.healthy){for(let i of r.skills)if(n.includes(i.id.toLowerCase())||n.includes(i.name.toLowerCase())){this.log(`Mesh routing [${t.channel}/${t.sender.name}] -> peer "${r.peer}" agent "${i.id}"`);let a=t.group?.id||t.sender.id,o=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",o);let l=this.startTypingLoop(e,a,o);try{let g=await this.mesh.sendTask(r.peer,t.text,i.id);if(clearInterval(l),g){let u=`**${i.name}** _(${r.peer})_:
108
+
109
+ `;await this.adapterSend(e,{channel:t.channel,chatId:a,text:u+g,replyTo:t.id,accountId:o})}return!0}catch(g){return clearInterval(l),this.log(`Mesh routing error: ${g.message}`),await this.adapterSend(e,{channel:t.channel,chatId:a,text:`Error from ${r.peer}/${i.name}: ${g.message}`,replyTo:t.id,parseMode:"plain",accountId:o}),!0}}}return!1}getAccountForAgent(e){for(let[t,n]of Object.entries(this.config.channels.telegram.accounts))if(n.agentBinding===e)return t}resolveAgent(e){if(e.resolvedAgent)return e.resolvedAgent;if(!e.group)return e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:e.channel==="whatsapp"?this.config.channels.whatsapp.defaultAgent:void 0;if(e.channel==="telegram"&&this.config.channels.telegram.policy.group==="mention-required"){let s=this.registry.findByMention(e.text);return s||void 0}let t=this.registry.findByMention(e.text);return t||(e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:this.config.channels.whatsapp.defaultAgent)}},W=me;J(W,"MAX_BOT_CHAIN_DEPTH",3);function ee(c){return c.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function fe(c){let e=c.split(`
110
+ `),t=[],n=!1,s="",r=[],i=!1,a=[],o=!1;for(let g=0;g<e.length;g++){let u=e[g];if(u.trimStart().startsWith("```"))if(n){n=!1;let p=ee(r.join(`
111
+ `)),d=s?`// ${s}
112
+ `:"";t.push(`<pre><code>${d}${p}</code></pre>`),s="";continue}else{n=!0,s=u.trimStart().slice(3).trim(),r=[];continue}if(n){r.push(u);continue}if(i&&!u.trimStart().startsWith(">")&&(t.push("</blockquote>"),i=!1),o&&!u.trim().startsWith("|")&&(o=!1,a=[]),u.trimStart().startsWith("> ")){let p=u.replace(/^>\s*/,"");i||(t.push("<blockquote>"),i=!0),t.push(M(p));continue}let f=u.match(/^(#{1,6})\s+(.+)$/);if(f){t.push(""),t.push(`<b>${M(f[2])}</b>`);continue}if(/^[-*_]{3,}\s*$/.test(u.trim())){t.push("\u2014\u2014\u2014");continue}if(u.trim().startsWith("|")&&u.trim().endsWith("|")){let p=u.split("|").slice(1,-1).map(d=>d.trim());if(/^\|[\s\-:|]+\|$/.test(u.trim())){o=!0;continue}if(!o){a=p,o=!0;continue}if(a.length>0&&p.length>0)if(p.length>=2){let d=[];for(let b=0;b<p.length;b++)if(b===0)d.push(`<b>${M(p[b])}</b>`);else{let w=a[b]?`${M(a[b])}: `:"";d.push(`${w}${M(p[b])}`)}t.push(`\u2022 ${d.join(" \u2014 ")}`)}else t.push(`\u2022 ${M(p[0])}`);continue}let m=u.match(/^(\s*)[-*+]\s+(.+)$/);if(m){let p=m[1].length>0?" ":"";t.push(`${p}\u2022 ${M(m[2])}`);continue}let y=u.match(/^(\s*)\d+[.)]\s+(.+)$/);if(y){let p=y[1].length>0?" ":"",d=u.match(/^(\s*)(\d+)/)?.[2]||"1";t.push(`${p}${d}. ${M(y[2])}`);continue}if(!u.trim()){t.push("");continue}t.push(M(u))}n&&t.push(`<pre><code>${ee(r.join(`
113
+ `))}</code></pre>`),i&&t.push("</blockquote>");let l=t.join(`
114
+ `).trim();return l=Rt(l),l}function M(c){let e=ee(c);return e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,n,s)=>`<a href="${ee(s)}">${n}</a>`),e=e.replace(/\*\*\*(.+?)\*\*\*/g,"<b><i>$1</i></b>"),e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>"),e=e.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g,"<i>$1</i>"),e=e.replace(/~~(.+?)~~/g,"<s>$1</s>"),e=e.replace(/\|\|(.+?)\|\|/g,"<tg-spoiler>$1</tg-spoiler>"),e}var Dt=/(?<=\w)\.(ts|js|py|rs|go|rb|cs|sh|md|yml|yaml|toml|json|env|css|html|xml|sql|tf|hcl)(?=[\s,;:)\]}<]|$)/gi;function Rt(c){let e=c.split(/(<\/?(?:code|pre|a)[^>]*>)/gi),t=!1;return e.map(n=>/<(?:code|pre|a)\b/i.test(n)?(t=!0,n):/<\/(?:code|pre|a)>/i.test(n)?(t=!1,n):t?n:n.replace(Dt,"<code>.$1</code>")).join("")}var te=class{name="telegram";accounts;offsets=new Map;handler;polling=!1;log;constructor(e,t=console.error.bind(console,"[telegram]")){this.accounts=new Map(Object.entries(e)),this.log=t}onMessage(e){this.handler=e}async start(){this.polling=!0;let e=Array.from(this.accounts.entries());this.log(`${e.length} Telegram account(s) to start`);for(let t=0;t<e.length;t++){let[n,s]=e[t];this.log(`Starting polling for account "${n}" (${t+1}/${e.length})`);try{let r=await this.apiCall(s.token,"getMe");this.log(`Bot @${r.result?.username} ready (account: ${n})`),this.pollLoop(n,s)}catch(r){this.log(`Failed to verify bot for account "${n}": ${r.message}`)}t<e.length-1&&await new Promise(r=>setTimeout(r,300))}this.log(`All ${e.length} Telegram account(s) started`)}async stop(){this.polling=!1}getTokenForAccount(e){return this.accounts.get(e)?.token}getDefaultToken(){let[,e]=Array.from(this.accounts.entries())[0];return e?.token}resolveToken(e,t){if(t){let n=this.getTokenForAccount(t);if(n)return n}return this.chatAccountMap.get(e)?this.getTokenForAccount(this.chatAccountMap.get(e)):this.getDefaultToken()}chatAccountMap=new Map;async send(e){let t=this.resolveToken(e.chatId,e.accountId);if(!t)return this.log("No telegram token found for sending"),"";let n=4096,s=e.text.length>n?e.text.slice(0,n-3)+"...":e.text,r=e.parseMode==="markdown"||e.parseMode===void 0?fe(s):s,i={chat_id:e.chatId,text:r,parse_mode:"HTML"};e.replyTo&&(i.reply_to_message_id=parseInt(e.replyTo,10)),e.parseMode==="html"?(i.parse_mode="HTML",i.text=s):e.parseMode==="plain"&&(delete i.parse_mode,i.text=s);try{let a=await this.apiCall(t,"sendMessage",i);return String(a.result?.message_id||"")}catch(a){if(i.parse_mode){delete i.parse_mode,i.text=s;let o=await this.apiCall(t,"sendMessage",i);return String(o.result?.message_id||"")}throw a}}async editMessage(e,t,n,s,r){let i=this.resolveToken(e,r);if(!i)return!1;let a=4096,o=n.length>a?n.slice(0,a-3)+"...":n,l=s!=="html"&&s!=="plain"?fe(o):o,g={chat_id:e,message_id:parseInt(t,10),text:l,parse_mode:"HTML"};s==="html"?(g.parse_mode="HTML",g.text=o):s==="plain"&&(delete g.parse_mode,g.text=o);try{return await this.apiCall(i,"editMessageText",g),!0}catch(u){if(u.message?.includes("message is not modified"))return!0;if(g.parse_mode){delete g.parse_mode,g.text=o;try{return await this.apiCall(i,"editMessageText",g),!0}catch{return!1}}return!1}}async react(e,t,n="\u{1F440}",s){let r=this.resolveToken(e,s);if(r)try{await this.apiCall(r,"setMessageReaction",{chat_id:e,message_id:parseInt(t,10),reaction:[{type:"emoji",emoji:n}]})}catch{}}async sendTyping(e,t){let n=this.resolveToken(e,t);if(n)try{await this.apiCall(n,"sendChatAction",{chat_id:e,action:"typing"})}catch{}}async pollLoop(e,t){let n=0;for(;this.polling;)try{let s=this.offsets.get(e)||0,i=(await this.apiCall(t.token,"getUpdates",{offset:s||void 0,timeout:30,allowed_updates:["message"]})).result||[];for(let a of i)if(this.offsets.set(e,a.update_id+1),a.message&&this.handler){let o=a.message,l=o.text||o.caption||"",g,u=o.photo&&o.photo.length>0,f=!!o.voice,m=!!o.audio,y=!!o.video,p=!!o.document;if(u||f||m||y||p){let w,k="application/octet-stream";if(u?(w=o.photo[o.photo.length-1].file_id,k="image/jpeg",l||(l="[Photo attached \u2014 please describe what you see]")):f?(w=o.voice.file_id,k=o.voice.mime_type||"audio/ogg",l||(l="[Voice message \u2014 please transcribe and respond]")):m?(w=o.audio.file_id,k=o.audio.mime_type||"audio/mpeg",l||(l=`[Audio: ${o.audio.title||"audio file"}]`)):y?(w=o.video.file_id,k=o.video.mime_type||"video/mp4",l||(l="[Video attached]")):p&&(w=o.document.file_id,k=o.document.mime_type||"application/octet-stream",l||(l=`[Document: ${o.document.file_name||"file"}]`)),w)try{let $=(await this.apiCall(t.token,"getFile",{file_id:w})).result?.file_path;if($){let P=`https://api.telegram.org/file/bot${t.token}/${$}`,B=await fetch(P);if(B.ok){let be=Buffer.from(await B.arrayBuffer()),S=k.split("/")[1]?.split(";")[0]||"bin",{mkdirSync:ae,writeFileSync:_}=await import("fs"),{randomUUID:U}=await import("crypto"),{resolve:G,join:ce}=await import("path"),x=G(process.cwd(),".agentx/media/telegram");ae(x,{recursive:!0});let C=o.document?.file_name||`${U()}.${S}`,T=ce(x,C);_(T,be),g={path:T,type:k,fileName:C}}}}catch(A){this.log(`Media download failed: ${A.message}`)}}if(!l)continue;let b={id:String(o.message_id),channel:"telegram",accountId:e,sender:{id:String(o.from.id),name:[o.from.first_name,o.from.last_name].filter(Boolean).join(" "),username:o.from.username},group:o.chat.type!=="private"?{id:String(o.chat.id),name:o.chat.title||""}:void 0,text:l,media:g,replyTo:o.reply_to_message?String(o.reply_to_message.message_id):void 0,replyToText:o.reply_to_message?o.reply_to_message.text||o.reply_to_message.caption||`[message from ${o.reply_to_message.from?.first_name||"unknown"}]`:void 0,timestamp:new Date(o.date*1e3),raw:a};this.chatAccountMap.set(String(o.chat.id),e),this.handler(b).catch(w=>{this.log(`Error handling message: ${w.message}`)})}n=0}catch(s){n++;let r=Math.min(5e3*Math.pow(2,n-1),6e4);this.log(`Poll error (${e}): ${s.message} [retry in ${r/1e3}s, errors: ${n}]`),await new Promise(i=>setTimeout(i,r))}}async apiCall(e,t,n){let s=`https://api.telegram.org/bot${e}/${t}`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});if(!r.ok){let i=await r.text();throw new Error(`Telegram API error: ${r.status} ${i}`)}return r.json()}};import{mkdirSync as Oe,writeFileSync as _t}from"fs";import{resolve as Ne,join as jt}from"path";import{randomUUID as Lt}from"crypto";var ne=class{name="whatsapp";sessionDir;defaultAgent;allowFrom;routes;handler;sock=null;sentMessageIds=new Set;log;constructor(e,t=console.error.bind(console,"[whatsapp]")){this.sessionDir=Ne(e.sessionDir),this.defaultAgent=e.defaultAgent,this.allowFrom=e.allowFrom,this.routes=e.routes||[],this.log=t}resolveAgent(e,t,n){for(let s of this.routes){if(s.contact){let r=s.contact.replace(/\+/g,"");if(e.includes(r)||r.includes(e))return s.agent}if(s.group&&(t||n)){let r=s.group.toLowerCase();if(t?.toLowerCase().includes(r)||n?.toLowerCase().includes(r))return s.agent}}return this.defaultAgent}onMessage(e){this.handler=e}async start(){let e,t,n,s;try{s=await import("@whiskeysockets/baileys"),e=s.default||s.makeWASocket,t=s.useMultiFileAuthState,n=s.DisconnectReason}catch{this.log("WhatsApp requires @whiskeysockets/baileys. Install with:"),this.log(" npm install @whiskeysockets/baileys");return}Oe(this.sessionDir,{recursive:!0});let{state:r,saveCreds:i}=await t(this.sessionDir),a;try{let{version:l}=await s.fetchLatestBaileysVersion();a=l,this.log(`WhatsApp Web version: ${l.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let o={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...l)=>this.log("WA error:",...l),child:()=>o};this.sock=e({auth:{creds:r.creds,keys:s.makeCacheableSignalKeyStore?s.makeCacheableSignalKeyStore(r.keys,o):r.keys},...a?{version:a}:{},logger:o,printQRInTerminal:!1,browser:["agentx","server","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1}),this.sock.ev.on("creds.update",i),this.sock.ev.on("messaging-history.set",l=>{this.log(`WA history sync: ${l.messages?.length||0} messages, ${l.isLatest?"latest":"partial"}`)}),this.sock.ev.on("connection.update",async l=>{let{connection:g,lastDisconnect:u,qr:f}=l;if(f){this.log("Scan QR code with WhatsApp to connect:");try{let{default:m}=await import("qrcode-terminal");m.generate(f,{small:!0})}catch{this.log(`QR: ${f}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(g==="close"){let m=u?.error?.output?.statusCode;this.log(`WhatsApp connection closed (status: ${m})`),m===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):m===n?.loggedOut||m===401?this.log("Logged out. Delete session dir and restart to re-scan QR."):m!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}g==="open"&&this.log("WhatsApp connected")}),this.sock.ev.on("messages.upsert",async l=>{if(this.log(`WA messages.upsert: ${l.messages?.length||0} messages, type: ${l.type}`),!!this.handler)for(let g of l.messages||[]){let u=(g.key.remoteJid||"").replace(/@.*/,"").slice(-6),f=!!(g.message?.conversation||g.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${u} fromMe=${g.key.fromMe} hasText=${f} type=${Object.keys(g.message||{}).join(",")}`),g.key.remoteJid==="status@broadcast")continue;if(g.key.id&&this.sentMessageIds.has(g.key.id)){this.sentMessageIds.delete(g.key.id);continue}if(g.key.fromMe){let x=this.sock?.user,C=g.key.remoteJid||"",T=x?.id?.replace(/:.*/,"")||"",le=x?.lid?.replace(/:.*/,"")||"",j=C.replace(/:.*/,"").replace(/@.*/,"");if(!(j===T||j===le))continue}let m=g.message?.conversation||g.message?.extendedTextMessage?.text||g.message?.imageMessage?.caption||g.message?.videoMessage?.caption||"",y=g.message||{},p=!!y.imageMessage,d=!!y.audioMessage,b=!!y.videoMessage,w=!!y.documentMessage,k=!!y.stickerMessage,A=p||d||b||w||k;if(A&&!m&&(p?m="[Image attached \u2014 please describe what you see]":d?m="[Voice message attached \u2014 please transcribe and respond]":b?m="[Video attached]":w?m=`[Document: ${y.documentMessage?.fileName||"file"}]`:k&&(m="[Sticker]")),!m)continue;let $=g.key.remoteJid||"",P=$.endsWith("@g.us"),B=$.replace(/@.*$/,""),S=(P?g.key.participant||"":$).replace(/@.*$/,"");if(this.allowFrom?.length&&!g.key.fromMe&&!this.allowFrom.some(C=>{let T=C.replace(/\+/g,"");return S.includes(T)||B.includes(T)}))continue;let ae=g.key.fromMe?"me":g.pushName||S,_;if(P&&this.sock)try{_=(await this.sock.groupMetadata($)).subject}catch{}let U=this.resolveAgent(S,_,P?$:void 0);if(!U){this.log(`No route for ${P?`group ${_||$}`:S}, skipping`);continue}let G;if(A&&this.sock)try{let C=await(await import("@whiskeysockets/baileys")).downloadMediaMessage(g,"buffer",{},{reuploadRequest:this.sock.updateMediaMessage,logger:this.sock.logger});if(C){let T=y.imageMessage?.mimetype||y.audioMessage?.mimetype||"audio/ogg",le=T.split("/")[1]?.split(";")[0]||"bin",j=Ne(this.sessionDir,"../media/inbound");Oe(j,{recursive:!0});let ge=y.documentMessage?.fileName||`${Lt()}.${le}`,he=jt(j,ge);_t(he,C),G={path:he,type:T,fileName:ge},this.log(`WA media saved: ${T} -> ${he}`)}}catch(x){this.log(`WA media download failed: ${x.message}`)}let ce={id:g.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:g.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||S)+"@s.whatsapp.net":S,name:ae,username:S},group:P?{id:$,name:_||$}:void 0,text:m,media:G,replyTo:g.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((g.messageTimestamp||0)*1e3),raw:g,resolvedAgent:U};this.handler(ce).catch(x=>{this.log(`Error handling message: ${x.message}`)})}})}async stop(){this.sock&&(this.sock.end(),this.sock=null)}async send(e){if(!this.sock)return this.log("WhatsApp not connected"),"";let t=e.chatId.includes("@")?e.chatId:`${e.chatId}@s.whatsapp.net`;try{let s=(await this.sock.sendMessage(t,{text:e.text}))?.key?.id||"";return s&&this.sentMessageIds.add(s),s}catch(n){return this.log(`Send error: ${n.message}`),""}}async editMessage(e,t,n){if(!this.sock)return!1;let s=e.includes("@")?e:`${e}@s.whatsapp.net`;try{return await this.sock.sendMessage(s,{text:n,edit:{remoteJid:s,id:t,fromMe:!0}}),!0}catch{return!1}}async sendTyping(e){if(!this.sock)return;let t=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendPresenceUpdate("composing",t)}catch{}}async react(e,t,n="\u{1F440}"){if(!this.sock)return;let s=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendMessage(s,{react:{text:n,key:{remoteJid:s,id:t}}})}catch{}}};import{writeFileSync as Et,mkdirSync as He,existsSync as Be}from"fs";import{resolve as ye}from"path";function O(c,e,t){let n=[];for(let s of c.split(","))if(s==="*")for(let r=e;r<=t;r++)n.push(r);else if(s.includes("/")){let[r,i]=s.split("/"),a=parseInt(i,10),o=r==="*"?e:parseInt(r,10);for(let l=o;l<=t;l+=a)n.push(l)}else if(s.includes("-")){let[r,i]=s.split("-").map(Number);for(let a=r;a<=i;a++)n.push(a)}else n.push(parseInt(s,10));return[...new Set(n)].sort((s,r)=>s-r)}function Wt(c,e,t){let n=c.trim().split(/\s+/);if(n.length!==5)throw new Error(`Invalid cron: ${c}`);let s=O(n[0],0,59),r=O(n[1],0,23),i=O(n[2],1,31),a=O(n[3],1,12),o=O(n[4],0,6),l=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),g=new Date(e.getTime()+6e4);g.setSeconds(0,0);let u=new Date(g.getTime()+366*24*60*60*1e3);for(;g<u;){let f=l.formatToParts(g),m=k=>parseInt(f.find(A=>A.type===k)?.value||"0",10),y=m("minute"),p=m("hour"),d=m("day"),b=m("month"),w=g.getDay();if(s.includes(y)&&r.includes(p)&&i.includes(d)&&a.includes(b)&&o.includes(w))return g;g.setTime(g.getTime()+6e4)}throw new Error(`No next run found for cron "${c}" within 1 year`)}var se=class{jobs=new Map;timers=new Map;registry;hooks;runsDir;running=!1;log;constructor(e,t,n,s=console.error.bind(console,"[cron]")){this.registry=t,this.hooks=n,this.log=s,this.runsDir=ye(process.cwd(),".agentx/cron/runs");for(let[r,i]of Object.entries(e.crons))this.jobs.set(r,{id:r,enabled:i.enabled,schedule:i.schedule,timezone:i.timezone,agent:i.agent,prompt:i.prompt,timeout:i.timeout,model:i.model,onError:i.onError,consecutiveErrors:0,totalRuns:0})}async start(){this.running=!0,Be(this.runsDir)||He(this.runsDir,{recursive:!0});for(let[e,t]of this.jobs){if(!t.enabled){this.log(`Job "${e}" is disabled, skipping`);continue}this.scheduleNext(e)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(e=>e.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}scheduleNext(e){let t=this.jobs.get(e);if(!(!t||!t.enabled||!this.running))try{let n=Wt(t.schedule,new Date,t.timezone);t.nextRun=n;let s=n.getTime()-Date.now();this.log(`Job "${e}" next run: ${n.toISOString()} (in ${Math.round(s/1e3)}s)`);let r=setTimeout(()=>this.executeJob(e),s);this.timers.set(e,r)}catch(n){this.log(`Failed to schedule "${e}": ${n.message}`)}}async executeJob(e){let t=this.jobs.get(e);if(!t||!this.running)return;if(this.hooks?.has("pre:cron-run")){let s=await this.hooks.execute("pre:cron-run",{event:"pre:cron-run",jobId:e,agent:t.agent,prompt:t.prompt});if(s.blocked){this.log(`Job "${e}" blocked by hook: ${s.message}`),this.scheduleNext(e);return}}this.log(`Executing job "${e}" -> agent "${t.agent}"`);let n=new Date;t.lastRun=n,t.totalRuns++;try{let s=await this.registry.execute({message:t.prompt,agentId:t.agent,context:{channel:"cron"}}),r={jobId:e,startedAt:n,completedAt:new Date,success:!s.error,response:s.content,error:s.error,duration:s.duration||Date.now()-n.getTime()};s.error?(t.consecutiveErrors++,this.log(`Job "${e}" failed (${t.consecutiveErrors} consecutive): ${s.error}`),t.onError==="disable"&&t.consecutiveErrors>=3&&(t.enabled=!1,this.log(`Job "${e}" disabled after ${t.consecutiveErrors} consecutive errors`))):(t.consecutiveErrors=0,this.log(`Job "${e}" completed in ${r.duration}ms`)),this.logRun(r),this.hooks?.has("post:cron-run")&&await this.hooks.execute("post:cron-run",{event:"post:cron-run",jobId:e,success:r.success,duration:r.duration,error:r.error?new Error(r.error):void 0})}catch(s){t.consecutiveErrors++,this.log(`Job "${e}" threw: ${s.message}`)}this.scheduleNext(e)}logRun(e){try{let t=ye(this.runsDir,e.jobId);Be(t)||He(t,{recursive:!0});let n=`${e.startedAt.toISOString().replace(/[:.]/g,"-")}.json`;Et(ye(t,n),JSON.stringify(e,null,2))}catch{}}list(){return Array.from(this.jobs.values())}};import{createServer as Nt}from"http";import{writeFileSync as Ht,existsSync as Bt,unlinkSync as Ut,mkdirSync as Gt}from"fs";import{resolve as Ue,dirname as Jt}from"path";var re=class{name="discord";token;agentBinding;handler;client=null;log;constructor(e,t=console.error.bind(console,"[discord]")){this.token=e.token,this.agentBinding=e.agentBinding,this.log=t}onMessage(e){this.handler=e}async start(){let e;try{e=await import("discord.js")}catch{this.log("Discord requires discord.js. Install with:"),this.log(" npm install discord.js");return}let{Client:t,GatewayIntentBits:n}=e;this.client=new t({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]}),this.client.on("ready",()=>{this.log(`Discord connected as ${this.client.user?.tag}`)}),this.client.on("messageCreate",async s=>{if(!this.handler||s.author.bot)return;let r=s.mentions.users.has(this.client.user?.id),i=!s.guild;if(!r&&!i)return;let a=s.content;if(this.client.user&&(a=a.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()),!a)return;let o={id:s.id,channel:"discord",accountId:"default",sender:{id:s.author.id,name:s.author.displayName||s.author.username,username:s.author.username},group:s.guild?{id:s.channelId,name:s.channel?.name||s.channelId}:void 0,text:a,replyTo:s.reference?.messageId,timestamp:s.createdAt,raw:s};this.handler(o).catch(l=>{this.log(`Error handling message: ${l.message}`)})});try{await this.client.login(this.token)}catch(s){this.log(`Discord login failed: ${s.message}`)}}async stop(){this.client&&(this.client.destroy(),this.client=null)}async send(e){if(!this.client)return"";try{let t=await this.client.channels.fetch(e.chatId);return t?.isTextBased()?(await t.send({content:e.text,...e.replyTo?{reply:{messageReference:e.replyTo}}:{}})).id:""}catch(t){return this.log(`Send error: ${t.message}`),""}}async editMessage(e,t,n){if(!this.client)return!1;try{let s=await this.client.channels.fetch(e);return s?.isTextBased()?(await(await s.messages.fetch(t)).edit(n),!0):!1}catch{return!1}}async sendTyping(e){if(this.client)try{let t=await this.client.channels.fetch(e);t?.isTextBased()&&await t.sendTyping()}catch{}}async react(e,t,n="\u{1F440}"){if(this.client)try{let s=await this.client.channels.fetch(e);if(!s?.isTextBased())return;await(await s.messages.fetch(t)).react(n)}catch{}}};import{createServer as Ot}from"http";var ie=class{name="gitlab";config;handler;server;botUsername;sentNoteIds=new Set;log;constructor(e,t=console.error.bind(console,"[gitlab]")){this.config=e,this.log=t}onMessage(e){this.handler=e}async start(){try{let t=await(await fetch(`${this.config.host}/api/v4/user`,{headers:{"PRIVATE-TOKEN":this.config.token}})).json();this.botUsername=t.username,this.log(`Bot user: ${this.botUsername}`)}catch(e){this.log(`Could not resolve bot user: ${e.message}`)}this.server=Ot(async(e,t)=>{e.method==="POST"?await this.handleWebhook(e,t):(t.writeHead(200,{"Content-Type":"text/plain"}),t.end("GitLab webhook endpoint. POST events here."))}),this.server.listen(this.config.webhookPort,()=>{this.log(`GitLab webhook listening on :${this.config.webhookPort}`)})}async stop(){this.server&&this.server.close()}async send(e){let t=e.chatId.split(":");if(t.length<3)return this.log(`Invalid chatId for GitLab reply: ${e.chatId}`),"";let n=t.pop(),s=t.pop(),r=t.join(":"),i=encodeURIComponent(r),a;switch(s){case"issue":a=`${this.config.host}/api/v4/projects/${i}/issues/${n}/notes`;break;case"merge_request":a=`${this.config.host}/api/v4/projects/${i}/merge_requests/${n}/notes`;break;default:return this.log(`Unsupported noteable type: ${s}`),""}try{let o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":this.config.token},body:JSON.stringify({body:e.text})});if(!o.ok){let u=await o.text();return this.log(`GitLab API error: ${o.status} ${u}`),""}let l=await o.json(),g=String(l.id||"");return g&&this.sentNoteIds.add(g),g}catch(o){return this.log(`GitLab send error: ${o.message}`),""}}async handleWebhook(e,t){if(this.config.webhookSecret&&e.headers["x-gitlab-token"]!==this.config.webhookSecret){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}let s=await this.readBody(e),r=s.object_kind||s.event_type||"unknown";switch(this.log(`Event: ${r} from ${s.project?.path_with_namespace||"unknown"}`),r){case"note":await this.handleNote(s,t);break;case"issue":await this.handleIssue(s,t);break;case"merge_request":await this.handleMR(s,t);break;case"pipeline":await this.handlePipeline(s,t);break;default:this.log(`Unhandled event: ${r}`),t.writeHead(200),t.end("ok")}}async handleNote(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes.note,s=e.project.path_with_namespace,r=e.user,i=String(e.object_attributes.id);if(this.botUsername&&r.username===this.botUsername){this.log(`Skipping own comment from ${this.botUsername}`),t.writeHead(200),t.end("ok");return}if(this.sentNoteIds.has(i)){this.sentNoteIds.delete(i),t.writeHead(200),t.end("ok");return}let a="",o="",l="";e.issue?(a="issue",o=String(e.issue.iid),l=e.issue.title):e.merge_request&&(a="merge_request",o=String(e.merge_request.iid),l=e.merge_request.title);let g=this.resolveAgentFromMention(n)||this.resolveAgent(s),u=`${s}:${a}:${o}`,f={id:String(e.object_attributes.id),channel:"gitlab",accountId:"default",sender:{id:u,name:r.name,username:r.username},text:`[GitLab ${a} #${o}: ${l}]
115
+ ${r.name} commented:
116
+ ${n}`,timestamp:new Date,raw:e,resolvedAgent:g};this.handler(f).catch(m=>{this.log(`Error handling note: ${m.message}`)}),t.writeHead(200),t.end("ok")}async handleIssue(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`issue-${n.iid}-${n.action}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:issue:${n.iid}`,name:e.user.name,username:e.user.username},text:`[GitLab Issue #${n.iid} ${n.action}]: ${n.title}
117
+ ${n.description?.slice(0,500)||""}
118
+ URL: ${n.url}`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling issue: ${a.message}`)),t.writeHead(200),t.end("ok")}async handleMR(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`mr-${n.iid}-${n.action}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:merge_request:${n.iid}`,name:e.user.name,username:e.user.username},text:`[GitLab MR !${n.iid} ${n.action}]: ${n.title}
119
+ Branch: ${n.source_branch} -> ${n.target_branch}
120
+ ${n.description?.slice(0,500)||""}
121
+ URL: ${n.url}`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling MR: ${a.message}`)),t.writeHead(200),t.end("ok")}async handlePipeline(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}if(e.object_attributes.status!=="failed"){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`pipeline-${n.id}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:pipeline:${n.id}`,name:e.user.name,username:e.user.username},text:`[GitLab Pipeline FAILED] Project: ${s}
122
+ Ref: ${n.ref}
123
+ Duration: ${n.duration}s
124
+ Please investigate the failure.`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling pipeline: ${a.message}`)),t.writeHead(200),t.end("ok")}resolveAgentFromMention(e){if(!this.config.agentMappings?.length)return;let t=e.toLowerCase(),n=e.match(/@(\w+)/g)?.map(s=>s.slice(1).toLowerCase())||[];for(let s of this.config.agentMappings){for(let r of s.gitlabUsernames)if(n.includes(r.toLowerCase()))return this.log(`Mention @${r} -> agent ${s.agentId}`),s.agentId;for(let r of s.keywords)if(t.includes(r.toLowerCase()))return this.log(`Keyword "${r}" -> agent ${s.agentId}`),s.agentId}}resolveAgent(e){for(let t of this.config.routes)if(t.project===e||t.project==="*")return t.agent}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{try{t(n?JSON.parse(n):{})}catch{t({raw:n})}}),e.on("error",()=>t({}))})}};var H=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new H(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(H.levelOrder[e]<H.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},r=e==="error"?"ERROR":e==="warn"?"WARN":"",i=`[${this.module}]`,a=r?`${i} ${r}: ${t}`:`${i} ${t}`;console.error(a)}},N=H;J(N,"levelOrder",{debug:0,info:1,warn:2,error:3});var oe=class{registry;config;log;constructor(e,t={},n=console.error.bind(console,"[webhook]")){this.registry=e,this.config=t,this.log=n}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),r=s[0],i=s[1];if(!r){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let a=await this.readBody(e),o=i||this.detectSource(e.headers),l=this.buildSummary(o,a,e.headers);this.log(`Webhook [${o}] -> ${r}: ${l.slice(0,100)}`);try{let g=await this.registry.execute({message:l,agentId:r,context:{channel:`webhook:${o}`,sender:`webhook:${o}`}});this.sendJson(t,g.error?500:200,{ok:!g.error,agent:r,source:o,response:g.content?.slice(0,500),error:g.error,duration:g.duration})}catch(g){this.sendJson(t,500,{error:g.message})}}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let i=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",o=t.user?.name||t.user_username||"";if(s.push(`Event: ${i}`),a&&s.push(`Project: ${a}`),o&&s.push(`User: ${o}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let g of t.commits.slice(0,3))s.push(` - ${g.message?.split(`
125
+ `)[0]||"no message"} (${g.author?.name||""})`)}let l=t.object_attributes;if(l?.title&&(s.push(`Title: ${l.title}`),s.push(`State: ${l.state||""}`),s.push(`Action: ${l.action||""}`),l.source_branch&&s.push(`Branch: ${l.source_branch} -> ${l.target_branch}`),l.url&&s.push(`URL: ${l.url}`)),l?.iid&&!l?.source_branch&&(s.push(`Issue #${l.iid}: ${l.title||""}`),l.description&&s.push(`Description: ${l.description.slice(0,200)}`)),t.object_kind==="pipeline"){let g=t.object_attributes;s.push(`Pipeline: ${g?.status||""} (${g?.ref||""})`),s.push(`Duration: ${g?.duration||0}s`)}break}case"github":{let i=n["x-github-event"]||"event",a=t.repository?.full_name||"",o=t.sender?.login||"";if(s.push(`Event: ${i}`),a&&s.push(`Repository: ${a}`),o&&s.push(`Sender: ${o}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
126
+ `)[0]||""} (${u.author?.name||""})`);let l=t.pull_request;l&&(s.push(`PR #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${l.head?.ref} -> ${l.base?.ref}`));let g=t.issue;g&&(s.push(`Issue #${g.number}: ${g.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let i=t.type||"event",a=t.data?.object||{};s.push(`Event: ${i}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let i=n["sentry-hook-resource"]||"event";s.push(`Resource: ${i}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(i=>i.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let r=JSON.stringify(t).slice(0,500);s.push(`Body: ${r}`)}return s.join(`
127
+ `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{try{t(n?JSON.parse(n):{})}catch{t({raw:n})}}),e.on("error",()=>t({}))})}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};var Ge=class{config;registry;router;cron;mesh;hooks;httpServer;webhooks;log;constructor(e){let t=new N("agentx");this.log=t.asConsoleLog(),this.log("Loading configuration..."),this.config=xe(e);let n=Ae(this.config);for(let s of n)this.log(` \u26A0 ${s}`);this.hooks=new ke,ve(process.cwd(),this.hooks),this.registry=new Y(this.config,this.log),this.router=new W(this.registry,this.config,this.hooks,this.log),this.webhooks=new oe(this.registry,{},this.log),this.cron=new se(this.config,this.registry,this.hooks,this.log),this.config.mesh.enabled&&(this.mesh=new K(this.config,this.log),this.router.setMesh(this.mesh))}async start(){this.log(""),this.log(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),this.log(" \u2502 agentx daemon \u2502"),this.log(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),this.log(""),this.log(` Node: ${this.config.node.name} (${this.config.node.id})`),this.log(` Bind: ${this.config.node.bind}`),this.log(""),await this.startChannels(),await this.cron.start(),this.mesh&&await this.mesh.start(),await this.startHttpApi(),this.log(""),this.log(" Agents:");for(let r of this.registry.list())this.log(` ${r.id} (${r.tier}) \u2192 ${r.workspace}`);let e=this.cron.list();if(e.length){this.log(""),this.log(" Cron Jobs:");for(let r of e){let i=r.enabled?"enabled":"disabled";this.log(` ${r.id} [${i}] \u2192 ${r.agent} (${r.schedule})`)}}if(this.mesh){this.log(""),this.log(" Mesh Peers:");for(let r of this.mesh.directory()){let i=r.healthy?"\u2713":"\u2717";this.log(` ${i} ${r.peer} (${r.peerUrl})`)}}this.log(""),this.log(" Ready."),this.log("");let t=Ue(process.cwd(),".agentx/daemon.pid");Gt(Jt(t),{recursive:!0}),Ht(t,String(process.pid)),this.log(` PID: ${process.pid} (${t})`),process.on("uncaughtException",r=>{this.log(`UNCAUGHT EXCEPTION: ${r.message}`),this.log(r.stack||"")}),process.on("unhandledRejection",r=>{this.log(`UNHANDLED REJECTION: ${r}`)});let n=!1,s=async r=>{n||(n=!0,this.log(`
128
+ Received ${r}, shutting down gracefully...`),await this.stop())};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM"))}async stop(){let e=Date.now();try{this.log(" Stopping channels..."),await Promise.race([this.router.stopAll(),new Promise(t=>setTimeout(t,5e3))])}catch(t){this.log(` Channel stop error: ${t.message}`)}try{this.log(" Stopping crons..."),await this.cron.stop()}catch{}try{this.mesh&&(this.log(" Stopping mesh..."),await this.mesh.stop())}catch{}this.httpServer&&this.httpServer.close();try{let t=Ue(process.cwd(),".agentx/daemon.pid");Bt(t)&&Ut(t)}catch{}this.log(` Shutdown complete (${Date.now()-e}ms)`),process.exit(0)}async startChannels(){if(this.config.channels.telegram.enabled){let e=this.config.channels.telegram.accounts;if(Object.keys(e).length>0){let t=new te(e,this.log);this.router.addChannel(t),this.log(" Telegram: enabled")}}if(this.config.channels.whatsapp.enabled){let e=new ne({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes},this.log);this.router.addChannel(e),this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes)`)}if(this.config.channels.discord?.enabled&&this.config.channels.discord.token){let e=new re({token:this.config.channels.discord.token,agentBinding:this.config.channels.discord.agentBinding},this.log);this.router.addChannel(e),this.log(" Discord: enabled")}if(this.config.channels.gitlab?.enabled&&this.config.channels.gitlab.token){let e=new ie({webhookPort:this.config.channels.gitlab.webhookPort,webhookSecret:this.config.channels.gitlab.webhookSecret,host:this.config.channels.gitlab.host,token:this.config.channels.gitlab.token,routes:this.config.channels.gitlab.routes,agentMappings:this.config.channels.gitlab.agentMappings},this.log);this.router.addChannel(e),this.log(` GitLab: enabled (${this.config.channels.gitlab.routes.length} project routes, webhook :${this.config.channels.gitlab.webhookPort})`)}await this.router.startAll()}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=Nt(async(s,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){r.writeHead(204),r.end();return}await this.handleHttp(s,r)}),this.httpServer.on("error",s=>{s.code==="EADDRINUSE"?(this.log(` ERROR: Port ${n} is already in use. Retrying in 5s...`),setTimeout(()=>{this.httpServer?.close(),this.httpServer?.listen(n,e||"0.0.0.0")},5e3)):this.log(` HTTP error: ${s.message}`)}),this.httpServer.listen(n,e||"0.0.0.0",()=>{this.log(` HTTP API: http://${e||"0.0.0.0"}:${n}`)})}async handleHttp(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`).pathname;try{if(e.method==="POST"&&s.startsWith("/webhook/")){await this.webhooks.handle(e,t,s);return}if(e.method==="POST"&&(s==="/v1/chat/completions"||s.match(/^\/llm\/[^/]+\/v1\/chat\/completions$/))){await this.handleOpenAICompat(e,t,s);return}switch(`${e.method} ${s}`){case"GET /health":this.json(t,200,{status:"ok",node:this.config.node,uptime:process.uptime(),agents:this.registry.list(),crons:this.cron.list().map(r=>({id:r.id,enabled:r.enabled,nextRun:r.nextRun})),mesh:this.mesh?.directory()||[],usage:this.registry.getTodayUsage()});break;case"GET /usage":this.json(t,200,this.registry.getUsage(7));break;case"GET /agents":this.json(t,200,this.registry.list());break;case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"POST /task":{let r=await we(e);if(!r.agent||!r.message){this.json(t,400,{error:"Missing: agent, message"});return}let i=await this.registry.execute({agentId:r.agent,message:r.message,context:r.context});this.json(t,i.error?500:200,i);break}case"POST /mesh/task":{let r=await we(e);if(!r.peer||!r.message){this.json(t,400,{error:"Missing: peer, message"});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let i=await this.mesh.sendTask(r.peer,r.message);this.json(t,200,{response:i});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(r=>({id:r.id,name:r.name,description:`Agent "${r.name}" (${r.tier})`,tags:[r.tier]})),defaultInputModes:["text"],defaultOutputModes:["text"]});break;default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /mesh","POST /task { agent, message, context? }","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","GET /.well-known/agent-card.json"]})}}catch(r){this.json(t,500,{error:r.message})}}async handleOpenAICompat(e,t,n){let s=await we(e),i=n.match(/^\/llm\/([^/]+)\//)?.[1]||s.model||"atlas",a=s.messages||[],o=[...a].reverse().find(f=>f.role==="user");if(!o?.content){this.json(t,400,{error:{message:"No user message found",type:"invalid_request_error"}});return}let l=a.slice(0,-1).map(f=>`${f.role==="user"?"User":"Assistant"}: ${f.content.slice(0,200)}`),g=l.length>0?`[Conversation]
129
+ ${l.slice(-10).join(`
130
+ `)}
131
+
132
+ `:"";if(s.stream===!0){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let f=`chatcmpl-${Date.now().toString(36)}`,m=await this.registry.execute({agentId:i,message:g+o.content,context:{channel:"api",sender:"openai-compat"}}),y=m.error||m.content||"",p={id:f,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,delta:{role:"assistant",content:y},finish_reason:"stop"}]};t.write(`data: ${JSON.stringify(p)}
133
+
134
+ `),t.write(`data: [DONE]
135
+
136
+ `),t.end()}else{let f=await this.registry.execute({agentId:i,message:g+o.content,context:{channel:"api",sender:"openai-compat"}}),m=f.error||f.content||"",y=Math.ceil(m.length/4);this.json(t,200,{id:`chatcmpl-${Date.now().toString(36)}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:{role:"assistant",content:m},finish_reason:"stop"}],usage:{prompt_tokens:Math.ceil(o.content.length/4),completion_tokens:y,total_tokens:Math.ceil(o.content.length/4)+y}})}}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};async function we(c){return new Promise((e,t)=>{let n="";c.on("data",s=>n+=s.toString()),c.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),c.on("error",t)})}import Ft from"path";import Kt from"fs-extra";function us(){let c=Ft.join("package.json");return Kt.readJSONSync(c)}export{F as a,K as b,Ye as c,xe as d,Ae as e,nt as f,rt as g,it as h,Ce as i,E as j,Y as k,W as l,te as m,ne as n,se as o,Ge as p,us as q};
137
+ //# sourceMappingURL=chunk-NGKOM4ZZ.js.map