agentix-cli 0.20.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-57MG4LBM.js → agent-Y4U4R3ZZ.js} +2 -2
- package/dist/{board-dashboard-HXDOYGIG.js → board-dashboard-2CPBWFOB.js} +339 -97
- package/dist/board-dashboard-2CPBWFOB.js.map +1 -0
- package/dist/chunk-2HXSJYAJ.js +15 -0
- package/dist/chunk-2HXSJYAJ.js.map +1 -0
- package/dist/{chunk-QW2OYR3N.js → chunk-ABVZHJUO.js} +2 -2
- package/dist/chunk-BHSPAP4U.js +44 -0
- package/dist/chunk-BHSPAP4U.js.map +1 -0
- package/dist/chunk-CO4YCIIA.js +13 -0
- package/dist/chunk-CO4YCIIA.js.map +1 -0
- package/dist/{chunk-4MREHZP5.js → chunk-GOLZ6NEL.js} +2 -2
- package/dist/chunk-GOLZ6NEL.js.map +1 -0
- package/dist/chunk-GSX4NK2N.js +2 -0
- package/dist/chunk-GSX4NK2N.js.map +1 -0
- package/dist/chunk-GV7S5BAX.js +2 -0
- package/dist/chunk-GV7S5BAX.js.map +1 -0
- package/dist/{chunk-WPPUOTY6.js → chunk-KX626FN4.js} +2 -2
- package/dist/chunk-OPKQNLGX.js +450 -0
- package/dist/chunk-OPKQNLGX.js.map +1 -0
- package/dist/chunk-OZOQKPJV.js +102 -0
- package/dist/chunk-OZOQKPJV.js.map +1 -0
- package/dist/{chunk-DLVOHCTA.js → chunk-P3TJHGO5.js} +2 -2
- package/dist/chunk-SZDACK6O.js +2 -0
- package/dist/chunk-SZDACK6O.js.map +1 -0
- package/dist/{chunk-TC3BSUP7.js → chunk-VYLZ7UYM.js} +2 -2
- package/dist/{chunk-WFHIIVLL.js → chunk-WHP4I44J.js} +75 -51
- package/dist/chunk-WHP4I44J.js.map +1 -0
- package/dist/chunk-X5D5AV5N.js +833 -0
- package/dist/chunk-X5D5AV5N.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/{config-QXWKEQON.js → config-BLOKGMER.js} +2 -2
- package/dist/config-mutator-RG7QY2EL.js +2 -0
- package/dist/doctor-ZTECTUHX.js +2 -0
- package/dist/index.d.ts +140 -3
- package/dist/index.js +1 -1
- package/dist/program-GZOJIWTB.js +2 -0
- package/dist/registry-QZIUSQ5J.js +2 -0
- package/dist/runner-BFYDWPUO.js +2 -0
- package/dist/scheduler-B2BQPV4M.js +2 -0
- package/dist/store-I3HEWVLQ.js +2 -0
- package/dist/store-I3HEWVLQ.js.map +1 -0
- package/dist/types-Y6ZCZ52Z.js +2 -0
- package/dist/types-Y6ZCZ52Z.js.map +1 -0
- package/dist/web/workflow-editor.global.js +12 -10
- package/dist/web/workflow-editor.global.js.map +1 -1
- package/dist/workspace-setup-DQCZX2NE.js +2 -0
- package/dist/workspace-setup-DQCZX2NE.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-HXDOYGIG.js.map +0 -1
- package/dist/chunk-23AUU4S2.js +0 -102
- package/dist/chunk-23AUU4S2.js.map +0 -1
- package/dist/chunk-4MREHZP5.js.map +0 -1
- package/dist/chunk-6B74TO2J.js +0 -743
- package/dist/chunk-6B74TO2J.js.map +0 -1
- package/dist/chunk-7GVXCOLO.js +0 -440
- package/dist/chunk-7GVXCOLO.js.map +0 -1
- package/dist/chunk-E4ZZILAK.js +0 -15
- package/dist/chunk-E4ZZILAK.js.map +0 -1
- package/dist/chunk-MBOLXKA2.js +0 -6
- package/dist/chunk-MBOLXKA2.js.map +0 -1
- package/dist/chunk-WFHIIVLL.js.map +0 -1
- package/dist/chunk-ZE2YFX4K.js +0 -45
- package/dist/chunk-ZE2YFX4K.js.map +0 -1
- package/dist/config-mutator-53XGR2NT.js +0 -2
- package/dist/doctor-SEOUFHSL.js +0 -2
- package/dist/program-WWCXMRU2.js +0 -2
- package/dist/registry-HM4ELSXS.js +0 -2
- package/dist/scheduler-XVFIK4XH.js +0 -2
- package/dist/workspace-setup-FPGN5VNY.js +0 -2
- /package/dist/{agent-57MG4LBM.js.map → agent-Y4U4R3ZZ.js.map} +0 -0
- /package/dist/{chunk-QW2OYR3N.js.map → chunk-ABVZHJUO.js.map} +0 -0
- /package/dist/{chunk-WPPUOTY6.js.map → chunk-KX626FN4.js.map} +0 -0
- /package/dist/{chunk-DLVOHCTA.js.map → chunk-P3TJHGO5.js.map} +0 -0
- /package/dist/{chunk-TC3BSUP7.js.map → chunk-VYLZ7UYM.js.map} +0 -0
- /package/dist/{config-QXWKEQON.js.map → config-BLOKGMER.js.map} +0 -0
- /package/dist/{config-mutator-53XGR2NT.js.map → config-mutator-RG7QY2EL.js.map} +0 -0
- /package/dist/{doctor-SEOUFHSL.js.map → doctor-ZTECTUHX.js.map} +0 -0
- /package/dist/{program-WWCXMRU2.js.map → program-GZOJIWTB.js.map} +0 -0
- /package/dist/{registry-HM4ELSXS.js.map → registry-QZIUSQ5J.js.map} +0 -0
- /package/dist/{scheduler-XVFIK4XH.js.map → runner-BFYDWPUO.js.map} +0 -0
- /package/dist/{workspace-setup-FPGN5VNY.js.map → scheduler-B2BQPV4M.js.map} +0 -0
package/dist/chunk-6B74TO2J.js
DELETED
|
@@ -1,743 +0,0 @@
|
|
|
1
|
-
import{f as Dt,g as Nt,i as Lt,j as Bt,k as Gt,q as Ft}from"./chunk-E4ZZILAK.js";import{b as Ut}from"./chunk-ZE2YFX4K.js";import{A as Pt,B as Et,h as xt,n as At,o as Ye}from"./chunk-TC3BSUP7.js";import{b as St}from"./chunk-SFQUP3BP.js";import{a as E,b as Ot,c as F,d as H,f as Qe}from"./chunk-QW2OYR3N.js";import{e as Ve,f as jt}from"./chunk-MBOLXKA2.js";import{e as Mt,f as X,g as Rt,i as _t}from"./chunk-23AUU4S2.js";import{a as Ct}from"./chunk-5F3J55LG.js";import{c as _}from"./chunk-4MREHZP5.js";import{a as pe}from"./chunk-VJUTQAPJ.js";import{a as It,d as Tt}from"./chunk-DJEZ2HVU.js";import{e as z}from"./chunk-DSYKYZMT.js";import{b as ue}from"./chunk-4YCH6IZV.js";var Qn={name:"agentx",version:"0.1.0"},Zn="2024-11-05",es={tools:{},elicitation:{form:{}}},ts=0;async function Ht(c,e){let t=++ts;return q({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:c,requestedSchema:e}}),new Promise(n=>{se.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{se.has(`elicit-${t}`)&&(se.delete(`elicit-${t}`),n(null))},6e4)})}var se=new Map,P=process.env.AGENTX_DAEMON_URL||"http://localhost:19900",ns=/\x1B\[[0-9;]*[A-Za-z]/g;function Z(c){return c.replace(ns,"")}var ss=[{name:"agentx_generate",description:"Generate code, components, pages, APIs, documents, tests, workflows, schemas, emails, diagrams, and more using AI. Understands the project's tech stack, schemas, and skills automatically.",inputSchema:{type:"object",properties:{task:{type:"string",description:"Describe what to generate (e.g., 'a responsive pricing card', 'REST API for users', 'GitHub Actions CI pipeline')"},type:{type:"string",description:"Output type: component, page, api, website, document, script, config, skill, media, report, test, workflow, schema, email, diagram, auto",default:"auto"},output_dir:{type:"string",description:"Optional output directory (relative to project root)"},cwd:{type:"string",description:"Project working directory (defaults to current directory)"}},required:["task"]}},{name:"agentx_inspect",description:"Analyze a project and return its tech stack, frameworks, databases, schemas, installed skills, and dependencies. Use this to understand a project before generating code.",inputSchema:{type:"object",properties:{cwd:{type:"string",description:"Project working directory (defaults to current directory)"}}}},{name:"agentx_skill_match",description:"Find installed skills that are relevant to a given task description. Returns matched skills with relevance scores.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task to match skills against"},cwd:{type:"string",description:"Project working directory"}},required:["task"]}},{name:"agentx_detect_output_type",description:"Auto-detect the best output type for a given task description based on keyword analysis.",inputSchema:{type:"object",properties:{task:{type:"string",description:"The task description to analyze"}},required:["task"]}},{name:"agentx_send",description:"Low-level outbound send when you ALREADY have a channel-native chatId (Telegram numeric chat id, GitLab 'group/project:issue:123', WhatsApp '+phone@s.whatsapp.net'). For sending to another agent by name, use agentx_send_agent instead. For sending to a human contact by name, use agentx_send_contact instead.",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Target channel: telegram, whatsapp, gitlab, discord"},chatId:{type:"string",description:'Chat ID. Telegram: numeric ("-1001234567890"). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},text:{type:"string",description:"Message text to send"},agentId:{type:"string",description:"Agent ID to send as (determines bot account on Telegram, GitLab token, etc.)"}},required:["channel","chatId","text"]}},{name:"agentx_send_agent",description:"Send a message to ANOTHER AGENT by exact agentId \u2014 uses the AgentX A2A mesh (or local registry when the agent lives on this daemon). This is the deterministic path for agent-to-agent communication; it never falls through to a contact lookup, so an unknown agentId returns 404 with the list of known agents instead of silently sending to a similarly-named human. Use this when the target is a registered agent.",inputSchema:{type:"object",properties:{agentId:{type:"string",description:"Exact agentId of the target agent (e.g. 'clawd', 'atlas'). Must match an agent in this daemon's registry or in a healthy mesh peer's directory."},text:{type:"string",description:"Message to send to the target agent"},senderAgentId:{type:"string",description:"Optional. The agentId on whose behalf this call is being made. Recorded in route_traces and (with A2A protocolVersion >= 2) validated by the receiving daemon."}},required:["agentId","text"]}},{name:"agentx_recent",description:"Read the most recent messages from a chat across ALL agents that have sessions for it. Returns inbound + each agent's replies in chronological order, so you can see what's actually been said in a Telegram chat / GitLab thread / WhatsApp DM regardless of which agent recorded it. Use this BEFORE speculating about what was sent \u2014 the cx/devops/marketing thread on 2026-04-29 about a Nadia/CX bot mixup would have been resolved in one call instead of three agents speculating. Bounded by sinceISO (default: last 24h) and limit (default: 30, max: 200).",inputSchema:{type:"object",properties:{channel:{type:"string",description:"Channel name. Examples: telegram, whatsapp, gitlab, github, discord, cron, api, a2a."},chatId:{type:"string",description:'Channel-native chat id. Telegram: numeric (e.g. "1816212449" for a DM, "-1001234567890" for a group). GitLab: "group/project:issue:123". WhatsApp: "+phone@s.whatsapp.net".'},sinceISO:{type:"string",description:"Optional ISO timestamp lower bound. Defaults to 24h ago."},limit:{type:"number",description:"Optional cap on returned messages. Default 30, max 200."}},required:["channel","chatId"]}},{name:"agentx_send_contact",description:"Send a message to a HUMAN CONTACT by name. Resolves through .agentx/contacts.json (id \u2192 exact alias \u2192 fuzzy substring). Refuses fuzzy matches without confirmed:true so the agent must ask the user to disambiguate before sending. Refuses when the name also matches a registered agent (use agentx_send_agent for those). Use this when the target is a person, not a bot.",inputSchema:{type:"object",properties:{contactName:{type:"string",description:"Free-form contact name. Tried as id first, then alias, then fuzzy substring."},text:{type:"string",description:"Message to send to the contact"},channel:{type:"string",description:"Optional explicit channel (telegram | whatsapp | gitlab | discord). Defaults to the first channel configured for the contact."},confirmed:{type:"boolean",description:"Pass true ONLY after the user has confirmed a fuzzy match. Without it, fuzzy matches return 409 with the candidate so you can ask the user."},agentId:{type:"string",description:"Optional agent identity used for the outbound send (determines bot account / token)."}},required:["contactName","text"]}},{name:"agentx_task",description:"Send a task to a specific agent on the daemon. The agent processes it and returns a response. Use to delegate work to specialized agents.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to send the task to"},message:{type:"string",description:"Task message for the agent"}},required:["agent","message"]}},{name:"agentx_agents",description:"List all agents registered on the daemon with their status (active tasks, total tasks, errors, tier).",inputSchema:{type:"object",properties:{}}},{name:"agentx_health",description:"Get the daemon health status including node info, agents, crons, mesh peers, and uptime.",inputSchema:{type:"object",properties:{}}},{name:"agentx_crons",description:"List cron jobs and their health. Shows healthy, failing, disabled counts and per-job status with consecutive error counts.",inputSchema:{type:"object",properties:{}}},{name:"agentx_debug",description:"Toggle debug mode on the daemon. Enable verbose logging for specific categories (webhook, agent, channel, cron, mesh, context, memory, all) or disable it.",inputSchema:{type:"object",properties:{action:{type:"string",description:'"on", "off", or "status"',default:"status"},categories:{type:"string",description:'Comma-separated categories to enable (e.g. "webhook,agent"). Only used with action=on.'}}}},{name:"agentx_wiki_query",description:"Query the agentx institutional wiki: a cross-agent knowledge base organized by article type (person, project, place, concept, event, decision, pattern). Use this BEFORE grep/memory-search when the question is about who / what happened / what we decided / how we do something. The query walks the catalog + wikilink graph and returns a synthesized answer with citations.",inputSchema:{type:"object",properties:{question:{type:"string",description:"The question to answer from the wiki, in natural language."},agent:{type:"string",description:"Which agent's wiki to query (default: first agent with a catalog). Each agent has its own wiki dir under .agentx/wiki/agents/<id>/"},wiki_dir:{type:"string",description:"Wiki root dir (default: <cwd>/.agentx/wiki)."},max_hops:{type:"number",description:"Wikilink hops from candidates (default 2, max 3).",default:2}},required:["question"]}},{name:"agentx_wiki_patch",description:"Edit a single wiki article via an LLM-applied instruction and write the result. Use this for targeted fixes, additions, or clarifications to an existing article when you already know what's wrong. For brand-new articles, use `agentx_wiki_interview` instead.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose wiki owns the article (required)."},title_or_path:{type:"string",description:"Article title (case-insensitive) or relative path like 'people/anis.md'."},instruction:{type:"string",description:"Plain-English edit instruction (e.g. 'Add a section on the KSA Supabase rollout'). The LLM makes the minimum edit that satisfies it."},model:{type:"string",description:"Claude model for the patch (default: sonnet).",default:"sonnet"},dry_run:{type:"boolean",description:"Preview the patched body without writing.",default:!1}},required:["agent","title_or_path","instruction"]}},{name:"agentx_wiki_interview",description:"Run a scripted wiki interview \u2014 synthesize ONE typed article from a list of Q&A answers, and save it. Non-interactive: caller supplies the answers upfront. Use for capturing tacit knowledge (person/project/decision/pattern/...) that never hit a channel. For editing an existing article, use `agentx_wiki_patch`.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID that will own the new article (required)."},topic:{type:"string",description:"What the article is about \u2014 e.g. 'MTGL deployment procedure', 'Yousef Al-Fahad', 'Hackathonat KSA migration'."},type:{type:"string",description:"Article type: person | project | place | concept | event | decision | pattern"},answers:{type:"array",description:"Answers to the type-specific question bank (one per question, in order). Empty string = skip that question. Final entry is typically 'save'.",items:{type:"string"}},model:{type:"string",description:"Synthesis model (default: sonnet).",default:"sonnet"},commit:{type:"boolean",description:"Write the article (true) or just preview (false).",default:!0}},required:["agent","topic","type","answers"]}},{name:"agentx_graph_review",description:"Triage pending intent-graph classifications via the configured review agent. The review agent sees each pending classification, may call `wiki query` for institutional context, and decides approve/reject/skip. Structural changes (new org, new unit) gate here; leaf additions auto-approve without this step.",inputSchema:{type:"object",properties:{max:{type:"number",description:"Cap reviews this run (default 20).",default:20},dry_run:{type:"boolean",description:"Show decisions but don't apply approvals/rejections.",default:!1},agent:{type:"string",description:"Override the review agent (defaults to graph.reviewAgent or graph.draftAgent)."}}}}];async function is(c,e){let t=e.cwd||process.cwd();switch(c){case"agentx_generate":{let n=e.task,s=e.type||"auto",i=e.output_dir,r=await Et({task:n,outputType:s,outputDir:i,cwd:t,overwrite:!0,dryRun:!1,context7:!0,interactive:!1,maxSteps:5}),o=[];return r.content&&o.push(r.content),r.files.written.length&&o.push(`
|
|
2
|
-
Created ${r.files.written.length} file(s):
|
|
3
|
-
${r.files.written.map(a=>` - ${a}`).join(`
|
|
4
|
-
`)}`),r.files.skipped.length&&o.push(`
|
|
5
|
-
Skipped ${r.files.skipped.length} existing file(s):
|
|
6
|
-
${r.files.skipped.map(a=>` - ${a}`).join(`
|
|
7
|
-
`)}`),r.followUp&&o.push(`
|
|
8
|
-
Needs clarification: ${r.followUp}`),{content:[{type:"text",text:o.join(`
|
|
9
|
-
`)||"Generation complete."}]}}case"agentx_inspect":{let n=await Pt(t,"inspect",{context7:{enabled:!1}}),s={languages:n.techStack.languages,frameworks:n.techStack.frameworks,packageManager:n.techStack.packageManager,databases:n.techStack.databases,styling:n.techStack.styling,testing:n.techStack.testing,deployment:n.techStack.deployment,monorepo:n.techStack.monorepo,srcDir:n.techStack.srcDir,dependencyCount:Object.keys(n.techStack.dependencies).length,devDependencyCount:Object.keys(n.techStack.devDependencies).length,schemas:{database:n.schemas.database?{type:n.schemas.database.type,tables:n.schemas.database.tables}:null,api:n.schemas.api?{type:n.schemas.api.type}:null,env:n.schemas.env?{variableCount:n.schemas.env.variables.length}:null,models:n.schemas.models?.map(i=>i.path)||[]},skills:n.skills.map(i=>({name:i.frontmatter.name,description:i.frontmatter.description,source:i.source}))};return{content:[{type:"text",text:`Project analysis:
|
|
10
|
-
|
|
11
|
-
${St(n.techStack)}
|
|
12
|
-
|
|
13
|
-
${JSON.stringify(s,null,2)}`}]}}case"agentx_skill_match":{let n=e.task,s=await It(t),i=Tt(s,n);return i.length?{content:[{type:"text",text:`Matching skills:
|
|
14
|
-
|
|
15
|
-
${i.map(o=>`- **${o.skill.frontmatter.name}** (relevance: ${(o.relevance*100).toFixed(0)}%)
|
|
16
|
-
${o.skill.frontmatter.description}
|
|
17
|
-
Match: ${o.matchReason}`).join(`
|
|
18
|
-
|
|
19
|
-
`)}`}]}:{content:[{type:"text",text:"No matching skills found. Install skills with: agentx skill install <owner/repo>"}]}}case"agentx_detect_output_type":{let n=e.task;return{content:[{type:"text",text:`Detected output type: ${xt(void 0,n)}`}]}}case"agentx_send":{let n=e.channel,s=e.chatId,i=e.text;if(!n||!s||!i){let a=await fetch(`${P}/channels`).catch(()=>null),l=a?await a.json():["telegram","whatsapp","gitlab","discord"],d=await Ht("Please provide the message details:",{type:"object",properties:{channel:{type:"string",title:"Channel",description:"Target channel",enum:l,default:n||l[0]},chatId:{type:"string",title:"Chat ID",description:"Telegram: numeric ID. GitLab: group/project:issue:123",default:s||""},text:{type:"string",title:"Message",description:"Message text to send",default:i||""}},required:["channel","chatId","text"]});if(!d)return{content:[{type:"text",text:"Send cancelled."}]};n=d.channel,s=d.chatId,i=d.text}let r=await fetch(`${P}/send`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:n,chatId:s,text:i,agentId:e.agentId})}),o=await r.json();return r.ok?{content:[{type:"text",text:`Message sent. ID: ${o.messageId||"ok"}`}]}:{content:[{type:"text",text:`Error: ${o.error||r.statusText}`}]}}case"agentx_send_agent":{let n=e.agentId,s=e.text,i=e.senderAgentId;if(!n||!s)return{content:[{type:"text",text:"Error: agentId and text are required."}]};let r=await fetch(`${P}/send/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:n,text:s,senderAgentId:i})}),o=await r.json();if(!r.ok){let l=Array.isArray(o?.known)?` Known agents: ${o.known.join(", ")}.`:"";return{content:[{type:"text",text:`Error: ${o.error||r.statusText}.${l}`}]}}let a=o.peer?` (via mesh peer ${o.peer})`:"";return{content:[{type:"text",text:`Message sent to agent ${n}${a}. ID: ${o.messageId||"ok"}`}]}}case"agentx_recent":{let n=e.channel,s=e.chatId,i=e.sinceISO,r=e.limit;if(!n||!s)return{content:[{type:"text",text:"Error: channel and chatId are required."}]};let o=await fetch(`${P}/chat/recent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({channel:n,chatId:s,sinceISO:i,limit:r})}),a=await o.json();if(!o.ok)return{content:[{type:"text",text:`Error: ${a.error||o.statusText}`}]};let l=a.messages||[];return l.length===0?{content:[{type:"text",text:`No messages in ${n}/${s} within the requested window.`}]}:{content:[{type:"text",text:l.map(g=>{let h=g.ts.slice(11,16),p=g.ts.slice(0,10),u=g.role==="agent"?`${g.agentId}`:g.senderName||"user";return`[${p} ${h}] ${u}: ${g.content}`}).join(`
|
|
20
|
-
`)}]}}case"agentx_send_contact":{let n=e.contactName,s=e.text,i=e.channel,r=e.confirmed===!0,o=e.agentId;if(!n||!s)return{content:[{type:"text",text:"Error: contactName and text are required."}]};let a=await fetch(`${P}/send/contact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contactName:n,text:s,channel:i,confirmed:r,agentId:o})}),l=await a.json();return a.status===409?{content:[{type:"text",text:`Refused: ${JSON.stringify(l,null,2)}`}]}:a.ok?{content:[{type:"text",text:`Message sent to contact ${l.contactId} via ${l.channel}. ID: ${l.messageId||"ok"}`}]}:{content:[{type:"text",text:`Error: ${l.error||a.statusText}`}]}}case"agentx_task":{let n=e.agent,s=e.message;if(!n||!s){let o=await fetch(`${P}/agents`).catch(()=>null),a=o?(await o.json()).map(d=>d.id):[],l=await Ht("Which agent should handle this task?",{type:"object",properties:{agent:{type:"string",title:"Agent",description:"Agent ID",...a.length?{enum:a}:{},default:n||""},message:{type:"string",title:"Task",description:"Task message for the agent",default:s||""}},required:["agent","message"]});if(!l)return{content:[{type:"text",text:"Task cancelled."}]};n=l.agent,s=l.message}let r=await(await fetch(`${P}/task`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:n,message:s})})).json();return r.error?{content:[{type:"text",text:`Agent error: ${r.error}`}]}:{content:[{type:"text",text:r.content||"Task completed."}]}}case"agentx_agents":return{content:[{type:"text",text:(await(await fetch(`${P}/agents`)).json()).map(r=>`${r.id} (${r.name}) \u2014 ${r.tier}, active: ${r.active}/${r.total}, errors: ${r.errors}`).join(`
|
|
21
|
-
`)||"No agents."}]};case"agentx_health":{let s=await(await fetch(`${P}/health`)).json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}case"agentx_crons":{let s=await(await fetch(`${P}/crons/health`)).json(),i=`Healthy: ${s.healthy}, Failing: ${s.failing}, Disabled: ${s.disabled}, Missed: ${s.missed}`,r=(s.jobs||[]).map(o=>` ${o.id}: ${o.status}${o.consecutiveErrors?` (${o.consecutiveErrors} errors)`:""}${o.lastError?` \u2014 ${o.lastError.slice(0,100)}`:""}`).join(`
|
|
22
|
-
`);return{content:[{type:"text",text:`${i}
|
|
23
|
-
|
|
24
|
-
${r}`}]}}case"agentx_wiki_query":{let n=String(e.question||"").trim();if(!n)return{content:[{type:"text",text:"Error: `question` is required."}]};let{WikiHub:s}=await import("./wiki-53W5NLZV.js"),{agenticQuery:i}=await import("./query-HZYYRCLU.js"),{resolve:r}=await import("path"),o=e.wiki_dir||r(process.cwd(),".agentx/wiki"),a=new s(o,void 0,"graph"),l=e.agent||"";if(!l){let{existsSync:m}=await import("fs");for(let y of a.listAgents()){let b=r(a.getAgentWiki(y).baseDir,"_index.md");if(m(b)){l=y;break}}}if(!l)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let d=a.getAgentWiki(l),g=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,h=await i(n,d,l,{maxHops:g});if(h.status!=="ok")return{content:[{type:"text",text:`Query returned status "${h.status}"${h.error?`: ${h.error}`:""}`}]};let p=h.citations.map(m=>` - ${m.title} [${m.type||"?"}] (${m.path})`).join(`
|
|
25
|
-
`),u=h.walked.length;return{content:[{type:"text",text:`${h.answer}
|
|
26
|
-
|
|
27
|
-
Citations (${u} article${u===1?"":"s"} walked):
|
|
28
|
-
${p}`}]}}case"agentx_wiki_patch":{let n=String(e.agent||"").trim(),s=String(e.title_or_path||"").trim(),i=String(e.instruction||"").trim();if(!n||!s||!i)return{content:[{type:"text",text:"Error: `agent`, `title_or_path`, and `instruction` are required."}]};let r=String(e.model||"sonnet"),o=e.dry_run===!0,{execFileSync:a}=await import("child_process"),l=["wiki","patch",n,s,i,"--patch-model",r,...o?["--no-commit"]:["--yes"]];try{let d=a(process.execPath,[process.argv[1],...l],{cwd:t,encoding:"utf-8",timeout:18e4,maxBuffer:8388608});return{content:[{type:"text",text:Z(d).trim()||"(no output)"}]}}catch(d){return{content:[{type:"text",text:`patch failed:
|
|
29
|
-
${[d.stdout,d.stderr,d.message].filter(Boolean).map(h=>Z(String(h))).join(`
|
|
30
|
-
`).trim().slice(0,2e3)}`}]}}}case"agentx_wiki_interview":{let n=String(e.agent||"").trim(),s=String(e.topic||"").trim(),i=String(e.type||"").trim().toLowerCase(),r=Array.isArray(e.answers)?e.answers.map(w=>String(w??"")):null;if(!n||!s||!i||!r||r.length===0)return{content:[{type:"text",text:"Error: `agent`, `topic`, `type`, and non-empty `answers[]` are required."}]};let o=String(e.model||"sonnet"),a=e.commit!==!1,l=r[r.length-1]?.toLowerCase(),d=["save","edit","scrap"].includes(l)?r:[...r,"save"],{execFileSync:g}=await import("child_process"),{writeFileSync:h,mkdtempSync:p}=await import("fs"),{tmpdir:u}=await import("os"),{join:f}=await import("path"),m=p(f(u(),"agentx-mcp-interview-")),y=f(m,"answers.txt");h(y,d.join(`
|
|
31
|
-
`));let b=["wiki","interview","--agent",n,"--topic",s,"--type",i,"--model",o,"--answers",y,...a?[]:["--no-commit"]];try{let w=g(process.execPath,[process.argv[1],...b],{cwd:t,encoding:"utf-8",timeout:24e4,maxBuffer:8388608});return{content:[{type:"text",text:Z(w).trim()||"(no output)"}]}}catch(w){return{content:[{type:"text",text:`interview failed:
|
|
32
|
-
${[w.stdout,w.stderr,w.message].filter(Boolean).map($=>Z(String($))).join(`
|
|
33
|
-
`).trim().slice(0,2e3)}`}]}}}case"agentx_graph_review":{let n=typeof e.max=="number"?Math.max(1,e.max):20,s=e.dry_run===!0,i=e.agent?String(e.agent):"",{execFileSync:r}=await import("child_process"),o=["graph","review","--max",String(n),...s?["--dry-run"]:[],...i?["--agent",i]:[]];try{let a=r(process.execPath,[process.argv[1],...o],{cwd:t,encoding:"utf-8",timeout:6e5,maxBuffer:8388608});return{content:[{type:"text",text:Z(a).trim()||"(no output)"}]}}catch(a){return{content:[{type:"text",text:`graph review failed:
|
|
34
|
-
${[a.stdout,a.stderr,a.message].filter(Boolean).map(d=>Z(String(d))).join(`
|
|
35
|
-
`).trim().slice(0,2e3)}`}]}}}case"agentx_debug":{let n=e.action||"status";if(n==="on"){let s=e.categories||"all";return await fetch(`${P}/debug/on?categories=${s}`,{method:"POST"}),{content:[{type:"text",text:`Debug enabled: ${s}`}]}}else{if(n==="off")return await fetch(`${P}/debug/off`,{method:"POST"}),{content:[{type:"text",text:"Debug disabled."}]};{let i=await(await fetch(`${P}/debug`)).json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}}}}default:throw new Error(`Unknown tool: ${c}`)}}function Wt(c,e){let t;try{t=JSON.parse(c)}catch(n){e("Failed to parse message:",n);return}if(t.id&&typeof t.id=="string"&&t.id.startsWith("elicit-")&&t.result){let n=se.get(t.id);n&&(se.delete(t.id),n(t.result));return}rs(t,e).catch(n=>e("Error:",n))}async function Zi(){let c=(...t)=>console.error("[agentx-mcp]",...t);c("Starting MCP server (stdio transport)...");let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{for(e+=t;e.length>0;)if(e.startsWith("Content-Length:")){let s=e.indexOf(`\r
|
|
36
|
-
\r
|
|
37
|
-
`);if(s===-1)break;let r=e.slice(0,s).match(/Content-Length:\s*(\d+)/);if(!r){e=e.slice(s+4);continue}let o=parseInt(r[1],10),a=s+4,l=a+o;if(e.length<l)break;let d=e.slice(a,l);e=e.slice(l),Wt(d,c)}else{let s=e.indexOf(`
|
|
38
|
-
`);if(s===-1)break;let i=e.slice(0,s).trim();e=e.slice(s+1),i&&Wt(i,c)}}),process.stdin.on("end",()=>{c("stdin closed, shutting down."),process.exit(0)})}function q(c){process.stdout.write(JSON.stringify(c)+`
|
|
39
|
-
`)}async function rs(c,e){let{method:t,id:n,params:s}=c;switch(e(`Received: ${t}`),t){case"initialize":{q({jsonrpc:"2.0",id:n,result:{protocolVersion:Zn,capabilities:es,serverInfo:Qn}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{q({jsonrpc:"2.0",id:n,result:{tools:ss}});break}case"tools/call":{let i=s?.name,r=s?.arguments||{};try{let o=await is(i,r);q({jsonrpc:"2.0",id:n,result:o})}catch(o){q({jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:`Error: ${o.message}`}],isError:!0}})}break}case"ping":{q({jsonrpc:"2.0",id:n,result:{}});break}default:n!==void 0&&q({jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${t}`}})}}var ee=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 i=s.body.getReader(),r=new TextDecoder,o="";for(;;){let{done:a,value:l}=await i.read();if(a)break;o+=r.decode(l,{stream:!0});let d=o.split(`
|
|
40
|
-
`);o=d.pop()||"";for(let g of d)if(g.startsWith("data: "))try{let h=JSON.parse(g.slice(6));yield{state:h.state,message:h.message?.parts?.[0]?.text,final:h.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}};import{Agent as os,fetch as as}from"undici";var cs=new os({headersTimeout:0,bodyTimeout:0}),Ze=3,me=class{peers=new Map;healthTimer;config;log;peerChangeCallback;onPeerChange(e){this.peerChangeCallback=e}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 ee(n.url,n.token),healthy:!1,agents:[],consecutiveFailures:0})}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 reloadPeers(e){this.config=e;let t=new Set(this.peers.keys()),n=new Map(e.mesh.peers.map(a=>[a.name,a])),s=[],i=[],r=[];for(let a of t)n.has(a)||(this.peers.delete(a),i.push(a));let o=[];for(let[a,l]of n){let d=this.peers.get(a);if(!d){let g={peer:l,client:new ee(l.url,l.token),healthy:!1,agents:[],consecutiveFailures:0};this.peers.set(a,g),s.push(a),o.push([a,g]);continue}d.peer.url!==l.url||d.peer.token!==l.token?(d.peer=l,d.client=new ee(l.url,l.token),d.healthy=!1,d.consecutiveFailures=0,r.push(a),o.push([a,d])):d.peer=l}return o.length&&await Promise.allSettled(o.map(([a,l])=>this.discoverPeer(a,l))),{added:s,removed:i,updated:r}}peerCount(){return this.peers.size}async refreshPeer(e){let t=this.peers.get(e);return t?(await this.discoverPeer(e,t),t.healthy):!1}async refreshAll(){let e=Array.from(this.peers.entries()).map(async([t,n])=>(await this.discoverPeer(t,n),{name:t,healthy:n.healthy}));return Promise.all(e)}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,i=setTimeout(()=>s.abort(),n),r=await t.client.getAgentCard();clearTimeout(i);let o=!t.healthy,a=new Set(t.agents.map(g=>g.id));t.healthy=!0,t.lastCheck=new Date,t.agentCard=r,t.agents=r.skills||[],t.consecutiveFailures=0,t.lastError=void 0;let l=new Set(t.agents.map(g=>g.id)),d=a.size!==l.size||[...l].some(g=>!a.has(g));o?(this.log(`Peer "${e}" recovered: ${r.name} (${t.agents.length} skills)`),this.peerChangeCallback?.({peer:e,healthy:!0,skills:[...l],delta:"recovered"})):(this.log(`Peer "${e}" healthy: ${r.name} (${t.agents.length} skills)`),d&&this.peerChangeCallback?.({peer:e,healthy:!0,skills:[...l],delta:"skills-changed"}))}catch(s){t.lastCheck=new Date,t.lastError=s.message,t.consecutiveFailures++,t.consecutiveFailures>=Ze&&t.healthy?(t.healthy=!1,this.log(`Peer "${e}" unreachable (${t.consecutiveFailures} consecutive failures): ${s.message}`),this.peerChangeCallback?.({peer:e,healthy:!1,skills:t.agents.map(i=>i.id),delta:"lost"})):t.consecutiveFailures<Ze&&this.log(`Peer "${e}" probe failed (${t.consecutiveFailures}/${Ze}): ${s.message}`)}}async sendTask(e,t,n,s={}){let i=this.peers.get(e);if(!i)throw new Error(`Unknown peer: ${e}`);if(!i.healthy)throw new Error(`Peer "${e}" is not healthy`);let r=n||i.agents[0]?.id;if(!r)throw new Error(`Peer "${e}" has no agents`);let o=`${i.peer.url}/task`,a={"Content-Type":"application/json"};i.peer.token&&(a.Authorization=`Bearer ${i.peer.token}`);let l=s.timeoutMs??30*60*1e3,d=new AbortController,g=setTimeout(()=>d.abort(),l),h;try{h=await as(o,{method:"POST",headers:a,body:JSON.stringify({agent:r,message:t,...s.senderAgentId?{senderAgentId:s.senderAgentId}:{},...s.context?{context:s.context}:{}}),signal:d.signal,dispatcher:cs})}catch(u){throw clearTimeout(g),d.signal.aborted?new Error(`Peer "${e}" /task timed out after ${Math.round(l/1e3)}s`):u}if(clearTimeout(g),!h.ok)throw new Error(`Peer "${e}" /task error: ${h.status}`);let p=await h.json();if(p.error)throw new Error(`Peer "${e}" agent error: ${p.error}`);return p.content||"No response"}async sendSignal(e,t){let n=this.peers.get(e)||this.findPeerByNormalizedName(e);if(!n)throw new Error(`Unknown peer: ${e}`);let s=`${n.peer.url}/webrtc/signal`,i={"Content-Type":"application/json"};n.peer.token&&(i.Authorization=`Bearer ${n.peer.token}`);try{return(await fetch(s,{method:"POST",headers:i,body:JSON.stringify(t)})).ok}catch(r){return this.log(`sendSignal to "${e}" failed: ${r.message}`),!1}}findPeerByNormalizedName(e){let t=e.toLowerCase().replace(/[^a-z0-9]/g,"");for(let[n,s]of this.peers)if(n.toLowerCase().replace(/[^a-z0-9]/g,"")===t)return s}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,channels:Array.isArray(t.agentCard?.channels)?t.agentCard.channels.map(n=>String(n)):[],lastCheck:t.lastCheck}))}};import{readFileSync as ds,writeFileSync as ls,existsSync as gs,mkdirSync as hs}from"fs";import{resolve as Jt}from"path";function ie(c,e,t="\u2026"){if(!c)return"";if(c.length<=e)return c;let n=e-t.length;if(n<=0)return c.slice(0,e);let s=c.slice(0,n),i=s.lastIndexOf(`
|
|
41
|
-
`);if(i>n*.6)return s.slice(0,i)+`
|
|
42
|
-
`+t;let r=Math.max(s.lastIndexOf(" "),s.lastIndexOf(" "));return r>n*.6?s.slice(0,r)+t:s+t}function et(c,e,t){if(!c)return"";let s=c.split(`
|
|
43
|
-
`).slice(0,e).join(`
|
|
44
|
-
`);return ie(s,t)}var us=30,zt=6e3,ps=1500,ms=6e4;function fs(c){let e=new Date(c),t=e.getUTCHours().toString().padStart(2,"0"),n=Math.floor(e.getUTCMinutes()/15)*15;return`${t}:${n.toString().padStart(2,"0")}`}var fe=class{dir;cache=new Map;constructor(e=Jt(process.cwd(),".agentx/groups")){this.dir=e,hs(this.dir,{recursive:!0})}add(e,t,n){let s=this.load(e),i=Date.now(),r=ie(n,ps),o=s[s.length-1];if(!(o&&o.sender===t&&o.text===r&&i-o.timestamp<ms)){for(s.push({sender:t,text:r,timestamp:i});s.length>us;)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,i=null,r=[],o="",a=()=>{if(!i)return!0;let l=i.repeat>1?`${i.line} [\xD7${i.repeat}]`:i.line;if(s+l.length>zt)return!1;if(r.push(l),s+=l.length,i.bucket!==o){let d=`\u2014 ${i.bucket} \u2014`;if(s+d.length>zt)return i=null,!1;r.push(d),s+=d.length,o=i.bucket}return i=null,!0};for(let l=t.length-2;l>=0;l--){let d=t[l],g=`${d.sender}: ${d.text}`,h=fs(d.timestamp);if(i&&i.line===g&&i.bucket===h){i.repeat++;continue}if(!a())break;i={line:g,repeat:1,bucket:h}}a();for(let l=r.length-1;l>=0;l--)n.splice(1,0,r[l]);return n.length<=1?"":(n.push("[End of conversation \u2014 respond to the latest message]"),n.join(`
|
|
45
|
-
`))}getEntries(e){return[...this.load(e)]}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Jt(this.dir,`${t}.json`)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.filePath(e);if(!gs(t))return this.cache.set(e,[]),[];try{let n=JSON.parse(ds(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{ls(this.filePath(e),JSON.stringify(t))}catch{}}};var ys={minChars:80,maxChars:4e3,idleFlushMs:2e3,minIntervalMs:1500,humanPacing:!1},bs={telegram:{minChars:60,maxChars:4096,minIntervalMs:1500},whatsapp:{minChars:40,maxChars:3e3,minIntervalMs:2e3,humanPacing:!0},discord:{minChars:80,maxChars:2e3,minIntervalMs:1e3},gitlab:{minChars:200,maxChars:6e4,minIntervalMs:3e3}},ye=class{config;buffer="";emitter;lastEmitTime=0;idleTimer;insideCodeFence=!1;fencePattern=/^```/;lastEmission=Promise.resolve();constructor(e,t,n){let s=n?bs[n]:{};this.config={...ys,...s,...t},this.emitter=e}push(e){this.buffer+=e,this.idleTimer&&clearTimeout(this.idleTimer),this.updateCodeFenceState(e),this.shouldEmit()?this.emit():this.idleTimer=setTimeout(()=>{this.buffer.length>0&&this.emit()},this.config.idleFlushMs)}async flush(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0),this.buffer.length>0&&(this.emitImmediate(this.buffer),this.buffer=""),await this.lastEmission}get pendingLength(){return this.buffer.length}shouldEmit(){return this.insideCodeFence||this.buffer.length<this.config.minChars||Date.now()-this.lastEmitTime<this.config.minIntervalMs?!1:this.findBreakPoint()>0}emit(){let e=this.findBreakPoint();if(e<=0&&this.buffer.length<this.config.maxChars)return;let t=e>0?e:Math.min(this.buffer.length,this.config.maxChars),n=this.buffer.slice(0,t);if(this.buffer=this.buffer.slice(t),this.config.humanPacing){let s=800+Math.random()*1700;setTimeout(()=>this.emitImmediate(n),s)}else this.emitImmediate(n)}emitImmediate(e){this.lastEmitTime=Date.now(),this.lastEmission=this.lastEmission.then(()=>Promise.resolve().then(()=>this.emitter(e)).catch(()=>{}))}findBreakPoint(){let e=this.buffer,t=Math.min(e.length,this.config.maxChars),n=e.lastIndexOf(`
|
|
46
|
-
|
|
47
|
-
`,t);if(n>=this.config.minChars)return n+2;let s=e.lastIndexOf(`
|
|
48
|
-
`,t);if(s>=this.config.minChars)return s+1;for(let i=t-1;i>=this.config.minChars;i--)if((e[i]==="."||e[i]==="!"||e[i]==="?")&&(i+1>=e.length||e[i+1]===" "||e[i+1]===`
|
|
49
|
-
`))return i+1;if(e.length>=this.config.maxChars){let i=e.lastIndexOf(" ",t);return i>=this.config.minChars?i+1:t}return-1}updateCodeFenceState(e){let t=e.split(`
|
|
50
|
-
`);for(let n of t)this.fencePattern.test(n.trim())&&(this.insideCodeFence=!this.insideCodeFence)}};import{readFileSync as dn,writeFileSync as ln,existsSync as nt,mkdirSync as gn,appendFileSync as cn}from"fs";import{resolve as st,dirname as hn}from"path";function Xt(c){let e=c.group?{type:"group",chatId:c.group.id,name:c.group.name}:c.channel==="gitlab"||c.channel==="github"?c.channel==="gitlab"?{type:"project",project:c.sender.id}:{type:"repo",repo:c.sender.id}:{type:"dm",chatId:c.sender.id};return{id:c.id,channel:c.channel,accountId:c.accountId,sender:{id:c.sender.id,name:c.sender.name,username:c.sender.username,isBot:c.sender.isBot===!0},conversation:e,content:{text:c.text,replyTo:c.replyToText},raw:c}}function qt(c,e,t){let n={...t,atMentionsOnly:!1,trace:[]};for(let s of e){let i=s.run(c,n);if(n.trace.push({stage:s.name,decision:i}),i.kind==="match"){let r=!!(n.hasAgent||n.hasMeshAgent),o=!!n.hasAgent?.(i.agentId),a=!!n.hasMeshAgent?.(i.agentId);if(r&&!o&&!a){let l={kind:"drop",reason:`unknown_agent:${i.agentId}`};return n.trace[n.trace.length-1]={stage:s.name,decision:l},{decidingStage:s.name,kind:"drop",reason:l.reason,trace:n.trace}}return{agentId:i.agentId,decidingStage:s.name,kind:"match",reason:`agent=${i.agentId}`,trace:n.trace}}if(i.kind==="drop")return{decidingStage:s.name,kind:"drop",reason:i.reason,trace:n.trace}}return{decidingStage:"fallthrough",kind:"drop",reason:"no stage matched",trace:n.trace}}var Kt=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function re(c,e){return Kt.test(c)?c:`${c}
|
|
51
|
-
|
|
52
|
-
<!-- agentx:${e} -->`}function W(c){if(!c)return null;let e=c.match(Kt);return e?e[1]:null}function tt(c){return c.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"")}var Yt={name:"self-reply-guard",run(c,e){if(c.sender.isAgent)return{kind:"drop",reason:`self-reply (agent=${c.sender.agentId??"?"})`};let t=W(c.content.text);return t?{kind:"drop",reason:`agentx-marker (agent=${t})`}:{kind:"pass"}}};var Vt={name:"handover",run(c,e){let t=c.conversation.type==="group"||c.conversation.type==="dm"?c.conversation.chatId:c.sender.id,n=e.handoverStore.get(c.channel,t,c.accountId);return n?{kind:"match",agentId:n.toAgent}:{kind:"pass"}}};var Qt={name:"adapter-resolved",run(c,e){if(c.channel==="gitlab"){let t=c.raw.resolvedAgent;return t?{kind:"match",agentId:t}:{kind:"drop",reason:"gitlab username has no agent mapping"}}return c.raw.resolvedAgent?{kind:"match",agentId:c.raw.resolvedAgent}:{kind:"pass"}}};var Zt={name:"dm-binding",run(c,e){if(c.conversation.type!=="dm")return{kind:"pass"};if(c.channel==="telegram"){let t=e.config.channels.telegram.accounts[c.accountId];return t?.agentBinding?{kind:"match",agentId:t.agentBinding}:{kind:"drop",reason:`telegram dm: no agentBinding for account "${c.accountId}"`}}if(c.channel==="whatsapp"){let t=e.config.channels.whatsapp.defaultAgent;return t?{kind:"match",agentId:t}:{kind:"drop",reason:"whatsapp dm: no defaultAgent configured"}}return{kind:"pass"}}};var en={name:"bot-policy",run(c,e){return c.sender.isBot&&(e.atMentionsOnly=!0),{kind:"pass"}}};var tn={name:"mention",run(c,e){let t=c.channel==="telegram"&&c.conversation.type==="group"&&e.config.channels.telegram.policy.group==="mention-required",n=e.atMentionsOnly||t,s=e.registry.findByMention(c.content.text,{atMentionsOnly:n});return s?{kind:"match",agentId:s}:t?{kind:"drop",reason:"telegram group mention-required: no @mention found"}:e.atMentionsOnly?{kind:"drop",reason:"bot-origin: no @mention of a local agent"}:{kind:"pass"}}};var nn={name:"fallback-binding",run(c,e){if(c.channel==="telegram"){let t=e.config.channels.telegram.accounts[c.accountId];return t?.agentBinding?{kind:"match",agentId:t.agentBinding}:{kind:"drop",reason:`no telegram agentBinding for account "${c.accountId}"`}}if(c.channel==="whatsapp"){let t=e.config.channels.whatsapp.defaultAgent;return t?{kind:"match",agentId:t}:{kind:"drop",reason:"no whatsapp defaultAgent"}}return{kind:"pass"}}};var sn=[Yt,Vt,Qt,Zt,en,tn,nn];function rn(c,e,t,n){let s=[];for(let[o,a]of Object.entries(c))a.agentBinding===e&&s.push(o);if(s.length===0)return;if(s.length===1||!t)return s[0];let i=n?.(t)??[];return s.filter(o=>i.includes(o))[0]||s[0]}var ws=new Set(["telegram","slack","whatsapp","discord"]);function on(c){return ws.has(c)?c:null}function ks(c,e,t,n=Date.now){let s=c.accountId||"default",i=c.group?.id||c.sender.id;return{ts:n(),source:e,sourceEventId:`${s}/${c.id}`,project:null,subject:`chat:${i}`,intent:c.replyTo?"message.reply":"message.received",rawJson:t}}function vs(c){return{decidedBy:"channel-router",decide:()=>({agentId:c.agentId,outcome:c.outcome==="deduped"?"halted":c.outcome,reason:c.outcome==="deduped"?`legacy-dedup: ${c.reason??""}`.trim():c.reason??null})}}function an(c,e,t,n,s,i=Date.now){let r=ks(e,t,n,i),o=vs(s),a=F(c,r,o,i);return H(c,t,a,s,i),a}var it=class{filePath;constructor(e){this.filePath=st(e,".agentx/router/inflight.jsonl"),gn(hn(this.filePath),{recursive:!0})}start(e){try{let t=JSON.stringify({type:"start",ts:Date.now(),...e})+`
|
|
53
|
-
`;cn(this.filePath,t)}catch{}}done(e){try{cn(this.filePath,JSON.stringify({type:"done",id:e,ts:Date.now()})+`
|
|
54
|
-
`)}catch{}}loadUnfinished(){if(!nt(this.filePath))return[];try{let e=dn(this.filePath,"utf-8"),t=new Map;for(let n of e.split(`
|
|
55
|
-
`))if(n.trim())try{let s=JSON.parse(n);s.type==="start"?t.set(s.id,s):s.type==="done"&&t.delete(s.id)}catch{}return[...t.values()]}catch{return[]}}compact(){try{let e=this.loadUnfinished(),t=e.map(n=>JSON.stringify(n)).join(`
|
|
56
|
-
`)+(e.length?`
|
|
57
|
-
`:"");ln(this.filePath,t)}catch{}}};var $s=4e3,rt=class{registry;config;channels=new Map;hooks;mesh;serviceMatcher;business;groupLog;handoverStore;log;getHandoverStore(){return this.handoverStore}recentMessageIds=new Map;MESSAGE_ID_TTL_MS=5*60*1e3;MESSAGE_ID_MAX_ENTRIES=2e3;DEDUP_STORE_PATH=".agentx/router/dedup.json";dedupDirtyCount=0;dedupSaveTimer;inflight;activeMeshForwards=0;getActiveMeshForwardCount(){return this.activeMeshForwards}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 fe,this.handoverStore=new Ct({log:(...i)=>s("[handover]",...i)}),this.inflight=new it(process.cwd()),this.loadDedupFromDisk()}loadDedupFromDisk(){try{let e=st(process.cwd(),this.DEDUP_STORE_PATH);if(!nt(e))return;let t=JSON.parse(dn(e,"utf-8")),n=Date.now(),s=0;for(let[i,r]of Object.entries(t))typeof r=="number"&&n-r<this.MESSAGE_ID_TTL_MS&&(this.recentMessageIds.set(i,r),s++);s>0&&this.log(`Router dedup: restored ${s} recent message ids from disk`)}catch{}}scheduleDedupSave(){if(this.dedupDirtyCount++,this.dedupDirtyCount>=20){this.flushDedupToDisk();return}this.dedupSaveTimer||(this.dedupSaveTimer=setTimeout(()=>this.flushDedupToDisk(),5e3))}flushDedupToDisk(){this.dedupSaveTimer&&(clearTimeout(this.dedupSaveTimer),this.dedupSaveTimer=void 0),this.dedupDirtyCount=0;try{let e=Date.now(),t={};for(let[i,r]of this.recentMessageIds)e-r<this.MESSAGE_ID_TTL_MS&&(t[i]=r);let n=st(process.cwd(),this.DEDUP_STORE_PATH),s=hn(n);nt(s)||gn(s,{recursive:!0}),ln(n,JSON.stringify(t))}catch{}}flushPersistence(){this.flushDedupToDisk(),this.inflight.compact()}setMesh(e){this.mesh=e}setServiceMatcher(e){this.serviceMatcher=e}getServiceMatcher(){return this.serviceMatcher}setBusiness(e){this.business=e}updateConfig(e){this.config=e}getChannel(e){return this.channels.get(e)}addChannel(e){this.channels.set(e.name,e),e.onMessage(t=>this.handleMessage(e,t))}async sendOutbound(e){let t=this.channels.get(e.channel);if(!t)throw new Error(`Unknown channel: "${e.channel}". Available: ${[...this.channels.keys()].join(", ")}`);let n=e.accountId;t.name==="telegram"&&!n&&e.agentId&&(n=this.getAccountForAgent(e.agentId)),this.log(`Outbound [${e.channel}] -> ${e.chatId}: ${e.text.slice(0,80)}`);let s;if(t.name==="telegram"&&n?s=await this.adapterSend(t,{...e,accountId:n}):s=await t.send(e),e.agentId)try{this.registry.getSessionStore().addAgentMessage(e.agentId,e.channel,e.chatId,e.text)}catch(i){this.log(`Failed to record outbound in recipient session: ${i.message}`)}return s}getChannelNames(){return[...this.channels.keys()]}async startAll(){for(let[e,t]of this.channels)this.log(`Starting channel: ${e}`),await t.start();this.replayInflight().catch(e=>this.log(`Inflight replay error: ${e.message}`))}async replayInflight(){let e=this.inflight.loadUnfinished();if(e.length!==0){this.log(`Inflight replay: ${e.length} task(s) to resume from previous run`);for(let t of e){let n=this.channels.get(t.channel);if(!n){this.log(`Inflight replay: adapter "${t.channel}" not available, skipping task ${t.id}`),this.inflight.done(t.id);continue}let s={id:t.id,channel:t.channel,accountId:t.accountId,sender:t.sender,group:t.group,text:t.text,replyTo:t.replyTo,replyToText:t.replyToText,timestamp:new Date(t.timestamp),resolvedAgent:t.resolvedAgent,preferNode:t.preferNode};this.log(`Inflight replay: ${t.channel}/${t.id} (agent=${t.resolvedAgent||"resolve"})`),this.handleMessage(n,s,{replay:!0}).catch(i=>this.log(`Inflight replay failed for ${t.id}: ${i.message}`)).finally(()=>this.inflight.done(t.id))}this.inflight.compact()}}async stopAll(){for(let[e,t]of this.channels)this.log(`Stopping channel: ${e}`),await t.stop()}isDuplicateMessage(e){if(!e.id)return!1;let t=`${e.channel}:${e.accountId||"default"}:${e.id}`,n=Date.now();if(this.recentMessageIds.size>=this.MESSAGE_ID_MAX_ENTRIES)for(let[i,r]of this.recentMessageIds)n-r>this.MESSAGE_ID_TTL_MS&&this.recentMessageIds.delete(i);let s=this.recentMessageIds.get(t);return s&&n-s<this.MESSAGE_ID_TTL_MS?!0:(this.recentMessageIds.set(t,n),this.scheduleDedupSave(),!1)}recordRouterDecisionInLedger(e,t){let n=on(e.channel);if(n&&E(n)!=="off")try{let s=an(_(),e,n,JSON.stringify(e),t);return s.outcome==="dispatched"?{eventId:s.eventId,decidedBy:s.decidedBy}:void 0}catch(s){this.log(`[ledger] router ${e.channel}/${e.id} record failed: ${s?.message??s}`);return}}async handleMessage(e,t,n={}){if(!n.replay&&this.isDuplicateMessage(t)){this.log(`Duplicate ${t.channel} message dropped: ${t.accountId||"default"}/${t.id}`),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"deduped",reason:"isDuplicateMessage"});return}if(this.hooks?.has("pre:channel-message")){let a=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,msg:t});if(a.blocked){this.log(`Message blocked by hook: ${a.message}`),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"halted",reason:`pre-hook blocked: ${a.message??""}`.trim()});return}a.modified?.text&&(t={...t,text:a.modified.text})}if(t.group){let a=t.group.id;this.groupLog.add(a,t.sender.name,t.text)}if(this.serviceMatcher){let a=t.group?.id||t.sender.id,l=this.serviceMatcher.match(t.text,t.sender.id,t.channel);if(l){this.log(`Service matched: "${l.service.name}" for ${t.sender.name} (trigger: ${l.trigger})`),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"halted",reason:`service-match: ${l.service.name} (trigger: ${l.trigger})`});let d=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",d);let g=this.startTypingLoop(e,a,d);await this.serviceMatcher.execute(l.service,this.registry,{channel:t.channel,sender:t.sender.name,chatId:a},async h=>{clearInterval(g),await this.adapterSend(e,{channel:t.channel,chatId:a,text:h,replyTo:t.id,accountId:d})});return}}let s=this.runRoutingPipeline(t),i=s.agentId;if(!i){this.traceRoute(t,"drop",s.reason,s.decidingStage),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"halted",reason:`routing:${s.reason}`});return}if(t.group&&t.channel==="telegram"){let a=this.getAccountForAgent(i,t.group.id);if(a&&a!==t.accountId){this.traceRoute(t,"drop",`multi-account-dedup (bound=${a} got=${t.accountId})`,"multi-account-dedup"),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"halted",reason:`multi-account-dedup (bound=${a} got=${t.accountId})`});return}}this.traceRoute(t,"match",`${s.decidingStage} agent=${i}`,s.decidingStage,i);let r=this.recordRouterDecisionInLedger(t,{agentId:i,outcome:"dispatched",reason:s.decidingStage});r&&(t={...t,intentRef:r});let o=t.group?.id||t.sender.id;this.inflight.start({id:t.id,channel:t.channel,accountId:t.accountId,text:t.text,sender:t.sender,group:t.group,replyTo:t.replyTo,replyToText:t.replyToText,timestamp:(t.timestamp instanceof Date?t.timestamp:new Date).toISOString(),resolvedAgent:i,preferNode:t.preferNode});try{return await this.processResolvedMessage(e,t,i,o)}finally{this.inflight.done(t.id)}}async processResolvedMessage(e,t,n,s){if(t.preferNode){this.log(`preferNode="${t.preferNode}" \u2014 forcing mesh routing for agent "${n}"`),await this.handleViaMeshByPeer(e,t,n,t.preferNode)||this.log(`Mesh peer "${t.preferNode}" not found or unhealthy for agent "${n}"`);return}let i=this.registry.getAgent(n);if(!i){await this.handleViaMeshByAgentId(e,t,n)||this.log(`Agent "${n}" not found locally or on any mesh peer`);return}let r=i.name||n,o=this.getAccountForAgent(n,t.group?.id)||t.accountId;this.log(`Routing [${t.channel}/${t.sender.name}] -> "${r}": ${t.text.slice(0,80)}`),this.adapterReact(e,s,t.id,"\u{1F440}",o);let a=this.startTypingLoop(e,s,o),l=typeof e.editMessage=="function",d,g="",h=l?new ye(async $=>{if(g+=$,d)try{await this.adapterEdit(e,s,d,g,void 0,o)}catch{}else{let I=g.length>20?g:`_${r} is writing..._
|
|
58
|
-
|
|
59
|
-
${g}`;try{d=await this.adapterSend(e,{channel:t.channel,chatId:s,text:I,replyTo:t.id,accountId:o})}catch{}}},void 0,t.channel):void 0,p=h?($,I)=>{h.push($)}:void 0;if(t.channelMeta?.agents){for(let $ of t.channelMeta.agents)if(!$.handle){let I=this.registry.getAgent($.id);I&&($.handle=I.mentions.find(k=>k.startsWith("@")),$.name=I.name)}}let u=t.group?this.groupLog.buildContext(s):"",f=u?`${u}
|
|
60
|
-
|
|
61
|
-
${t.sender.name}: ${t.text}`:t.text,m=await this.registry.execute({message:f,agentId:n,intentRef:t.intentRef,context:{channel:t.channel,sender:t.sender.name,senderId:t.sender.id,senderUsername:t.sender.username,group:t.group?.name,chatId:s,mediaPath:t.media?.path,mediaType:t.media?.type,replyToText:t.replyToText,channelMeta:t.channelMeta}},p);if(clearInterval(a),await h?.flush(),m.error){if(m.error.startsWith("__queued__")){clearInterval(a),this.log(`Message queued for ${r}`);return}this.log(`Agent error: ${m.error}`);let $=`Error: ${m.error}`;d?await this.adapterEdit(e,s,d,$,"plain",o):await this.adapterSend(e,{channel:t.channel,chatId:s,text:$,replyTo:t.id,parseMode:"plain",accountId:o});return}let y=m.content;if(this.hooks?.has("post:channel-message")){let $=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:y,agentId:n});if($.blocked){this.log(`Response blocked by hook: ${$.message}`);return}$.modified?.response&&(y=$.modified.response)}t.channel==="gitlab"&&y&&(this.channels.get("gitlab")?.getAgentToken?.(n)||(y=`> **${r}** (${n})
|
|
62
|
-
|
|
63
|
-
${y}`)),t.channel==="whatsapp"&&y&&(y=`*${r}*
|
|
64
|
-
|
|
65
|
-
${y}`);let b;y&&(d?(await this.adapterEdit(e,s,d,y,void 0,o),b=d):b=await this.adapterSend(e,{channel:t.channel,chatId:s,text:y,replyTo:t.id,accountId:o,agentId:n})),t.group&&y&&this.groupLog.add(s,r,y);let w=this.config.notifications;if(w?.destination&&m.duration){let $=(w.longTaskThreshold||30)*1e3;if(m.duration>=$&&!m.error&&w.on?.taskComplete||m.error&&w.on?.taskError){let k=Math.round(m.duration/1e3),S=m.error?"failed":"completed",T=et(t.text,6,300),x=m.error?ie(m.error,300):et(m.content,6,400),C=`${S==="failed"?"\u{1F534}":"\u2705"} **${r}** ${S} (${k}s)
|
|
66
|
-
${t.channel}/${t.sender.name}: ${T}
|
|
67
|
-
${x}`;this.sendOutbound({channel:w.destination.channel,chatId:w.destination.chatId,text:C,agentId:n,accountId:w.destination.accountId}).catch(A=>{this.log(`Task notification failed: ${A.message}`)})}}if(this.business&&m.duration&&this.business.recordTaskCompletion(n,Math.round(m.duration/1e3),!m.error,t.channel),t.channel==="gitlab"&&m.duration&&!m.error){let $=this.channels.get("gitlab");$&&$.logTimeSpent(s,m.duration,n).catch(I=>{this.log(`GitLab time tracking failed: ${I.message}`)})}y&&b&&["telegram","whatsapp","discord","slack"].includes(t.channel)&&this.handleBotToBotChain(e,t,n,y,b,0).catch($=>{this.log(`Bot-to-bot error: ${$.message}`)})}async handleBotToBotChain(e,t,n,s,i,r,o=new Set){if(r>=rt.MAX_BOT_CHAIN_DEPTH){this.log(`Bot-to-bot: max depth (${r}) reached, stopping`);return}o.add(n);for(let[a,l]of Object.entries(this.config.agents)){if(a===n)continue;if(o.has(a)){this.log(`Bot-to-bot: "${a}" already participated, stopping chain`);continue}if(!l.mentions.filter(f=>f.startsWith("@")).some(f=>s.toLowerCase().includes(f.toLowerCase())))continue;this.log(`Bot-to-bot [${r+1}]: "${n}" -> "${a}"`);let h=t.group?.id||t.sender.id,p=this.getAccountForAgent(a),u=this.getAccountForAgent(n);try{this.adapterReact(e,h,i,"\u{1F440}",p);let f=this.startTypingLoop(e,h,p),m=r===0?`[Original from ${t.sender.name}]: ${t.text}
|
|
68
|
-
|
|
69
|
-
[${n} said]: ${s}`:s,y=await this.registry.execute({message:m,agentId:a,context:{channel:t.channel,sender:`agent:${n}`,group:t.group?.name,chatId:t.group?.id||t.sender.id,channelMeta:t.channelMeta}});if(clearInterval(f),y.content&&!y.error){let b=y.content;t.channel==="whatsapp"&&(b=`*${l.name}*
|
|
70
|
-
|
|
71
|
-
${b}`);let w=await this.adapterSend(e,{channel:t.channel,chatId:h,text:b,accountId:p});w&&y.content&&await this.handleBotToBotChain(e,t,a,y.content,w,r+1,o)}else y.error&&this.log(`Bot-to-bot "${a}" error: ${y.error}`)}catch(f){this.log(`Bot-to-bot "${a}" failed: ${f.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,i,r){return e.name==="telegram"&&r?e.editMessage(t,n,s,i,r):e.editMessage?.(t,n,s,i)??!1}adapterReact(e,t,n,s,i){e.name==="telegram"&&i?e.react(t,n,s,i):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,$s)}traceRoute(e,t,n,s="unknown",i){let r=e.group?.id||e.sender?.id||"?";this.log(`[route] ${e.channel}:${r} msgId=${e.id} acct=${e.accountId??"\u2014"} kind=${t} ${n}`);let o=new Date().toISOString();t==="match"&&i?X().emit("message:matched",{channel:e.channel,chatId:String(r),msgId:e.id,accountId:e.accountId,agentId:i,decidingStage:s,at:o}):t==="drop"&&X().emit("message:dropped",{channel:e.channel,chatId:String(r),msgId:e.id,accountId:e.accountId,decidingStage:s,reason:n,at:o})}runRoutingPipeline(e){let t=Xt(e);return qt(t,sn,{config:this.config,registry:this.registry,handoverStore:this.handoverStore,hasAgent:n=>!!this.registry.getAgent(n),hasMeshAgent:n=>this.mesh?this.mesh.directory().some(s=>s.healthy&&s.skills.some(i=>i.id===n)):!1})}buildMeshContext(e,t){return{channel:e.channel,sender:e.sender.name,senderId:e.sender.id,senderUsername:e.sender.username,group:e.group?.name,chatId:t,mediaPath:e.media?.path,mediaType:e.media?.type,replyToText:e.replyToText,channelMeta:e.channelMeta}}async handleViaMesh(e,t){if(!this.mesh)return!1;let n=t.text.toLowerCase(),s=this.mesh.directory();for(let i of s)if(i.healthy){for(let r of i.skills)if(n.includes(r.id.toLowerCase())||n.includes(r.name.toLowerCase())){this.log(`Mesh routing [${t.channel}/${t.sender.name}] -> peer "${i.peer}" agent "${r.id}"`);let o=t.group?.id||t.sender.id,a=t.accountId;this.adapterReact(e,o,t.id,"\u{1F440}",a);let l=this.startTypingLoop(e,o,a);try{let d=await this.mesh.sendTask(i.peer,t.text,r.id,{context:this.buildMeshContext(t,o)});if(clearInterval(l),d){let g=`**${r.name}** _(${i.peer})_:
|
|
72
|
-
|
|
73
|
-
`;await this.adapterSend(e,{channel:t.channel,chatId:o,text:g+d,replyTo:t.id,accountId:a})}return!0}catch(d){return clearInterval(l),this.log(`Mesh routing error: ${d.message}`),await this.adapterSend(e,{channel:t.channel,chatId:o,text:`Error from ${i.peer}/${r.name}: ${d.message}`,replyTo:t.id,parseMode:"plain",accountId:a}),!0}}}return!1}async handleViaMeshByAgentId(e,t,n){if(!this.mesh)return!1;let s=this.mesh.directory();for(let i of s){if(!i.healthy)continue;let r=i.skills.find(d=>d.id===n);if(!r)continue;this.log(`Mesh routing by agentId [${t.channel}/${t.sender.name}] -> peer "${i.peer}" agent "${n}"`);let o=t.group?.id||t.sender.id,a=t.accountId;this.adapterReact(e,o,t.id,"\u{1F440}",a);let l=this.startTypingLoop(e,o,a);try{let d=await this.mesh.sendTask(i.peer,t.text,n,{context:this.buildMeshContext(t,o)});return clearInterval(l),d&&await this.adapterSend(e,{channel:t.channel,chatId:o,text:d,replyTo:t.id,accountId:a}),!0}catch(d){return clearInterval(l),this.log(`Mesh routing error for ${n}: ${d.message}`),await this.adapterSend(e,{channel:t.channel,chatId:o,text:`Error from ${i.peer}/${r.name}: ${d.message}`,replyTo:t.id,parseMode:"plain",accountId:a}),!0}}return!1}async handleViaMeshByPeer(e,t,n,s){if(!this.mesh)return!1;let r=this.mesh.directory().find(h=>h.peer===s);if(!r||!r.healthy)return!1;let o=r.skills.find(h=>h.id===n)??{name:n,id:n};this.log(`Mesh routing by preferNode [${t.channel}/${t.sender.name}] -> peer "${s}" agent "${n}"`);let a=t.group?.id||t.sender.id,l=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",l);let d=this.startTypingLoop(e,a,l),g=Date.now();this.activeMeshForwards++;try{let h=await this.mesh.sendTask(s,t.text,n,{context:this.buildMeshContext(t,a)}),p=Date.now()-g;if(clearInterval(d),h&&await this.adapterSend(e,{channel:t.channel,chatId:a,text:h,replyTo:t.id,accountId:l,agentId:n}),t.channel==="gitlab"&&p){let u=this.channels.get("gitlab");u&&u.logTimeSpent(a,p,n).catch(f=>{this.log(`GitLab time tracking (mesh) failed: ${f.message}`)})}return!0}catch(h){return clearInterval(d),this.log(`Mesh routing error for ${s}/${n}: ${h.message}`),await this.adapterSend(e,{channel:t.channel,chatId:a,text:`Error from ${s}/${o.name}: ${h.message}`,replyTo:t.id,parseMode:"plain",accountId:l}),!0}finally{this.activeMeshForwards--}}getAccountForAgent(e,t){let n=this.channels.get("telegram");return rn(this.config.channels.telegram.accounts,e,t,n?.getGroupBotAccounts?.bind(n))}resolveAgent(e){return this.runRoutingPipeline(e).agentId}},oe=rt;ue(oe,"MAX_BOT_CHAIN_DEPTH",3);function be(c){return c.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ae(c){let t=c.replace(/\\([_*\[\]()~`>#+=|{}.!\\-])/g,"$1").split(`
|
|
74
|
-
`),n=[],s=!1,i="",r=[],o=!1,a=[],l=!1;for(let g=0;g<t.length;g++){let h=t[g];if(h.trimStart().startsWith("```"))if(s){s=!1;let m=be(r.join(`
|
|
75
|
-
`)),y=i?`// ${i}
|
|
76
|
-
`:"";n.push(`<pre><code>${y}${m}</code></pre>`),i="";continue}else{s=!0,i=h.trimStart().slice(3).trim(),r=[];continue}if(s){r.push(h);continue}if(o&&!h.trimStart().startsWith(">")&&(n.push("</blockquote>"),o=!1),l&&!h.trim().startsWith("|")&&(l=!1,a=[]),h.trimStart().startsWith("> ")){let m=h.replace(/^>\s*/,"");o||(n.push("<blockquote>"),o=!0),n.push(L(m));continue}let p=h.match(/^(#{1,6})\s+(.+)$/);if(p){n.push(""),n.push(`<b>${L(p[2])}</b>`);continue}if(/^[-*_]{3,}\s*$/.test(h.trim())){n.push("\u2014\u2014\u2014");continue}if(h.trim().startsWith("|")&&h.trim().endsWith("|")){let m=h.split("|").slice(1,-1).map(y=>y.trim());if(/^\|[\s\-:|]+\|$/.test(h.trim())){l=!0;continue}if(!l){a=m,l=!0;continue}if(a.length>0&&m.length>0)if(m.length>=2){let y=[];for(let b=0;b<m.length;b++)if(b===0)y.push(`<b>${L(m[b])}</b>`);else{let w=a[b]?`${L(a[b])}: `:"";y.push(`${w}${L(m[b])}`)}n.push(`\u2022 ${y.join(" \u2014 ")}`)}else n.push(`\u2022 ${L(m[0])}`);continue}let u=h.match(/^(\s*)[-*+]\s+(.+)$/);if(u){let m=u[1].length>0?" ":"";n.push(`${m}\u2022 ${L(u[2])}`);continue}let f=h.match(/^(\s*)\d+[.)]\s+(.+)$/);if(f){let m=f[1].length>0?" ":"",y=h.match(/^(\s*)(\d+)/)?.[2]||"1";n.push(`${m}${y}. ${L(f[2])}`);continue}if(!h.trim()){n.push("");continue}n.push(L(h))}s&&n.push(`<pre><code>${be(r.join(`
|
|
77
|
-
`))}</code></pre>`),o&&n.push("</blockquote>");let d=n.join(`
|
|
78
|
-
`).trim();return d=Is(d),d}function L(c){let e=be(c);return e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,n,s)=>`<a href="${be(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 Ss=/(?<=\w)\.(ts|js|py|rs|go|rb|cs|sh|md|yml|yaml|toml|json|env|css|html|xml|sql|tf|hcl)(?=[\s,;:)\]}<]|$)/gi;function Is(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(Ss,"<code>.$1</code>")).join("")}import{readFileSync as ct,writeFileSync as mn,mkdirSync as fn,existsSync as dt}from"fs";import{resolve as yn,dirname as bn}from"path";import{existsSync as un,mkdirSync as Ts,readFileSync as xs,renameSync as As,writeFileSync as Cs}from"fs";import{dirname as Ms,resolve as Rs}from"path";var at=class{filePath;data;constructor(e,t=".agentx/cursors.json"){this.filePath=Rs(e,t),this.data={};try{if(un(this.filePath)){let n=JSON.parse(xs(this.filePath,"utf-8"));n&&typeof n=="object"&&(this.data=n)}}catch{}}key(e,t){return`${e}:${t}`}read(e,t){let n=this.data[this.key(e,t)];return n===void 0?null:n}commit(e,t,n){let s=this.key(e,t);this.data[s]!==n&&(this.data[s]=n,this.persist())}snapshot(){return{...this.data}}persist(){let e=Ms(this.filePath);un(e)||Ts(e,{recursive:!0});let t=`${this.filePath}.tmp`;Cs(t,JSON.stringify(this.data,null,2)),As(t,this.filePath)}},ot;function pn(c){return ot||(ot=new at(c??process.cwd())),ot}var lt=class{data={};filePath;dirty=!1;constructor(e){this.filePath=yn(e,".agentx/telegram/groups.json"),this.load()}load(){try{dt(this.filePath)&&(this.data=JSON.parse(ct(this.filePath,"utf-8")))}catch{this.data={}}}save(){try{fn(bn(this.filePath),{recursive:!0}),mn(this.filePath,JSON.stringify(this.data,null,2)),this.dirty=!1}catch{}}setBotStatus(e,t,n,s,i,r){this.data[e]||(this.data[e]={name:t,bots:{}}),t&&(this.data[e].name=t),this.data[e].bots[n]={username:i,agentId:s,status:r,updatedAt:new Date().toISOString()},this.dirty=!0,this.save()}getGroupBots(e){let t=this.data[e];return t?Object.entries(t.bots).filter(([,n])=>n.status!=="left"&&n.status!=="kicked").map(([n,s])=>({accountId:n,agentId:s.agentId,username:s.username})):[]}hasGroup(e){return!!this.data[e]}listGroups(){return Object.entries(this.data).map(([e,t])=>({id:e,name:t.name,botCount:Object.values(t.bots).filter(n=>n.status!=="left"&&n.status!=="kicked").length}))}};var K=class{name="telegram";accounts;cursors;handler;polling=!1;accountPolling=new Map;log;globalAllowFrom;constructor(e,t={},n=console.error.bind(console,"[telegram]")){this.accounts=new Map(Object.entries(e)),this.globalAllowFrom=t.policy?.allowFrom,this.log=n,this.groupStore=new lt(process.cwd()),this.cursors=pn(process.cwd())}effectiveAllowFrom(e){let t=this.accounts.get(e);return t?.allowFrom!==void 0?t.allowFrom:this.globalAllowFrom}isAllowed(e,t,n,s){let i=this.effectiveAllowFrom(e);if(!i||i.length===0)return!1;let r=t!=null?String(t):"",o=n!=null?String(n):"",a=s?.toLowerCase();for(let l of i)if(l&&(l===r||l===o||l.startsWith("@")&&a&&l.slice(1).toLowerCase()===a))return!0;return!1}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];await this.startAccount(n,s,{index:t+1,of:e.length}),t<e.length-1&&await new Promise(i=>setTimeout(i,300))}this.log(`All ${e.length} Telegram account(s) started`)}async startAccount(e,t,n={}){if(this.accountPolling.get(e)){this.log(`Account "${e}" already polling \u2014 skipping duplicate start`);return}let s=n.index!=null&&n.of!=null?`(${n.index}/${n.of})`:"(hot-reload)";if(t.pollInbound===!1){this.log(`Account "${e}" ${s} \u2014 send-only (pollInbound=false), skipping getUpdates loop`);try{let i=await this.apiCall(t.token,"getMe"),r=i.result?.id,o=i.result?.username;r&&this.botInfo.set(e,{userId:r,username:o||e})}catch(i){this.log(`Send-only account "${e}" getMe failed: ${i.message} \u2014 send may still work if token is valid`)}return}this.log(`Starting polling for account "${e}" ${s}`);try{await this.apiCall(t.token,"deleteWebhook",{drop_pending_updates:!1}).catch(()=>{});let i,r,o=[0,2e3,5e3,1e4];for(let d=0;d<o.length;d++){o[d]>0&&await new Promise(g=>setTimeout(g,o[d]));try{i=await this.apiCall(t.token,"getMe"),d>0&&this.log(`Bot account "${e}" verified on retry ${d}`);break}catch(g){r=g,d<o.length-1&&this.log(`Verify attempt ${d+1} failed for "${e}" (${g.message}) \u2014 retrying`)}}if(!i)throw r;let a=i.result?.id,l=i.result?.username;this.log(`Bot @${l} ready (account: ${e})`),a&&this.botInfo.set(e,{userId:a,username:l||e}),this.accountPolling.set(e,!0),this.pollLoop(e,t)}catch(i){this.log(`Failed to verify bot for account "${e}" after retries: ${i.message}`)}}async stopAccount(e){this.accountPolling.set(e,!1);let t=this.accounts.get(e);if(t)try{await this.apiCall(t.token,"getUpdates",{offset:-1,timeout:0})}catch{}}async stop(){this.polling=!1;let e=Array.from(this.accounts.keys()).map(t=>this.stopAccount(t));await Promise.allSettled(e)}async reloadAccounts(e,t){if(!this.polling)return this.accounts=new Map(Object.entries(e)),this.globalAllowFrom=t?.allowFrom,{added:[],removed:[],tokenChanged:[]};let n=new Set(this.accounts.keys()),s=new Set(Object.keys(e)),i=[],r=[],o=[];this.globalAllowFrom=t?.allowFrom;for(let a of n)s.has(a)||(await this.stopAccount(a),this.accounts.delete(a),this.botInfo.delete(a),r.push(a));for(let a of s){if(!n.has(a))continue;let l=this.accounts.get(a),d=e[a];this.accounts.set(a,d),l.token!==d.token&&(await this.stopAccount(a),await this.startAccount(a,d),o.push(a))}for(let a of s)n.has(a)||(this.accounts.set(a,e[a]),await this.startAccount(a,e[a]),i.push(a));return{added:i,removed:r,tokenChanged:o}}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;botInfo=new Map;groupStore;getGroupBotAccounts(e){return this.groupStore.getGroupBots(e).map(t=>t.accountId)}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,i=e.parseMode==="markdown"||e.parseMode===void 0?ae(s):s,r={chat_id:e.chatId,text:i,parse_mode:"HTML"};e.replyTo&&(r.reply_to_message_id=parseInt(e.replyTo,10)),e.parseMode==="html"?(r.parse_mode="HTML",r.text=s):e.parseMode==="plain"&&(delete r.parse_mode,r.text=s);try{let o=await this.apiCall(t,"sendMessage",r),a=String(o.result?.message_id||"");return this.recordOutboundShadow(e.chatId,a,s,e.agentId,e.accountId),a}catch(o){if(r.parse_mode){delete r.parse_mode,r.text=s;let a=await this.apiCall(t,"sendMessage",r),l=String(a.result?.message_id||"");return this.recordOutboundShadow(e.chatId,l,s,e.agentId,e.accountId),l}throw o}}recordOutboundShadow(e,t,n,s,i){if(t)try{this.appendShadowLog(e,{externalId:t,role:"agent",name:s||i||"agent",content:n,timestamp:new Date().toISOString(),accountId:i})}catch(r){this.log(`outbound shadow-log write failed: ${r.message}`)}}async sendWithInlineButtons(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,i=e.parseMode==="markdown"||e.parseMode===void 0?ae(s):s,r={chat_id:e.chatId,text:i,parse_mode:e.parseMode==="plain"?void 0:"HTML",reply_markup:JSON.stringify({inline_keyboard:e.buttons.map(o=>[{text:o.label,url:o.url}])})};r.parse_mode===void 0&&delete r.parse_mode;try{let o=await this.apiCall(t,"sendMessage",r);return String(o.result?.message_id||"")}catch(o){if(r.parse_mode){delete r.parse_mode,r.text=s;let a=await this.apiCall(t,"sendMessage",r);return String(a.result?.message_id||"")}throw o}}async editMessage(e,t,n,s,i){let r=this.resolveToken(e,i);if(!r)return!1;let o=4096,a=n.length>o?n.slice(0,o-3)+"...":n,l=s!=="html"&&s!=="plain"?ae(a):a,d={chat_id:e,message_id:parseInt(t,10),text:l,parse_mode:"HTML"};s==="html"?(d.parse_mode="HTML",d.text=a):s==="plain"&&(delete d.parse_mode,d.text=a);try{return await this.apiCall(r,"editMessageText",d),!0}catch(g){if(g.message?.includes("message is not modified"))return!0;if(d.parse_mode){delete d.parse_mode,d.text=a;try{return await this.apiCall(r,"editMessageText",d),!0}catch{return!1}}return!1}}async sendDraft(e,t,n,s,i){if(!K.isDirectMessage(e))return!1;let r=this.resolveToken(e,i);if(!r)return!1;let o=4096,a=n.length>o?n.slice(0,o-3)+"...":n;if(!a)return!1;let l=s!=="html"&&s!=="plain"?ae(a):a,d={chat_id:parseInt(e,10),draft_id:t,text:l,parse_mode:"HTML"};s==="plain"?(delete d.parse_mode,d.text=a):s==="html"&&(d.text=a);try{return await this.apiCall(r,"sendMessageDraft",d),!0}catch{if(d.parse_mode){delete d.parse_mode,d.text=a;try{return await this.apiCall(r,"sendMessageDraft",d),!0}catch{return!1}}return!1}}static isDirectMessage(e){let t=parseInt(e,10);return Number.isFinite(t)&&t>0}async react(e,t,n="\u{1F440}",s){let i=this.resolveToken(e,s);if(i)try{await this.apiCall(i,"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&&this.accountPolling.get(e)!==!1;)try{let s=this.cursors.read("telegram",e),i=typeof s=="number"?s:0,o=(await this.apiCall(t.token,"getUpdates",{offset:i||void 0,timeout:30,allowed_updates:["message","my_chat_member"]})).result||[];for(let a of o){if(this.cursors.commit("telegram",e,a.update_id+1),a.message&&this.handler){let l=a.message,d=l.text||l.caption||"",g,h=l.photo&&l.photo.length>0,p=!!l.voice,u=!!l.audio,f=!!l.video,m=!!l.document;if(h||p||u||f||m){let I,k="application/octet-stream";if(h?(I=l.photo[l.photo.length-1].file_id,k="image/jpeg",d||(d="[Photo attached \u2014 please describe what you see]")):p?(I=l.voice.file_id,k=l.voice.mime_type||"audio/ogg",d||(d="[Voice message \u2014 please transcribe and respond]")):u?(I=l.audio.file_id,k=l.audio.mime_type||"audio/mpeg",d||(d=`[Audio: ${l.audio.title||"audio file"}]`)):f?(I=l.video.file_id,k=l.video.mime_type||"video/mp4",d||(d="[Video attached]")):m&&(I=l.document.file_id,k=l.document.mime_type||"application/octet-stream",d||(d=`[Document: ${l.document.file_name||"file"}]`)),I)try{let T=(await this.apiCall(t.token,"getFile",{file_id:I})).result?.file_path;if(T){let x=`https://api.telegram.org/file/bot${t.token}/${T}`,C=await fetch(x);if(C.ok){let A=Buffer.from(await C.arrayBuffer()),O=k.split("/")[1]?.split(";")[0]||"bin",{mkdirSync:N,writeFileSync:qe}=await import("fs"),{randomUUID:j}=await import("crypto"),{resolve:G,join:D}=await import("path"),V=G(process.cwd(),".agentx/media/telegram");N(V,{recursive:!0});let U=l.document?.file_name||`${j()}.${O}`,Q=D(V,U);qe(Q,A),g={path:Q,type:k,fileName:U}}}}catch(S){this.log(`Media download failed: ${S.message}`)}}if(!d)continue;if(!this.isAllowed(e,l.from?.id,l.chat?.id,l.from?.username)){this.log(`[telegram/${e}] dropped message from ${l.from?.id}${l.from?.username?` (@${l.from.username})`:""} in chat ${l.chat?.id} \u2014 not in allowlist`);continue}let b=l.chat.type!=="private",w=String(l.chat.id),v;b&&(this.groupStore.hasGroup(w)||await this.seedGroupMembership(w,l.chat.title),v=await this.getChannelMeta(w));let $={id:String(l.message_id),channel:"telegram",accountId:e,sender:{id:String(l.from.id),name:[l.from.first_name,l.from.last_name].filter(Boolean).join(" "),username:l.from.username,isBot:l.from.is_bot===!0},group:b?{id:w,name:l.chat.title||""}:void 0,text:d,media:g,replyTo:l.reply_to_message?String(l.reply_to_message.message_id):void 0,replyToText:l.reply_to_message?l.reply_to_message.text||l.reply_to_message.caption||`[message from ${l.reply_to_message.from?.first_name||"unknown"}]`:void 0,timestamp:new Date(l.date*1e3),raw:a,channelMeta:v};this.chatAccountMap.set(String(l.chat.id),e);try{this.appendShadowLog(String(l.chat.id),{externalId:String(l.message_id),role:"user",name:$.sender.name,content:d,timestamp:$.timestamp.toISOString(),accountId:e})}catch(I){this.log(`shadow-log write failed: ${I.message}`)}this.handler($).catch(I=>{this.log(`Error handling message: ${I.message}`)})}if(a.my_chat_member){let l=a.my_chat_member,d=String(l.chat.id),g=l.chat.title,h=l.new_chat_member.status,p=l.new_chat_member.user.username||e;this.groupStore.setBotStatus(d,g,e,t.agentBinding,p,h),this.log(`Group membership: @${p} is now "${h}" in "${g||d}"`)}}n=0}catch(s){n++;let i=Math.min(5e3*Math.pow(2,n-1),6e4);this.log(`Poll error (${e}): ${s.message} [retry in ${i/1e3}s, errors: ${n}]`),await new Promise(r=>setTimeout(r,i))}}listKnownChats(){let e=[];for(let[t,n]of this.chatAccountMap)K.isDirectMessage(t)&&e.push({id:t,kind:"dm",accountId:n});for(let t of this.groupStore.listGroups())e.push({id:t.id,name:t.name,kind:"group"});return e}async getChannelMeta(e){let t=this.groupStore.getGroupBots(e);if(t.length)return{channel:"telegram",agents:t.map(n=>({id:n.agentId,name:n.username,handle:`@${n.username}`})),facts:[`${t.length} bot(s) verified in this group`]}}async seedGroupMembership(e,t){this.log(`Seeding group membership for "${t||e}"`);for(let[n,s]of this.accounts){let i=this.botInfo.get(n);if(i)try{let o=(await this.apiCall(s.token,"getChatMember",{chat_id:Number(e),user_id:i.userId})).result?.status;o&&this.groupStore.setBotStatus(e,t,n,s.agentBinding,i.username,o)}catch{this.groupStore.setBotStatus(e,t,n,s.agentBinding,i.username,"left")}}this.log(`Seeded: ${this.groupStore.getGroupBots(e).length} bot(s) in "${t||e}"`)}appendShadowLog(e,t){let n=t.timestamp.slice(0,10),s=this.shadowLogPath(e,n),i={messages:[]};if(dt(s))try{i=JSON.parse(ct(s,"utf-8")),Array.isArray(i.messages)||(i.messages=[])}catch{i={messages:[]}}i.messages.some(r=>r.externalId===t.externalId&&r.role===t.role)||(i.messages.push(t),fn(bn(s),{recursive:!0}),mn(s,JSON.stringify(i,null,2)))}shadowLogPath(e,t){let n=e.replace(/[^a-zA-Z0-9_-]/g,"_");return yn(process.cwd(),".agentx/sessions",`_telegram_raw:${n}:${t}.json`)}async seedHistory(e,t){let n=[],s=0,i=new Date,r=t.sinceISO?new Date(t.sinceISO):new Date(i.getTime()-14*864e5);for(let o=0;o<14;o++){let a=new Date(i.getTime()-o*864e5);if(a.getTime()<r.getTime()-864e5)break;let l=a.toISOString().slice(0,10),d=this.shadowLogPath(e,l);if(dt(d)){try{let h=(JSON.parse(ct(d,"utf-8")).messages??[]).slice();for(let p=h.length-1;p>=0;p--){let u=h[p];if(!(t.sinceISO&&u.timestamp<t.sinceISO)&&(n.push({role:u.role,name:u.name,content:u.content,timestamp:u.timestamp,externalId:u.externalId,accountId:u.accountId}),s+=u.content.length,n.length>=t.maxMessages||s>=t.maxChars))break}}catch{}if(n.length>=t.maxMessages||s>=t.maxChars)break}}return n.reverse()}async apiCall(e,t,n){let s=`https://api.telegram.org/bot${e}/${t}`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});if(!i.ok){let r=await i.text();throw new Error(`Telegram API error: ${i.status} ${r}`)}return i.json()}};import{mkdirSync as kn,writeFileSync as Ls}from"fs";import{resolve as vn,join as Bs}from"path";import{randomUUID as Gs}from"crypto";import{readFileSync as _s,writeFileSync as Ps,mkdirSync as Es,existsSync as wn}from"fs";import{resolve as js,dirname as Os}from"path";var we=class{contacts=new Map;chats=new Map;groups=new Map;cachePath;constructor(e){this.cachePath=js(e,"cache.json"),this.load()}listContacts(){return Array.from(this.contacts.values())}listChats(){return Array.from(this.chats.values())}listGroups(){return Array.from(this.groups.values())}getContact(e){return this.contacts.get(e)}getChat(e){return this.chats.get(e)}getGroup(e){return this.groups.get(e)}applyContactsUpdate(e){let t=new Date().toISOString();for(let n of e){let s=typeof n.id=="string"?n.id:"";if(!s)continue;let i=this.contacts.get(s)??{jid:s,phone:Ds(s),updatedAt:t},r={...i,pushName:gt(n.notify,n.pushName,i.pushName),savedName:gt(n.name,n.verifiedName,i.savedName),status:gt(n.status,i.status),updatedAt:t};this.contacts.set(s,r)}}applyChatsUpsert(e){let t=new Date().toISOString();for(let n of e){let s=typeof n.id=="string"?n.id:"";if(!s)continue;let i={jid:s,name:typeof n.name=="string"?n.name:this.chats.get(s)?.name,isGroup:s.endsWith("@g.us"),lastMessageAt:Ns(n.conversationTimestamp)??this.chats.get(s)?.lastMessageAt,unreadCount:typeof n.unreadCount=="number"?n.unreadCount:this.chats.get(s)?.unreadCount,updatedAt:t};this.chats.set(s,i)}}applyGroupsUpdate(e){let t=new Date().toISOString();for(let n of e){let s=typeof n.id=="string"?n.id:"";if(!s)continue;let i=this.groups.get(s)??{jid:s,subject:"",members:[],updatedAt:t},r=Array.isArray(n.participants)?n.participants.map(a=>({jid:typeof a.id=="string"?a.id:"",admin:typeof a.admin=="string"?a.admin:void 0})).filter(a=>a.jid):i.members,o={...i,subject:typeof n.subject=="string"?n.subject:i.subject,description:typeof n.desc=="string"?n.desc:i.description,owner:typeof n.owner=="string"?n.owner:i.owner,members:r,updatedAt:t};this.groups.set(s,o)}}applyHistorySet(e){Array.isArray(e.chats)&&this.applyChatsUpsert(e.chats),Array.isArray(e.contacts)&&this.applyContactsUpdate(e.contacts)}save(){let e={version:1,contacts:this.listContacts(),chats:this.listChats(),groups:this.listGroups()},t=Os(this.cachePath);wn(t)||Es(t,{recursive:!0}),Ps(this.cachePath,JSON.stringify(e,null,2),"utf8")}load(){if(wn(this.cachePath))try{let e=JSON.parse(_s(this.cachePath,"utf8"));if(e.version!==1)return;for(let t of e.contacts??[])this.contacts.set(t.jid,t);for(let t of e.chats??[])this.chats.set(t.jid,t);for(let t of e.groups??[])this.groups.set(t.jid,t)}catch{}}};function Ds(c){let e=c.split("@")[0]??"";return!e||c.endsWith("@lid")?"":e.replace(/[^0-9]/g,"")}function gt(...c){for(let e of c)if(typeof e=="string"&&e.length>0)return e}function Ns(c){if(typeof c=="number"&&Number.isFinite(c))return c;if(c&&typeof c=="object"&&"low"in c&&"high"in c){let e=c.low;return c.high*4294967296+(e>>>0)}}var ve=class{name="whatsapp";sessionDir;defaultAgent;allowFrom;routes;handler;sock=null;reconnectAttempts=0;generation=0;sentMessageIds=new Set;log;cache;throttleMinMs=1500;throttleMaxPerMinute=20;lastReadAt=0;readsInWindow=[];onQR;onStatus;constructor(e,t=console.error.bind(console,"[whatsapp]")){this.sessionDir=vn(e.sessionDir),this.defaultAgent=e.defaultAgent,this.allowFrom=e.allowFrom,this.routes=e.routes||[],this.onQR=e.onQR,this.onStatus=e.onStatus,this.log=t,this.cache=new we(this.sessionDir),e.throttle?.minMsBetweenCalls&&(this.throttleMinMs=e.throttle.minMsBetweenCalls),e.throttle?.maxCallsPerMinute&&(this.throttleMaxPerMinute=e.throttle.maxCallsPerMinute)}getCache(){return this.cache}isConnected(){return!!this.sock&&!!this.sock.user}resolveAgent(e,t,n){for(let s of this.routes){if(s.contact){let i=s.contact.replace(/\+/g,"");if(e.includes(i)||i.includes(e))return s.agent}if(s.group&&(t||n)){let i=s.group.toLowerCase();if(t?.toLowerCase().includes(i)||n?.toLowerCase().includes(i))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}kn(this.sessionDir,{recursive:!0});let i=++this.generation;if(this.sock){try{this.sock.end(void 0)}catch{}this.sock=null}let{state:r,saveCreds:o}=await t(this.sessionDir),a;try{let{version:d}=await s.fetchLatestBaileysVersion();a=d,this.log(`WhatsApp Web version: ${d.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let l={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...d)=>this.log("WA error:",...d),child:()=>l};this.sock=e({auth:{creds:r.creds,keys:s.makeCacheableSignalKeyStore?s.makeCacheableSignalKeyStore(r.keys,l):r.keys},...a?{version:a}:{},logger:l,printQRInTerminal:!1,browser:["agentx","server","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1}),this.sock.ev.on("creds.update",o),this.sock.ev.on("messaging-history.set",d=>{this.log(`WA history sync: ${d.messages?.length||0} messages, ${d.isLatest?"latest":"partial"}`);try{this.cache.applyHistorySet(d)}catch(g){this.log(`cache history-set error: ${g.message}`)}}),this.sock.ev.on("contacts.update",d=>{try{this.cache.applyContactsUpdate(d)}catch(g){this.log(`cache contacts.update error: ${g.message}`)}}),this.sock.ev.on("contacts.upsert",d=>{try{this.cache.applyContactsUpdate(d)}catch(g){this.log(`cache contacts.upsert error: ${g.message}`)}}),this.sock.ev.on("chats.upsert",d=>{try{this.cache.applyChatsUpsert(d)}catch(g){this.log(`cache chats.upsert error: ${g.message}`)}}),this.sock.ev.on("chats.update",d=>{try{this.cache.applyChatsUpsert(d)}catch(g){this.log(`cache chats.update error: ${g.message}`)}}),this.sock.ev.on("groups.update",d=>{try{this.cache.applyGroupsUpdate(d)}catch(g){this.log(`cache groups.update error: ${g.message}`)}}),this.sock.ev.on("connection.update",async d=>{let{connection:g,lastDisconnect:h,qr:p}=d;if(i===this.generation){if(p){this.log("Scan QR code with WhatsApp to connect:");try{this.onQR?.(p)}catch{}try{let{default:u}=await import("qrcode-terminal");u.generate(p,{small:!0})}catch{this.log(`QR: ${p}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(g)try{this.onStatus?.(g,h?.error?.message)}catch{}if(g==="open")try{this.onQR?.(null)}catch{}if(g==="close"){let u=h?.error?.output?.statusCode,f=h?.error?.output?.payload?.message||"";if(this.log(`WhatsApp connection closed (status: ${u}, reason: ${f})`),u===n?.loggedOut||u===401)this.log("Logged out. Delete session dir and restart to re-scan QR.");else if(u===440||u===408){if(this.reconnectAttempts++,this.reconnectAttempts>=5){this.log(`WhatsApp: giving up after ${this.reconnectAttempts} conflict attempts. Another session is active for this number \u2014 close it or re-scan QR.`);return}let m=Math.min(1e4*Math.pow(2,this.reconnectAttempts-1),12e4);this.log(`Reconnecting in ${m/1e3}s (attempt ${this.reconnectAttempts}/5)...`),setTimeout(()=>this.start(),m)}else u===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):u!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}g==="open"&&this.log("WhatsApp connected")}}),this.sock.ev.on("messages.upsert",async d=>{if(this.reconnectAttempts>0&&(this.log(`WhatsApp connection stable, resetting reconnect counter (was ${this.reconnectAttempts})`),this.reconnectAttempts=0),this.log(`WA messages.upsert: ${d.messages?.length||0} messages, type: ${d.type}`),!!this.handler)for(let g of d.messages||[]){let h=(g.key.remoteJid||"").replace(/@.*/,"").slice(-6),p=!!(g.message?.conversation||g.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${h} fromMe=${g.key.fromMe} hasText=${p} 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 j=this.sock?.user,G=g.key.remoteJid||"",D=j?.id?.replace(/:.*/,"")||"",V=j?.lid?.replace(/:.*/,"")||"",U=G.replace(/:.*/,"").replace(/@.*/,"");if(!(U===D||U===V))continue}let u=g.message?.conversation||g.message?.extendedTextMessage?.text||g.message?.imageMessage?.caption||g.message?.videoMessage?.caption||"",f=g.message||{},m=!!f.imageMessage,y=!!f.audioMessage,b=!!f.videoMessage,w=!!f.documentMessage,v=!!f.stickerMessage,$=m||y||b||w||v;if($&&!u&&(m?u="[Image attached \u2014 please describe what you see]":y?u="[Voice message attached \u2014 please transcribe and respond]":b?u="[Video attached]":w?u=`[Document: ${f.documentMessage?.fileName||"file"}]`:v&&(u="[Sticker]")),!u)continue;let I=g.key.remoteJid||"",k=I.endsWith("@g.us"),S=I.replace(/@.*$/,""),x=(k?g.key.participant||"":I).replace(/@.*$/,"");if(this.allowFrom?.length&&!g.key.fromMe&&!this.allowFrom.some(G=>{let D=G.replace(/\+/g,"");return x.includes(D)||S.includes(D)}))continue;let C=g.key.fromMe?"me":g.pushName||x,A;if(k&&this.sock)try{A=(await this.sock.groupMetadata(I)).subject}catch{}let O=this.resolveAgent(x,A,k?I:void 0);if(!O){this.log(`No route for ${k?`group ${A||I}`:x}, skipping`);continue}let N;if($&&this.sock)try{let G=await(await import("@whiskeysockets/baileys")).downloadMediaMessage(g,"buffer",{},{reuploadRequest:this.sock.updateMediaMessage,logger:this.sock.logger});if(G){let D=f.imageMessage?.mimetype||f.audioMessage?.mimetype||"audio/ogg",V=D.split("/")[1]?.split(";")[0]||"bin",U=vn(this.sessionDir,"../media/inbound");kn(U,{recursive:!0});let Q=f.documentMessage?.fileName||`${Gs()}.${V}`,Ke=Bs(U,Q);Ls(Ke,G),N={path:Ke,type:D,fileName:Q},this.log(`WA media saved: ${D} -> ${Ke}`)}}catch(j){this.log(`WA media download failed: ${j.message}`)}let qe={id:g.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:g.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||x)+"@s.whatsapp.net":x,name:C,username:x},group:k?{id:I,name:A||I}:void 0,text:u,media:N,replyTo:g.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((g.messageTimestamp||0)*1e3),raw:g,resolvedAgent:O};this.handler(qe).catch(j=>{this.log(`Error handling message: ${j.message}`)})}})}async stop(){try{this.cache.save()}catch(e){this.log(`cache save error: ${e.message}`)}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 n;if(e.poll)n={poll:{name:e.poll.name,values:e.poll.values,selectableCount:e.poll.selectableCount??1}};else if(e.media){let r={mimetype:e.media.mimetype};e.media.caption&&(r.caption=e.media.caption),e.media.fileName&&(r.fileName=e.media.fileName);let o={url:e.media.url};switch(e.media.type){case"image":n={image:o,...r};break;case"video":n={video:o,...r};break;case"audio":n={audio:o,ptt:!1,...r};break;case"document":n={document:o,...r};break;default:n={document:o,...r}}}else n={text:e.text};let i=(await this.sock.sendMessage(t,n))?.key?.id||"";return i&&this.sentMessageIds.add(i),i}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{}}listContacts(){return this.cache.listContacts().map($n)}listChats(){return this.cache.listChats().map(Us)}async getContactProfile(e){let t=this.cache.getContact(e);return t?$n(t):null}async getGroupMetadata(e){let t=this.cache.getGroup(e);if(t&&t.subject)return ke(t);if(!this.isConnected())return t?ke(t):null;try{let n=await this.throttleGate(()=>this.sock.groupMetadata(e));this.cache.applyGroupsUpdate([{id:e,subject:n?.subject,desc:n?.desc,owner:n?.owner,participants:n?.participants}]);let s=this.cache.getGroup(e);return s?ke(s):null}catch(n){return this.log(`getGroupMetadata(${e}) failed: ${n.message}`),t?ke(t):null}}async getHistory(e,t={}){if(!this.isConnected())return[];let n=Math.max(1,Math.min(500,t.limit??50));try{return(await this.throttleGate(async()=>{let i=this.sock;return typeof i.loadMessages=="function"?await i.loadMessages(e,n,t.before?{before:{id:t.before}}:void 0):typeof i.fetchMessagesFromWA=="function"?await i.fetchMessagesFromWA(e,n,t.before?{before:{id:t.before}}:void 0):[]})||[]).map(Fs).filter(Boolean)}catch(s){return this.log(`getHistory(${e}) failed: ${s.message}`),[]}}async seedHistory(e,t){let n=t.sinceISO?new Date(t.sinceISO).getTime():0,s=await this.getHistory(e,{limit:t.maxMessages}),i=[],r=0;for(let o of s){if(n&&(o.timestamp??0)*1e3<n||!o.text)continue;let a=o.timestamp?new Date(o.timestamp*1e3).toISOString():new Date().toISOString();if(i.push({role:o.fromMe?"agent":"user",name:o.fromMe?"agent":o.fromJid||"user",content:o.text,timestamp:a,externalId:o.id}),r+=o.text.length,i.length>=t.maxMessages||r>=t.maxChars)break}return i}async throttleGate(e){let t=Date.now();if(this.readsInWindow=this.readsInWindow.filter(s=>t-s<6e4),this.readsInWindow.length>=this.throttleMaxPerMinute){let s=6e4-(t-this.readsInWindow[0])+10;await Sn(s)}let n=Date.now()-this.lastReadAt;return n<this.throttleMinMs&&await Sn(this.throttleMinMs-n),this.lastReadAt=Date.now(),this.readsInWindow.push(this.lastReadAt),e()}};function $n(c){return{jid:c.jid,phone:c.phone,name:c.savedName||c.pushName||c.phone||c.jid,pushName:c.pushName,savedName:c.savedName,status:c.status,updatedAt:c.updatedAt}}function Us(c){return{jid:c.jid,name:c.name||c.jid.replace(/@.*$/,""),isGroup:c.isGroup,lastMessageAt:c.lastMessageAt,unreadCount:c.unreadCount}}function ke(c){return{jid:c.jid,subject:c.subject||"",description:c.description,owner:c.owner,members:c.members.map(e=>({jid:e.jid,admin:e.admin})),memberCount:c.members.length}}function Fs(c){if(!c||!c.key)return null;let e=c.message||{},t=e.conversation||e.extendedTextMessage?.text||e.imageMessage?.caption||e.videoMessage?.caption||"",n;if(e.imageMessage?n={kind:"image",caption:e.imageMessage.caption}:e.audioMessage?n={kind:"audio"}:e.videoMessage?n={kind:"video",caption:e.videoMessage.caption}:e.documentMessage?n={kind:"document",filename:e.documentMessage.fileName}:e.stickerMessage&&(n={kind:"sticker"}),!t&&!n)return null;let s=typeof c.messageTimestamp=="number"?c.messageTimestamp:c.messageTimestamp?.low??void 0;return{id:c.key.id,fromJid:c.key.fromMe?c.key.remoteJid||"":c.key.participant||c.key.remoteJid||"",fromMe:!!c.key.fromMe,timestamp:s,text:t,media:n}}function Sn(c){return new Promise(e=>setTimeout(e,Math.max(0,c)))}import{createServer as Gi}from"http";import{writeFileSync as qn,existsSync as he,unlinkSync as Ui,mkdirSync as Kn,readFileSync as Xe,watch as Fi}from"fs";import{resolve as B,dirname as Hi}from"path";var $e=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 i=s.mentions.users.has(this.client.user?.id),r=!s.guild;if(!i&&!r)return;let o=s.content;if(this.client.user&&(o=o.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()),!o)return;let a={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:o,replyTo:s.reference?.messageId,timestamp:s.createdAt,raw:s};this.handler(a).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{}}};var Se=class{name="slack";botToken;appToken;agentBinding;handler;socket=null;web=null;botUserId;log;constructor(e,t=console.error.bind(console,"[slack]")){this.botToken=e.botToken,this.appToken=e.appToken,this.agentBinding=e.agentBinding,this.log=t}onMessage(e){this.handler=e}async start(){let e,t;try{e=await import("@slack/socket-mode"),t=await import("@slack/web-api")}catch{this.log("Slack requires @slack/socket-mode and @slack/web-api. Install with:"),this.log(" npm install @slack/socket-mode @slack/web-api");return}let{SocketModeClient:n}=e,{WebClient:s}=t;this.web=new s(this.botToken);try{let r=await this.web.auth.test();this.botUserId=r.user_id,this.log(`Slack connected as @${r.user} (${this.botUserId}) in team ${r.team}`)}catch(r){this.log(`Slack auth.test failed: ${r.message}`);return}this.socket=new n({appToken:this.appToken});let i=async(r,o)=>{try{await o()}catch{}if(!this.handler)return;let a=r.event;if(!a||typeof a.text!="string"||a.bot_id||a.user===this.botUserId||a.subtype==="bot_message")return;let l=a.channel_type==="im",d=this.botUserId&&a.text.includes(`<@${this.botUserId}>`);if(!l&&!d)return;let g=a.text;if(this.botUserId&&(g=g.replace(new RegExp(`<@${this.botUserId}>`,"g"),"").trim()),!g)return;let h=a.user||"slack-user";try{let u=await this.web.users.info({user:a.user});h=u?.user?.profile?.display_name||u?.user?.real_name||h}catch{}let p={id:a.client_msg_id||a.ts,channel:"slack",accountId:"default",sender:{id:a.user,name:h,username:h},group:l?void 0:{id:a.channel,name:a.channel},text:g,replyTo:a.thread_ts&&a.thread_ts!==a.ts?a.thread_ts:void 0,timestamp:a.ts?new Date(parseFloat(a.ts)*1e3):new Date,raw:a};try{await this.handler(p)}catch(u){this.log(`Error handling message: ${u.message}`)}};this.socket.on("app_mention",i),this.socket.on("message",i),this.socket.on("error",r=>this.log(`Slack socket error: ${r?.message||r}`));try{await this.socket.start()}catch(r){this.log(`Slack socket start failed: ${r.message}`)}}async stop(){if(this.socket){try{await this.socket.disconnect()}catch{}this.socket=null}this.web=null}async send(e){if(!this.web)return"";try{return(await this.web.chat.postMessage({channel:e.chatId,text:e.text,thread_ts:e.replyTo,mrkdwn:e.parseMode!=="plain"})).ts}catch(t){return this.log(`Send error: ${t.message}`),""}}async editMessage(e,t,n){if(!this.web)return!1;try{return await this.web.chat.update({channel:e,ts:t,text:n}),!0}catch(s){return this.log(`Edit error: ${s.message}`),!1}}async react(e,t,n="eyes"){if(this.web)try{let s=n.replace(/^:|:$/g,"");await this.web.reactions.add({channel:e,timestamp:t,name:s})}catch{}}};import{createServer as Xs}from"http";function Hs(c,e,t,n=Date.now){return{ts:n(),source:"gitlab",sourceEventId:`${c.entityKind}:${c.iid}:${c.action}:${e.agentId}:${e.trigger}`,project:c.project,subject:`${c.entityKind}:${c.iid}:agent:${e.agentId}:trigger:${e.trigger}`,intent:`${c.entityKind}.${c.action}`,rawJson:t}}function Ws(c,e){return{decidedBy:`gitlab:${c}:target-${e.trigger}`,decide:()=>({agentId:e.agentId,outcome:"dispatched",reason:null})}}function Ie(c,e,t,n,s,i=Date.now){let r=Hs(e,t,n,i),o=Ws(e.entityKind,t),a=F(c,r,o,i);return H(c,"gitlab",a,s,i),a}function Js(c,e,t=Date.now){return{ts:t(),source:"gitlab",sourceEventId:`note:${c.noteId}`,project:c.project,subject:`${c.noteableType}:${c.noteableIid}:note:${c.noteId}`,intent:`note.${c.noteableType}`,rawJson:e}}function zs(c){return{decidedBy:"gitlab:note:mention",decide:()=>({agentId:c,outcome:c?"dispatched":"halted",reason:c?null:"no @mention resolved to an agent"})}}function ht(c,e,t,n,s=Date.now){let i=Js(e,t,s),r=zs(n.agentId),o=F(c,i,r,s);return H(c,"gitlab",o,n,s),o}function In(c,e,t,n,s,i,r=Date.now){let o={ts:r(),source:"gitlab",sourceEventId:`${e.entityKind}:${e.iid}:${e.action}:${t}`,project:e.project,subject:`${e.entityKind}:${e.iid}:${t}`,intent:`${e.entityKind}.${e.action}`,rawJson:s},l=F(c,o,{decidedBy:n,decide:()=>({agentId:i.agentId,outcome:i.outcome==="deduped"?"halted":i.outcome,reason:i.outcome==="deduped"?`legacy-dedup: ${i.reason??""}`.trim():i.reason??null})},r);return H(c,"gitlab",l,i,r),l}var Te=class{name="gitlab";config;handler;server;botUsername;botUsernames=new Set;sentNoteIds=new Set;usernameToAgent=new Map;agentToUsername=new Map;dispatchedTargets=new Map;DISPATCH_TTL_MS=5*60*1e3;log;hooks;reactForwarder;sendNoteForwarder;logTimeForwarder;createIssueForwarder;setLabelsForwarder;constructor(e,t=console.error.bind(console,"[gitlab]"),n){this.config=e,this.log=t,this.hooks=n}setReactForwarder(e){this.reactForwarder=e}setSendNoteForwarder(e){this.sendNoteForwarder=e}setLogTimeForwarder(e){this.logTimeForwarder=e}setCreateIssueForwarder(e){this.createIssueForwarder=e}setSetLabelsForwarder(e){this.setLabelsForwarder=e}onMessage(e){this.handler=e}async start(){let e=[];this.config.token&&e.push({label:"global",token:this.config.token});for(let i of this.config.agentMappings||[])i.token&&e.push({label:i.agentId,token:i.token});let t=await Promise.allSettled(e.map(async({label:i,token:r})=>{let o=await fetch(`${this.config.host}/api/v4/user`,{headers:{"PRIVATE-TOKEN":r}});if(!o.ok)throw new Error(`${o.status}`);let a=await o.json();return{label:i,username:a.username}}));for(let i of t)if(i.status==="fulfilled"){let{label:r,username:o}=i.value;this.botUsernames.add(o),r==="global"?(this.botUsername=o,this.log(`Global bot user: ${o}`)):(this.usernameToAgent.set(o.toLowerCase(),r),this.agentToUsername.set(r,o.toLowerCase()),this.log(`Agent "${r}" -> GitLab user @${o}`))}for(let i of this.config.agentMappings||[]){for(let r of i.gitlabUsernames)this.botUsernames.add(r),(!this.usernameToAgent.has(r.toLowerCase())||i.node)&&this.usernameToAgent.set(r.toLowerCase(),i.agentId);!this.agentToUsername.has(i.agentId)&&i.gitlabUsernames.length>0&&this.agentToUsername.set(i.agentId,i.gitlabUsernames[0].toLowerCase())}let n=new Set((this.config.agentMappings??[]).map(i=>i.agentId)),s=[];for(let i of this.config.knownAgentIds??[]){if(n.has(i))continue;let r=[i,`noqta-${i}`];for(let o of r)this.botUsernames.add(o),this.usernameToAgent.has(o.toLowerCase())||this.usernameToAgent.set(o.toLowerCase(),i);this.agentToUsername.has(i)||this.agentToUsername.set(i,i.toLowerCase()),s.push(i)}this.log(`Bot users (${this.botUsernames.size}): ${[...this.botUsernames].join(", ")}`),this.log(`Username->Agent map: ${[...this.usernameToAgent.entries()].map(([i,r])=>`@${i}->${r}`).join(", ")}`),s.length>0&&this.log(`GitLab auto-derived defaults for ${s.length} agent(s): ${s.join(", ")} (override by adding an agentMappings entry)`),this.server=Xs(async(i,r)=>{i.method==="POST"?await this.handleWebhook(i,r):(r.writeHead(200,{"Content-Type":"text/plain"}),r.end("GitLab webhook endpoint. POST events here."))}),this.server.on("error",i=>{i.code==="EADDRINUSE"?(this.log(`GitLab webhook port ${this.config.webhookPort} in use, retrying in 5s...`),setTimeout(()=>{this.server?.close(),this.server?.listen(this.config.webhookPort)},5e3)):this.log(`GitLab webhook server error: ${i.message}`)}),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(),i=t.join(":"),r=encodeURIComponent(i),o;switch(s){case"issue":o=`${this.config.host}/api/v4/projects/${r}/issues/${n}/notes`;break;case"merge_request":o=`${this.config.host}/api/v4/projects/${r}/merge_requests/${n}/notes`;break;default:return this.log(`Unsupported noteable type: ${s}`),""}let a=this.config.agentMappings?.find(g=>g.agentId===e.agentId),l=this.getAgentToken(e.agentId);if(!l&&a?.node&&this.sendNoteForwarder)try{let g=re(e.text,e.agentId||"unknown"),h=await this.sendNoteForwarder(a.node,i,s,n,e.agentId||"",g);return h&&this.sentNoteIds.add(h),h}catch(g){return this.log(`GitLab send forward to "${a.node}" failed: ${g.message} \u2014 skipping (would post as group bot)`),""}let d=l||this.config.token;z.webhook("gitlab","send",`agentId="${e.agentId}" token=${l?"per-agent":"GLOBAL("+this.botUsername+")"}`);try{let g=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":d},body:JSON.stringify({body:re(e.text,e.agentId||"unknown")})});if(!g.ok){let u=await g.text();return this.log(`GitLab API error: ${g.status} ${u}`),""}let h=await g.json(),p=String(h.id||"");return p&&this.sentNoteIds.add(p),p}catch(g){return this.log(`GitLab send error: ${g.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),i=s.object_kind||s.event_type||"unknown";switch(this.log(`Event: ${i} from ${s.project?.path_with_namespace||"unknown"}`),i){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: ${i}`),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,i=e.user,r=String(e.object_attributes.id),o=W(n);if(o){let k=n.match(/@(\w[\w.-]*)/g)?.map(T=>T.slice(1).replace(/[.]+$/,""))||[];if(!k.some(T=>{let x=this.usernameToAgent.get(T.toLowerCase());return x&&x!==o})){this.log(`AgentX comment from ${o}, no cross-agent mention, skipping (note ${r})`),t.writeHead(200),t.end("ok");return}this.log(`Bot-to-bot handoff: ${o} \u2192 ${k.join(", ")} (note ${r})`)}if(this.sentNoteIds.has(r)){this.sentNoteIds.delete(r),t.writeHead(200),t.end("ok");return}let a=n.match(/@(\w[\w.-]*)/g)?.map(k=>k.slice(1).replace(/[.]+$/,""))||[];if(a.length===0){this.log(`No @mention in note ${r}, skipping`),t.writeHead(200),t.end("ok");return}if(this.isBotUser(i.username)&&!o){this.log(`Bot comment from ${i.username} without signature, skipping (note ${r})`),t.writeHead(200),t.end("ok");return}let l="",d="",g="";e.issue?(l="issue",d=String(e.issue.iid),g=e.issue.title):e.merge_request&&(l="merge_request",d=String(e.merge_request.iid),g=e.merge_request.title),z.webhook("gitlab","handleNote",`noteId=${r} mentions=[${a.join(",")}] user=${i.username}`);let h=this.resolveAgentFromMention(n);if(z.webhook("gitlab","resolve",`agentId=${h??"NONE"}`),!h){if(this.log(`[handleNote] @mentions in note ${r} are not agents (${a.join(", ")}), skipping`),E("gitlab")!=="off")try{ht(_(),{noteId:r,project:s,noteableType:l,noteableIid:d,mentions:a.map(k=>k.toLowerCase())},JSON.stringify(e),{agentId:null,outcome:"halted",reason:`unresolved-mentions: ${a.join(",")}`})}catch(k){this.log(`[ledger] gitlab note ${r} (no-resolve) record failed: ${k?.message??k}`)}t.writeHead(200),t.end("ok");return}let p=h,u=this.config.agentMappings?.find(k=>k.agentId===p),f=u?.token,m=u?.node;z.webhook("gitlab","token",`agent="${p}" mapping=${u?"found":"MISSING"} hasToken=${!!f} node=${m??"local"}`),this.reactToNote(s,l,d,e.object_attributes.id,f,m,p).catch(()=>{});let y=`${s}:${l}:${d}`,b=await this.getChannelMeta(y),w=tt(n),v=await this.downloadNoteImages(w,s,f||this.config.token),$;if(E("gitlab")!=="off")try{let k=ht(_(),{noteId:r,project:s,noteableType:l,noteableIid:d,mentions:a.map(S=>S.toLowerCase())},JSON.stringify(e),{agentId:p,outcome:"dispatched",reason:`mention:${a[0]}`});k.outcome==="dispatched"&&($={eventId:k.eventId,decidedBy:k.decidedBy})}catch(k){this.log(`[ledger] gitlab note ${r} record failed: ${k?.message??k}`)}let I={id:String(e.object_attributes.id),channel:"gitlab",accountId:"default",sender:{id:y,name:i.name,username:i.username},text:`[GitLab ${s} ${l} #${d}: ${g}]
|
|
79
|
-
${i.name} commented:
|
|
80
|
-
${w}`,timestamp:new Date,raw:e,resolvedAgent:p,preferNode:u?.node,channelMeta:b?{...b,issue:{type:l,iid:d,title:g}}:void 0,media:v,intentRef:$};this.handler(I).catch(k=>{this.log(`Error handling note: ${k.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,i=this.resolveAgent(s),r=this.isBotUser(e.user.username);r&&this.log(`Issue #${n.iid} authored by bot "${e.user.username}" \u2014 default dispatch suppressed (hooks still fire)`);let o,a=!1;if(this.hooks?.has("on:gitlab-issue"))try{let p=await this.hooks.execute("on:gitlab-issue",{event:"on:gitlab-issue",issueEvent:e,project:s,iid:n.iid,title:n.title,description:n.description||"",url:n.url,action:n.action,usernameToAgent:Object.fromEntries(this.usernameToAgent.entries()),agentMappings:this.config.agentMappings||[],defaultAgentId:i||null});p.blocked&&(a=!0);let u=p.modified?.dispatch;Array.isArray(u)&&u.length>0&&(o=u.filter(f=>f&&typeof f.agentId=="string"))}catch(p){this.log(`on:gitlab-issue hook error: ${p.message}`)}if(o&&o.length>0){let p=E("gitlab")!=="off",u=p?{entityKind:"issue",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url}:null,f=p?JSON.stringify(e):"";for(let m of o){let y=this.config.agentMappings?.find(k=>k.agentId===m.agentId),b=`${s}:issue:${n.iid}`,w=await this.getChannelMeta(b),v=`issue-hook-${n.iid}-${m.agentId}${m.assignee?`-${m.assignee}`:""}-${n.action}`,$;if(u)try{let k=Ie(_(),u,{agentId:m.agentId,trigger:"hook-dispatch"},f,{agentId:m.agentId,outcome:"dispatched",reason:m.preferNode?`hook (node:${m.preferNode})`:"hook"});k.outcome==="dispatched"&&($={eventId:k.eventId,decidedBy:k.decidedBy})}catch(k){this.log(`[ledger] gitlab issue #${n.iid} hook-dispatch ${m.agentId} record failed: ${k?.message??k}`)}let I={id:v,channel:"gitlab",accountId:"default",sender:{id:b,name:e.user.name,username:e.user.username},text:m.prompt||`[GitLab ${s} Issue #${n.iid} ${n.action}]: ${n.title}
|
|
81
|
-
${n.description?.slice(0,500)||""}
|
|
82
|
-
URL: ${n.url}`,timestamp:new Date,raw:e,resolvedAgent:m.agentId,preferNode:m.preferNode||y?.node,channelMeta:w?{...w,issue:{type:"issue",iid:String(n.iid),title:n.title}}:void 0,intentRef:$};this.log(`Issue #${n.iid} hook dispatch -> agent "${m.agentId}"${m.preferNode||y?.node?` (remote: ${m.preferNode||y?.node})`:""}`),this.handler(I).catch(k=>this.log(`Error handling hook dispatch: ${k.message}`))}t.writeHead(200),t.end("ok");return}if(a){if(this.log(`Issue #${n.iid}: on:gitlab-issue hook suppressed default dispatch`),E("gitlab")!=="off")try{In(_(),{entityKind:"issue",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url},"hook-blocked","gitlab:issue:hook",JSON.stringify(e),{agentId:null,outcome:"halted",reason:"on:gitlab-issue hook returned blocked:true"})}catch(p){this.log(`[ledger] gitlab issue #${n.iid} hook-blocked record failed: ${p?.message??p}`)}t.writeHead(200),t.end("ok");return}if(r){t.writeHead(200),t.end("ok");return}let l=this.computeIssueTargets(e,i);if(l.length===0){this.log(`Issue #${n.iid}: no agent target (no mention, no agent assignee, no default route)`),t.writeHead(200),t.end("ok");return}let d=E("gitlab")!=="off",g=d?{entityKind:"issue",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url}:null,h=d?JSON.stringify(e):"";for(let p of l){let u=`${s}:issue:${n.iid}:${p.agentId}:${n.action}:${p.trigger}`,f=this.isDispatchedRecently(u),m;if(g)try{let y=Ie(_(),g,p,h,f?{agentId:null,outcome:"deduped",reason:"isDispatchedRecently"}:{agentId:p.agentId,outcome:"dispatched"});y.outcome==="dispatched"&&(m={eventId:y.eventId,decidedBy:y.decidedBy})}catch(y){this.log(`[ledger] gitlab issue #${n.iid} target ${p.agentId} record failed: ${y?.message??y}`)}if(f)this.log(`Issue #${n.iid}: skip duplicate dispatch ${u}`);else{this.markDispatched(u);let y=this.config.agentMappings?.find(I=>I.agentId===p.agentId),b=`${s}:issue:${n.iid}`,w=await this.getChannelMeta(b),v=p.trigger==="assignee-added"?`[GitLab ${s} Issue #${n.iid} assigned to you: ${n.title}]
|
|
83
|
-
${n.description?.slice(0,1500)||""}
|
|
84
|
-
URL: ${n.url}
|
|
85
|
-
|
|
86
|
-
Please acknowledge this assignment in a comment, then start working on the issue.`:`[GitLab ${s} Issue #${n.iid} ${n.action}]: ${n.title}
|
|
87
|
-
${n.description?.slice(0,500)||""}
|
|
88
|
-
URL: ${n.url}`,$={id:`issue-${n.iid}-${n.action}-${p.agentId}-${p.trigger}`,channel:"gitlab",accountId:"default",sender:{id:b,name:e.user.name,username:e.user.username},text:v,timestamp:new Date,raw:e,resolvedAgent:p.agentId,preferNode:y?.node,channelMeta:w?{...w,issue:{type:"issue",iid:String(n.iid),title:n.title}}:void 0,intentRef:m};this.log(`Issue #${n.iid} -> agent "${p.agentId}" (trigger: ${p.trigger})`),this.handler($).catch(I=>this.log(`Error handling issue: ${I.message}`))}}t.writeHead(200),t.end("ok")}computeIssueTargets(e,t){let n=[],s=new Set,i=(d,g)=>{!d||s.has(d)||(s.add(d),n.push({agentId:d,trigger:g}))},o=(e.object_attributes.description||"").match(/@(\w[\w.-]*)/g)?.map(d=>d.slice(1).replace(/[.]+$/,"").toLowerCase())||[];for(let d of o)i(this.usernameToAgent.get(d),"mention");let a=new Set((e.changes?.assignees?.previous??[]).map(d=>d.username.toLowerCase())),l=(e.changes?.assignees?.current??[]).map(d=>d.username.toLowerCase());for(let d of l)a.has(d)||i(this.usernameToAgent.get(d),"assignee-added");if(n.length===0){let d=(e.assignees??[]).map(g=>g.username.toLowerCase());for(let g of d)i(this.usernameToAgent.get(g),"assignee-current")}return n.length===0&&i(t,"default-route"),n}isDispatchedRecently(e){let t=this.dispatchedTargets.get(e);return t?t<Date.now()?(this.dispatchedTargets.delete(e),!1):!0:!1}markDispatched(e){let t=Date.now();if(this.dispatchedTargets.set(e,t+this.DISPATCH_TTL_MS),this.dispatchedTargets.size>200)for(let[n,s]of this.dispatchedTargets)s<t&&this.dispatchedTargets.delete(n)}async handleMR(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}if(this.isBotUser(e.user.username)){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,i=this.resolveAgent(s),r=this.computeMRTargets(e,i);if(r.length===0){t.writeHead(200),t.end("ok");return}let o=E("gitlab")!=="off",a=o?{entityKind:"merge_request",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url}:null,l=o?JSON.stringify(e):"";for(let d of r){let g=`${s}:merge_request:${n.iid}:${d.agentId}:${n.action}:${d.trigger}`,h=this.isDispatchedRecently(g),p;if(a)try{let u=Ie(_(),a,d,l,h?{agentId:null,outcome:"deduped",reason:"isDispatchedRecently"}:{agentId:d.agentId,outcome:"dispatched"});u.outcome==="dispatched"&&(p={eventId:u.eventId,decidedBy:u.decidedBy})}catch(u){this.log(`[ledger] gitlab MR !${n.iid} target ${d.agentId} record failed: ${u?.message??u}`)}if(!h){this.markDispatched(g);let u=this.config.agentMappings?.find(v=>v.agentId===d.agentId),f=`${s}:merge_request:${n.iid}`,m=await this.getChannelMeta(f),b=d.trigger==="assignee-added"||d.trigger==="reviewer-added"?`[GitLab ${s} MR !${n.iid} ${d.trigger==="reviewer-added"?"review requested":"assigned to you"}: ${n.title}]
|
|
89
|
-
Branch: ${n.source_branch} -> ${n.target_branch}
|
|
90
|
-
${n.description?.slice(0,1500)||""}
|
|
91
|
-
URL: ${n.url}
|
|
92
|
-
|
|
93
|
-
Please acknowledge in a comment, then ${d.trigger==="reviewer-added"?"review this MR":"start working on it"}.`:`[GitLab ${s} MR !${n.iid} ${n.action}]: ${n.title}
|
|
94
|
-
Branch: ${n.source_branch} -> ${n.target_branch}
|
|
95
|
-
${n.description?.slice(0,500)||""}
|
|
96
|
-
URL: ${n.url}`,w={id:`mr-${n.iid}-${n.action}-${d.agentId}-${d.trigger}`,channel:"gitlab",accountId:"default",sender:{id:f,name:e.user.name,username:e.user.username},text:b,timestamp:new Date,raw:e,resolvedAgent:d.agentId,preferNode:u?.node,channelMeta:m?{...m,issue:{type:"merge_request",iid:String(n.iid),title:n.title}}:void 0,intentRef:p};this.log(`MR !${n.iid} -> agent "${d.agentId}" (trigger: ${d.trigger})`),this.handler(w).catch(v=>this.log(`Error handling MR: ${v.message}`))}}t.writeHead(200),t.end("ok")}computeMRTargets(e,t){let n=[],s=new Set,i=(d,g)=>{!d||s.has(d)||(s.add(d),n.push({agentId:d,trigger:g}))},o=(e.object_attributes.description||"").match(/@(\w[\w.-]*)/g)?.map(d=>d.slice(1).replace(/[.]+$/,"").toLowerCase())||[];for(let d of o)i(this.usernameToAgent.get(d),"mention");let a=new Set((e.changes?.assignees?.previous??[]).map(d=>d.username.toLowerCase()));for(let d of e.changes?.assignees?.current??[]){let g=d.username.toLowerCase();a.has(g)||i(this.usernameToAgent.get(g),"assignee-added")}let l=new Set((e.changes?.reviewers?.previous??[]).map(d=>d.username.toLowerCase()));for(let d of e.changes?.reviewers?.current??[]){let g=d.username.toLowerCase();l.has(g)||i(this.usernameToAgent.get(g),"reviewer-added")}if(n.length===0){for(let d of e.assignees??[])i(this.usernameToAgent.get(d.username.toLowerCase()),"assignee-current");for(let d of e.reviewers??[])i(this.usernameToAgent.get(d.username.toLowerCase()),"reviewer-current")}return n.length===0&&i(t,"default-route"),n}async handlePipeline(e,t){let n=e.object_attributes,s=e.project.path_with_namespace;if(["success","failed","canceled"].includes(n.status)&&this.hooks?.has("on:gitlab-pipeline")&&this.hooks.execute("on:gitlab-pipeline",{event:"on:gitlab-pipeline",pipelineId:n.id,status:n.status,ref:n.ref,duration:n.duration,project:s,projectId:e.project?.id,raw:e}).catch(a=>this.log(`on:gitlab-pipeline hook error: ${a.message}`)),!this.handler||n.status!=="failed"){t.writeHead(200),t.end("ok");return}let r=this.resolveAgent(s),o={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}
|
|
97
|
-
Ref: ${n.ref}
|
|
98
|
-
Duration: ${n.duration}s
|
|
99
|
-
Please investigate the failure.`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(o).catch(a=>this.log(`Error handling pipeline: ${a.message}`)),t.writeHead(200),t.end("ok")}resolveAgentFromMention(e){let t=e.match(/@(\w[\w.-]*)/g)?.map(n=>n.slice(1).replace(/[.]+$/,"").toLowerCase())||[];if(t.length!==0)for(let n of t){let s=this.usernameToAgent.get(n);if(s)return this.log(`Mention @${n} -> agent "${s}" (resolved from token)`),s}}resolveAgent(e){for(let t of this.config.routes)if(t.project===e||t.project==="*")return t.agent}async getChannelMeta(e){let t=e.split(":"),n=t[0],s=t[1],i=t[2],r=[];for(let a of this.config.routes)(a.project===n||a.project==="*")&&r.push({id:a.agent,name:a.agent});for(let a of this.config.agentMappings||[])r.some(l=>l.id===a.agentId)||r.push({id:a.agentId,name:a.agentId});return{channel:"gitlab",agents:r,project:n,issue:s&&i?{type:s,iid:i,title:""}:void 0,facts:["This is a GitLab webhook event \u2014 respond as a GitLab comment","Do NOT use Telegram handles or delegate to other agents","Do NOT mention other agents by name \u2014 you are the only agent responding to this event","Stay in your role \u2014 do not act as or speak for other agents"]}}isBotUser(e){return this.botUsernames.has(e)}async seedHistory(e,t){let n=e.split(":");if(n.length<3)return[];let s=n.pop(),i=n.pop(),r=n.join(":"),o=encodeURIComponent(r),a;if(i==="issue")a=`${this.config.host}/api/v4/projects/${o}/issues/${s}/notes?sort=asc&per_page=${Math.max(20,Math.min(100,t.maxMessages))}`;else if(i==="merge_request")a=`${this.config.host}/api/v4/projects/${o}/merge_requests/${s}/notes?sort=asc&per_page=${Math.max(20,Math.min(100,t.maxMessages))}`;else return[];let l=this.config.token;if(!l)return[];let d;try{let u=await fetch(a,{headers:{"PRIVATE-TOKEN":l}});if(!u.ok)return[];d=await u.json()}catch{return[]}let g=[],h=0,p=t.sinceISO?new Date(t.sinceISO).getTime():0;for(let u of d){if(u.system||p&&new Date(u.created_at).getTime()<p)continue;let f=W(u.body),m=tt(u.body);if(g.push({role:f?"agent":"user",name:u.author?.name||u.author?.username||(f??"user"),content:m,timestamp:u.created_at,externalId:String(u.id)}),h+=m.length,g.length>=t.maxMessages||h>=t.maxChars)break}return g}getAgentToken(e){return!e||!this.config.agentMappings?.length?void 0:this.config.agentMappings.find(n=>n.agentId===e)?.token}getTokenForMentionedAgent(e){if(!this.config.agentMappings?.length)return;let t=e.match(/@(\w[\w.-]*)/g)?.map(n=>n.slice(1).replace(/[.]+$/,"").toLowerCase())||[];for(let n of this.config.agentMappings)if(n.token&&n.gitlabUsernames.some(s=>t.includes(s.toLowerCase())))return n.token}async reactToNote(e,t,n,s,i,r,o){if(!i&&r&&o&&this.reactForwarder){this.log(`Forwarding \u{1F440} reaction for "${o}" to mesh peer "${r}"`),await this.reactForwarder(r,e,t,n,s,o);return}if(!i){this.log(`No token for reaction on note ${s} (agent "${o}") \u2014 skipping`);return}let a=encodeURIComponent(e),l;switch(t){case"issue":l=`${this.config.host}/api/v4/projects/${a}/issues/${n}/notes/${s}/award_emoji`;break;case"merge_request":l=`${this.config.host}/api/v4/projects/${a}/merge_requests/${n}/notes/${s}/award_emoji`;break;default:return}try{let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":i},body:JSON.stringify({name:"eyes"})});d.ok||this.log(`Reaction failed on note ${s}: ${d.status}`)}catch(d){this.log(`Failed to react to note ${s}: ${d.message}`)}}async logTimeSpent(e,t,n){let s=e.split(":");if(s.length<3)return;let i=s.pop(),r=s.pop(),o=s.join(":"),a=Math.max(60,Math.round(t/1e3)),l=Math.floor(a/3600),d=Math.ceil(a%3600/60),g=l>0?`${l}h${d>0?` ${d}m`:""}`:`${d}m`,h=encodeURIComponent(o),p=r==="merge_request"?"merge_requests":"issues",u=`${this.config.host}/api/v4/projects/${h}/${p}/${i}/add_spent_time`,f=this.config.agentMappings?.find(b=>b.agentId===n),m=this.getAgentToken(n);if(!m&&f?.node&&this.logTimeForwarder){try{await this.logTimeForwarder(f.node,o,r,i,n||"",t),this.log(`Time logged (via peer "${f.node}"): ${g} on ${o} ${p}/${i} (${n})`)}catch(b){this.log(`Time log forward to "${f.node}" failed: ${b.message} \u2014 skipping (would log as group bot)`)}return}let y=m||this.config.token;try{let b=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":y},body:JSON.stringify({duration:g})});if(b.ok)this.log(`Time logged: ${g} on ${o} ${r} #${i} (${n||"global"})`);else{let w=await b.text();this.log(`Time log failed (${b.status}): ${w.slice(0,100)}`)}}catch(b){this.log(`Time log error: ${b.message}`)}}async createIssue(e){let{project:t,title:n,description:s="",labels:i=[],assignees:r=[],agentId:o}=e,a=this.config.agentMappings?.find(u=>u.agentId===o),l=this.getAgentToken(o);if(!l&&a?.node&&this.createIssueForwarder)try{let u=await this.createIssueForwarder(a.node,t,n,s,i,r,o||"");return u&&this.log(`Issue created (via peer "${a.node}") #${u.iid} on ${t}`),u}catch(u){return this.log(`Issue-create forward to "${a.node}" failed: ${u.message}`),null}let d=l||this.config.token;if(!d)return this.log(`Issue-create failed: no token available for agent "${o||"global"}"`),null;let g=encodeURIComponent(t),h=`${this.config.host}/api/v4/projects/${g}/issues`,p=new URLSearchParams;p.set("title",n),s&&p.set("description",s),i.length>0&&p.set("labels",i.join(","));for(let u of r)try{let f=await fetch(`${this.config.host}/api/v4/users?username=${encodeURIComponent(u)}`,{headers:{"PRIVATE-TOKEN":d}});if(f.ok){let m=await f.json();m[0]?.id&&p.append("assignee_ids[]",String(m[0].id))}}catch(f){this.log(`Issue-create: failed to resolve assignee "${u}": ${f.message}`)}try{let u=await fetch(h,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","PRIVATE-TOKEN":d},body:p.toString()});if(!u.ok){let m=await u.text();return this.log(`Issue-create failed (${u.status}): ${m.slice(0,200)}`),null}let f=await u.json();return this.log(`Issue created #${f.iid} on ${t} (${o||"global"})`),{iid:f.iid,url:f.web_url}}catch(u){return this.log(`Issue-create error: ${u.message}`),null}}async setLabels(e){let{project:t,kind:n="issue",iid:s,add:i=[],remove:r=[],agentId:o}=e,a=this.config.agentMappings?.find(u=>u.agentId===o),l=this.getAgentToken(o);if(!l&&a?.node&&this.setLabelsForwarder)try{let u=await this.setLabelsForwarder(a.node,t,n,s,i,r,o||"");return u&&this.log(`Labels updated (via peer "${a.node}") on ${t} ${n}/${s}`),u}catch(u){return this.log(`setLabels forward to "${a.node}" failed: ${u.message}`),null}let d=l||this.config.token;if(!d)return this.log(`setLabels failed: no token for "${o||"global"}"`),null;let g=n==="merge_request"?"merge_requests":"issues",h=`${this.config.host}/api/v4/projects/${encodeURIComponent(t)}/${g}/${s}`,p=new URLSearchParams;i.length&&p.set("add_labels",i.join(",")),r.length&&p.set("remove_labels",r.join(","));try{let u=await fetch(h,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded","PRIVATE-TOKEN":d},body:p.toString()});if(!u.ok){let m=await u.text();return this.log(`setLabels failed (${u.status}): ${m.slice(0,200)}`),null}return(await u.json()).labels??[]}catch(u){return this.log(`setLabels error: ${u.message}`),null}}async getLabels(e){let{project:t,kind:n="issue",iid:s}=e;if(!this.config.token)return null;let i=n==="merge_request"?"merge_requests":"issues",r=`${this.config.host}/api/v4/projects/${encodeURIComponent(t)}/${i}/${s}`;try{let o=await fetch(r,{headers:{"PRIVATE-TOKEN":this.config.token}});return o.ok?(await o.json()).labels??[]:(this.log(`getLabels failed (${o.status})`),null)}catch(o){return this.log(`getLabels error: ${o.message}`),null}}async downloadNoteImages(e,t,n){let s=/!\[[^\]]*\]\(([^)]+\.(?:png|jpg|jpeg|gif|webp|svg))\)/gi,i=[...e.matchAll(s)];if(i.length===0)return;let r=i[0][1],o;if(r.startsWith("http"))o=r;else{let a=encodeURIComponent(t);o=`${this.config.host}/${t}${r}`}try{let a=await fetch(o,{headers:{"PRIVATE-TOKEN":n}});if(!a.ok){this.log(`Failed to download image: ${a.status} ${o}`);return}let l=Buffer.from(await a.arrayBuffer()),d=a.headers.get("content-type")||"image/png",g=d.split("/")[1]?.split(";")[0]||"png",{mkdirSync:h,writeFileSync:p}=await import("fs"),{resolve:u}=await import("path"),{randomUUID:f}=await import("crypto"),m=u(process.cwd(),".agentx/media/gitlab");h(m,{recursive:!0});let y=`${f().slice(0,8)}.${g}`,b=u(m,y);return p(b,l),this.log(`Downloaded GitLab image: ${b} (${l.length} bytes)`),{path:b,type:d,fileName:r.split("/").pop()||y}}catch(a){this.log(`Image download error: ${a.message}`);return}}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({}))})}};import{createHmac as qs,createSign as Ks}from"crypto";import{readFileSync as Tn}from"fs";var xe=class{name="github";config;handler;globalToken;botUsernames=new Set;sentCommentIds=new Set;log;sendCommentForwarder;appPrivateKey;installationTokens=new Map;constructor(e,t=console.error.bind(console,"[github]")){this.config=e,this.log=t}setSendCommentForwarder(e){this.sendCommentForwarder=e}onMessage(e){this.handler=e}async start(){if((this.config.clientId||this.config.appId)&&this.config.privateKeyFile)try{this.appPrivateKey=Tn(this.config.privateKeyFile,"utf-8").trim(),this.log(`GitHub App mode: issuer=${this.config.clientId||this.config.appId}`);let t=this.generateAppJWT(),n=await fetch("https://api.github.com/app",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"}});if(n.ok){let s=await n.json();this.log(`GitHub App: "${s.name}" (slug: ${s.slug})`),s.slug&&this.botUsernames.add(`${s.slug}[bot]`.toLowerCase())}else this.log(`GitHub App auth failed: ${n.status} ${await n.text().catch(()=>"")}`)}catch(t){this.log(`Failed to load GitHub App key: ${t.message}`)}if(!this.appPrivateKey&&(this.globalToken=this.resolveToken(this.config.token,this.config.tokenFile),this.globalToken))try{let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${this.globalToken}`,"User-Agent":"AgentX"}});if(t.ok){let n=await t.json();this.log(`GitHub PAT fallback: ${n.login}`)}}catch(t){this.log(`Failed to resolve GitHub user: ${t.message}`)}for(let t of this.config.agentMappings||[])for(let n of t.githubUsernames)this.botUsernames.add(n.toLowerCase());this.log(`GitHub channel started (${this.config.routes.length} routes, ${this.botUsernames.size} bot users)`)}async stop(){}async handleWebhook(e,t,n){if(this.config.webhookSecret){let r=e["x-hub-signature-256"],o=n||JSON.stringify(t);if(!this.verifySignature(o,r)){this.log("GitHub webhook signature verification failed");return}}let s=e["x-github-event"]||"unknown",i=t.repository?.full_name||"unknown";switch(this.log(`GitHub event: ${s} from ${i}`),s){case"issue_comment":await this.handleIssueComment(t);break;case"pull_request":await this.handlePR(t);break;case"pull_request_review":await this.handlePRReview(t);break;case"pull_request_review_comment":await this.handlePRReviewComment(t);break;case"issues":await this.handleIssue(t);break;case"push":await this.handlePush(t);break;case"ping":this.log("GitHub webhook ping received");break;default:this.log(`Unhandled GitHub event: ${s}`)}}async send(e){let t=e.chatId.split(":");if(t.length<3)return this.log(`Invalid chatId for GitHub reply: ${e.chatId}`),"";let n=parseInt(t.pop(),10),s=t.pop(),i=t.join(":"),r=this.config.agentMappings?.find(u=>u.agentId===e.agentId),o=this.getAgentToken(e.agentId),a=e.agentId||"unknown",d=!!this.appPrivateKey?"":`> \u{1F916} **${a}** (via AgentX)
|
|
100
|
-
|
|
101
|
-
`,g=re(`${d}${e.text}`,a),h=o||await this.getTokenForRepo(i);if(!h&&r?.node&&this.sendCommentForwarder)try{let u=await this.sendCommentForwarder(r.node,i,n,a,g);if(u)return this.sentCommentIds.add(u),u;this.log(`GitHub send forward to "${r.node}" returned empty \u2014 no local token available either`)}catch(u){this.log(`GitHub send forward to "${r.node}" failed: ${u.message}`)}if(!h)return this.log(`No GitHub token available for posting comment (agent: ${e.agentId})`),"";let p=`https://api.github.com/repos/${i}/issues/${n}/comments`;try{let u=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"},body:JSON.stringify({body:g})});if(!u.ok){let y=await u.text();return this.log(`GitHub API error: ${u.status} ${y.slice(0,200)}`),""}let f=await u.json(),m=String(f.id||"");return m&&this.sentCommentIds.add(m),m}catch(u){return this.log(`GitHub send error: ${u.message}`),""}}async react(e,t,n){let s=e.split(":");if(s.length<3)return;s.pop(),s.pop();let i=s.join(":"),r=await this.getTokenForRepo(i);if(!(!r||!t))try{await fetch(`https://api.github.com/repos/${i}/issues/comments/${t}/reactions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"},body:JSON.stringify({content:"eyes"})})}catch{}}async getChannelMeta(e){let t=e.split(":"),n=t[0]+(t.length>1,""),s=t.length>=2?t[t.length-2]:void 0,i=t.length>=3?t[t.length-1]:void 0,r=t.slice(0,-2),o=r.length>0?r.join(":"):t[0],a=[];for(let l of this.config.routes)(l.repo===o||l.repo==="*")&&a.push({id:l.agent,name:l.agent});return{channel:"github",agents:a,project:o,issue:s&&i?{type:s,iid:i,title:""}:void 0,facts:["This is a GitHub webhook event \u2014 respond as a GitHub comment","Use `gh` CLI or the GitHub API to interact with the repository","Do NOT use Telegram handles or delegate to other agents"]}}async handleIssueComment(e){if(!this.handler){this.log("[github] issue_comment dropped: no handler attached");return}if(e.action!=="created"){this.log(`[github] issue_comment skipped: action="${e.action}" (only "created" routes)`);return}let t=e.comment,n=e.repository.full_name,s=t.user,i=W(t.body);if(i){this.log(`AgentX comment from ${i}, skipping (comment ${t.id})`);return}if(this.isBotUser(s.login)){this.log(`Bot user ${s.login}, skipping (comment ${t.id})`);return}let r=String(t.id);if(this.sentCommentIds.has(r)){this.log(`[github] echo skip: comment ${r} matched our own post`),this.sentCommentIds.delete(r);return}let o=!!e.issue.pull_request,l=`${n}:${o?"pull":"issue"}:${e.issue.number}`,d=this.resolveAgent(n),g=d?this.config.agentMappings?.find(u=>u.agentId===d):void 0,h=await this.getChannelMeta(l),p={id:r,channel:"github",accountId:"default",sender:{id:l,name:s.login,username:s.login},text:`[GitHub ${o?"PR":"Issue"} #${e.issue.number}: ${e.issue.title}]
|
|
102
|
-
${s.login} commented:
|
|
103
|
-
${t.body}`,timestamp:new Date,raw:e,resolvedAgent:d,preferNode:g?.node,channelMeta:h};this.reactToComment(n,t.id).catch(()=>{}),this.handler(p).catch(u=>this.log(`Error handling issue_comment: ${u.message}`))}async handlePR(e){if(!this.handler)return;let t=e.pull_request,n=e.repository.full_name;if(this.isBotUser(t.user.login)||!["opened","reopened","ready_for_review"].includes(e.action))return;let i=`${n}:pull:${t.number}`,r=this.resolveAgent(n),o=r?this.config.agentMappings?.find(d=>d.agentId===r):void 0,a=await this.getChannelMeta(i),l={id:`pr-${n}-${t.number}`,channel:"github",accountId:"default",sender:{id:i,name:t.user.login,username:t.user.login},text:`[GitHub PR #${t.number} ${e.action}]: ${t.title}
|
|
104
|
-
Branch: ${t.head.ref} -> ${t.base.ref}
|
|
105
|
-
${t.body?.slice(0,500)||""}
|
|
106
|
-
URL: ${t.html_url}`,timestamp:new Date,raw:e,resolvedAgent:r,preferNode:o?.node,channelMeta:a};this.handler(l).catch(d=>this.log(`Error handling PR: ${d.message}`))}async handlePRReview(e){if(!this.handler||e.action!=="submitted")return;let t=e.review,n=e.repository.full_name;if(this.isBotUser(t.user.login)||t.state==="commented"&&!t.body)return;let s=`${n}:pull:${e.pull_request.number}`,i=this.resolveAgent(n),r=i?this.config.agentMappings?.find(a=>a.agentId===i):void 0,o={id:`review-${t.id}`,channel:"github",accountId:"default",sender:{id:s,name:t.user.login,username:t.user.login},text:`[GitHub PR #${e.pull_request.number} Review (${t.state})]: ${e.pull_request.title}
|
|
107
|
-
${t.user.login} reviewed:
|
|
108
|
-
${t.body||"(no body)"}`,timestamp:new Date,raw:e,resolvedAgent:i,preferNode:r?.node};this.handler(o).catch(a=>this.log(`Error handling PR review: ${a.message}`))}async handlePRReviewComment(e){if(!this.handler||e.action!=="created")return;let t=e.comment,n=e.repository.full_name;if(this.isBotUser(t.user.login)||W(t.body))return;let s=`${n}:pull:${e.pull_request.number}`,i=this.resolveAgent(n),r=i?this.config.agentMappings?.find(a=>a.agentId===i):void 0,o={id:`review-comment-${t.id}`,channel:"github",accountId:"default",sender:{id:s,name:t.user.login,username:t.user.login},text:`[GitHub PR #${e.pull_request.number} Review Comment]: ${e.pull_request.title}
|
|
109
|
-
${t.user.login} commented on ${t.path}:${t.line}:
|
|
110
|
-
${t.body}`,timestamp:new Date,raw:e,resolvedAgent:i,preferNode:r?.node};this.handler(o).catch(a=>this.log(`Error handling PR review comment: ${a.message}`))}async handleIssue(e){if(!this.handler)return;let t=e.issue,n=e.repository.full_name;if(this.isBotUser(t.user.login)||!["opened","assigned","reopened"].includes(e.action))return;let i=`${n}:issue:${t.number}`,r=this.resolveAgent(n),o=r?this.config.agentMappings?.find(l=>l.agentId===r):void 0,a={id:`issue-${n}-${t.number}`,channel:"github",accountId:"default",sender:{id:i,name:t.user.login,username:t.user.login},text:`[GitHub Issue #${t.number} ${e.action}]: ${t.title}
|
|
111
|
-
${t.body?.slice(0,500)||""}
|
|
112
|
-
URL: ${t.html_url}`,timestamp:new Date,raw:e,resolvedAgent:r,preferNode:o?.node};this.handler(a).catch(l=>this.log(`Error handling issue: ${l.message}`))}async handlePush(e){if(!this.handler)return;let t=e.repository.full_name,n=e.ref,s=e.commits||[];if(s.length===0)return;let i=this.resolveAgent(t),r=i?this.config.agentMappings?.find(l=>l.agentId===i):void 0,o=s.slice(0,5).map(l=>` - ${l.message.split(`
|
|
113
|
-
`)[0]} (${l.author?.name||l.author?.username||""})`).join(`
|
|
114
|
-
`),a={id:`push-${s[0]?.id?.slice(0,8)||Date.now()}`,channel:"github",accountId:"default",sender:{id:`${t}:push:${n}`,name:e.pusher.name,username:e.pusher.name},text:`[GitHub Push] ${t} ref:${n}
|
|
115
|
-
${s.length} commit(s):
|
|
116
|
-
${o}`,timestamp:new Date,raw:e,resolvedAgent:i,preferNode:r?.node};this.handler(a).catch(l=>this.log(`Error handling push: ${l.message}`))}resolveAgent(e){for(let t of this.config.routes)if(t.repo===e||t.repo==="*")return t.agent}isBotUser(e){return this.botUsernames.has(e.toLowerCase())}getAgentToken(e){if(!e||!this.config.agentMappings?.length)return;let t=this.config.agentMappings.find(n=>n.agentId===e);if(t)return this.resolveToken(t.token,t.tokenFile)}resolveToken(e,t){if(e)return e;if(t)try{return Tn(t,"utf-8").trim().split(`
|
|
117
|
-
`)[0].trim()}catch(n){this.log(`Failed to read token file ${t}: ${n.message}`)}}verifySignature(e,t){if(!t||!this.config.webhookSecret)return!1;let n="sha256="+qs("sha256",this.config.webhookSecret).update(e).digest("hex");return t===n}async reactToComment(e,t){let n=await this.getTokenForRepo(e);if(n)try{await fetch(`https://api.github.com/repos/${e}/issues/comments/${t}/reactions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"},body:JSON.stringify({content:"eyes"})})}catch{}}async getTokenForRepo(e){if(this.appPrivateKey&&this.config.appId&&e){let t=await this.getInstallationToken(e);if(t)return t}return this.globalToken}generateAppJWT(){let e=Math.floor(Date.now()/1e3),t={iat:e-60,exp:e+600,iss:this.config.clientId||String(this.config.appId)},n=Buffer.from(JSON.stringify({alg:"RS256",typ:"JWT"})).toString("base64url"),s=Buffer.from(JSON.stringify(t)).toString("base64url"),i=`${n}.${s}`,r=Ks("RSA-SHA256");r.update(i);let o=r.sign(this.appPrivateKey,"base64url");return`${i}.${o}`}async getInstallationToken(e){let t=this.installationTokens.get(e);if(t&&t.expiresAt>Date.now()+6e4)return t.token;try{let n=this.generateAppJWT(),s=await fetch(`https://api.github.com/repos/${e}/installation`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"}});if(!s.ok){this.log(`GitHub App not installed on ${e}: ${s.status}`);return}let i=await s.json(),r=await fetch(`https://api.github.com/app/installations/${i.id}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"}});if(!r.ok){this.log(`Failed to get installation token for ${e}: ${r.status}`);return}let o=await r.json(),a=new Date(o.expires_at).getTime();return this.installationTokens.set(e,{token:o.token,expiresAt:a}),this.log(`Got installation token for ${e} (expires: ${o.expires_at})`),o.token}catch(n){this.log(`Installation token error for ${e}: ${n.message}`);return}}};function J(c){return c.toLowerCase().replace(/[^a-z0-9]/g,"")}var Ae=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,t=[],n=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(t.map(J)),this.log=n,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,t){return`${e}|${J(t)}`}cleanupExpired(){let e=Date.now();for(let[t,n]of this.pending){let s=n.filter(i=>i.expiresAt>e);s.length===0?this.pending.delete(t):s.length!==n.length&&this.pending.set(t,s)}for(let[t,n]of this.recentRings)n<=e&&this.recentRings.delete(t)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,t,n){return this.addSubscriber(e,t,{kind:"sse",res:n})}subscribeInternal(e,t,n){return this.addSubscriber(e,t,{kind:"callback",deliver:n})}addSubscriber(e,t,n){let s={callId:e,recipient:t,sink:n};this.subs.add(s);let i=n.kind==="sse"?"sse":"internal";this.log(`subscribe[${i}] call=${e} as=${t} (${this.subs.size} total)`);let r=this.pendingKey(e,t),o=this.pending.get(r);if(o&&o.length){let a=Date.now(),l=o.filter(d=>d.expiresAt>a);for(let{signal:d}of l)this.deliverTo(s,d);this.pending.delete(r),l.length&&this.log(`flushed ${l.length} buffered signal(s) to new subscriber call=${e} as=${t}`)}return()=>{this.subs.delete(s),this.log(`unsubscribe[${i}] call=${e} as=${t} (${this.subs.size} remaining)`)}}deliverTo(e,t){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
|
|
118
|
-
data: ${JSON.stringify(t)}
|
|
119
|
-
|
|
120
|
-
`):e.sink.deliver(t),!0}catch{return!1}}async handleOutgoing(e){let t=J(e.to);if(t===J(this.localName)||this.hasSubscriberFor(e.callId,t))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let s=await this.forwarder(e.to,e);return s?{ok:s}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,t){for(let n of this.subs)if(n.callId===e&&J(n.recipient)===t)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(J(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let n=Date.now(),s=this.recentRings.get(e.callId);if(s&&s>n)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,n+3e5),this.ringHandler)try{this.ringHandler(e)}catch(i){this.log(`ringHandler threw: ${i.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let n=this.pendingKey(e.callId,e.to),s=this.pending.get(n)||[];s.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(n,s),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${s.length} pending)`)}return{ok:!0}}fanOut(e){let t=0,n=J(e.to);for(let s of this.subs)s.callId===e.callId&&J(s.recipient)===n&&(this.deliverTo(s,e)?t++:this.subs.delete(s));return t}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};var xn=`<!doctype html>
|
|
121
|
-
<html lang="en">
|
|
122
|
-
<head>
|
|
123
|
-
<meta charset="utf-8">
|
|
124
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
125
|
-
<title>AgentX Call</title>
|
|
126
|
-
<style>
|
|
127
|
-
:root { color-scheme: dark; }
|
|
128
|
-
body { margin: 0; font: 14px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #0e1116; color: #e6edf3; }
|
|
129
|
-
header { padding: 10px 14px; border-bottom: 1px solid #21262d; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
|
130
|
-
header h1 { font-size: 15px; margin: 0; font-weight: 600; }
|
|
131
|
-
header .sp { flex: 1; }
|
|
132
|
-
main { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 8px; }
|
|
133
|
-
video { width: 100%; aspect-ratio: 16 / 9; background: #161b22; border-radius: 6px; object-fit: cover; }
|
|
134
|
-
.tile { position: relative; }
|
|
135
|
-
.tile .label { position: absolute; top: 6px; left: 8px; font-size: 11px; background: rgba(0,0,0,.55); padding: 2px 6px; border-radius: 3px; }
|
|
136
|
-
form { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
|
137
|
-
input, select, button { background: #21262d; color: #e6edf3; border: 1px solid #30363d; border-radius: 4px; padding: 6px 10px; font: inherit; }
|
|
138
|
-
button { cursor: pointer; }
|
|
139
|
-
button:hover { background: #30363d; }
|
|
140
|
-
button.primary { background: #238636; border-color: #2ea043; }
|
|
141
|
-
button.primary:hover { background: #2ea043; }
|
|
142
|
-
button.danger { background: #da3633; border-color: #f85149; }
|
|
143
|
-
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
144
|
-
#log { padding: 8px 14px; max-height: 160px; overflow: auto; font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; border-top: 1px solid #21262d; color: #8b949e; }
|
|
145
|
-
#log .err { color: #f85149; }
|
|
146
|
-
#log .ok { color: #56d364; }
|
|
147
|
-
.status { font-size: 12px; padding: 2px 8px; border-radius: 10px; background: #30363d; }
|
|
148
|
-
.status.ok { background: #1f6f3d; color: #aff5b4; }
|
|
149
|
-
.status.err { background: #6e2b2b; color: #ffabab; }
|
|
150
|
-
</style>
|
|
151
|
-
</head>
|
|
152
|
-
<body>
|
|
153
|
-
<header>
|
|
154
|
-
<h1>AgentX / P2P Call</h1>
|
|
155
|
-
<span id="selfName" class="status">\u2026</span>
|
|
156
|
-
<span class="sp"></span>
|
|
157
|
-
<form id="form">
|
|
158
|
-
<input id="to" placeholder="peer name" required autocomplete="off" />
|
|
159
|
-
<input id="callId" placeholder="call id" required autocomplete="off" />
|
|
160
|
-
<button type="submit" id="joinBtn" class="primary">Join</button>
|
|
161
|
-
<button type="button" id="hangupBtn" class="danger" disabled>Hang up</button>
|
|
162
|
-
</form>
|
|
163
|
-
</header>
|
|
164
|
-
<main>
|
|
165
|
-
<div class="tile"><video id="local" autoplay playsinline muted></video><span class="label">You</span></div>
|
|
166
|
-
<div class="tile"><video id="remote" autoplay playsinline></video><span class="label" id="remoteLabel">Remote</span></div>
|
|
167
|
-
</main>
|
|
168
|
-
<div id="log"></div>
|
|
169
|
-
|
|
170
|
-
<script>
|
|
171
|
-
(() => {
|
|
172
|
-
const $ = (id) => document.getElementById(id);
|
|
173
|
-
const log = (msg, cls) => {
|
|
174
|
-
const line = document.createElement("div");
|
|
175
|
-
if (cls) line.className = cls;
|
|
176
|
-
line.textContent = "[" + new Date().toLocaleTimeString() + "] " + msg;
|
|
177
|
-
$("log").appendChild(line);
|
|
178
|
-
$("log").scrollTop = $("log").scrollHeight;
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
const qs = new URLSearchParams(location.search);
|
|
182
|
-
if (qs.get("to")) $("to").value = qs.get("to");
|
|
183
|
-
$("callId").value = qs.get("callId") || Math.random().toString(36).slice(2, 10);
|
|
184
|
-
const botName = qs.get("bot") || null; // e.g. ?bot=atlas \u2192 invite server-side bot
|
|
185
|
-
|
|
186
|
-
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
187
|
-
|
|
188
|
-
// Multi-peer state. For a pair call there's one entry (the human). When a
|
|
189
|
-
// server-side bot joins, a second entry is added whose isPrimary is false
|
|
190
|
-
// so we don't overwrite the remote video with the bot's (silent) stream.
|
|
191
|
-
let state = null; // { es, localStream, cfg, primary, callId, peers: Map<name, {pc, isPrimary}> }
|
|
192
|
-
|
|
193
|
-
async function loadConfig() {
|
|
194
|
-
const r = await fetch("/webrtc/config");
|
|
195
|
-
if (!r.ok) {
|
|
196
|
-
log("webrtc signaling is not enabled on this daemon (" + r.status + ")", "err");
|
|
197
|
-
$("selfName").textContent = "disabled";
|
|
198
|
-
$("selfName").className = "status err";
|
|
199
|
-
$("joinBtn").disabled = true;
|
|
200
|
-
return null;
|
|
201
|
-
}
|
|
202
|
-
const cfg = await r.json();
|
|
203
|
-
$("selfName").textContent = cfg.localName;
|
|
204
|
-
$("selfName").className = "status ok";
|
|
205
|
-
return cfg;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
async function sendSignal(signal) {
|
|
209
|
-
const r = await fetch("/webrtc/signal/out", {
|
|
210
|
-
method: "POST",
|
|
211
|
-
headers: { "Content-Type": "application/json" },
|
|
212
|
-
body: JSON.stringify(signal),
|
|
213
|
-
});
|
|
214
|
-
if (!r.ok) log("send " + signal.kind + " -> " + signal.to + " failed: " + r.status, "err");
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/** Find an existing peer by name (normalized \u2014 handles MacBook-Local vs
|
|
218
|
-
* macbook-local spelling drift between the URL and the remote's node.name). */
|
|
219
|
-
function findPeerEntry(name) {
|
|
220
|
-
if (!state) return null;
|
|
221
|
-
const want = norm(name);
|
|
222
|
-
for (const [key, entry] of state.peers) {
|
|
223
|
-
if (norm(key) === want) return entry;
|
|
224
|
-
}
|
|
225
|
-
return null;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
/** Build an RTCPeerConnection for a specific remote peer. Primary peer
|
|
229
|
-
* drives the remote video tile; non-primary peers (bots) just receive. */
|
|
230
|
-
function createPeer(peerName, isPrimary) {
|
|
231
|
-
const pc = new RTCPeerConnection({ iceServers: state.cfg.iceServers });
|
|
232
|
-
for (const track of state.localStream.getTracks()) pc.addTrack(track, state.localStream);
|
|
233
|
-
pc.ontrack = (ev) => {
|
|
234
|
-
if (isPrimary) {
|
|
235
|
-
$("remote").srcObject = ev.streams[0];
|
|
236
|
-
$("remoteLabel").textContent = peerName;
|
|
237
|
-
}
|
|
238
|
-
log("track from " + peerName + (isPrimary ? " (primary)" : " (bot)"), "ok");
|
|
239
|
-
};
|
|
240
|
-
pc.onicecandidate = (ev) => {
|
|
241
|
-
if (!ev.candidate) return;
|
|
242
|
-
sendSignal({
|
|
243
|
-
kind: "ice",
|
|
244
|
-
callId: state.callId, from: state.cfg.localName, to: peerName,
|
|
245
|
-
candidate: {
|
|
246
|
-
candidate: ev.candidate.candidate,
|
|
247
|
-
sdpMid: ev.candidate.sdpMid,
|
|
248
|
-
sdpMLineIndex: ev.candidate.sdpMLineIndex,
|
|
249
|
-
usernameFragment: ev.candidate.usernameFragment,
|
|
250
|
-
},
|
|
251
|
-
});
|
|
252
|
-
};
|
|
253
|
-
pc.onconnectionstatechange = () => {
|
|
254
|
-
log("pc[" + peerName + "] state: " + pc.connectionState);
|
|
255
|
-
};
|
|
256
|
-
state.peers.set(peerName, { pc, isPrimary });
|
|
257
|
-
return pc;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
async function handleInboundSignal(sig) {
|
|
261
|
-
if (sig.callId !== state.callId) return;
|
|
262
|
-
if (sig.kind === "hangup") {
|
|
263
|
-
log("<- hangup from " + sig.from, "err");
|
|
264
|
-
teardown();
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
// Find by normalized name so URL-spelling vs node.name-spelling mismatches
|
|
268
|
-
// don't drop signals (same trick the broker uses for its fan-out).
|
|
269
|
-
let entry = findPeerEntry(sig.from);
|
|
270
|
-
if (!entry && sig.kind === "offer") {
|
|
271
|
-
// New peer offering \u2014 figure out if it's the primary human (matches the
|
|
272
|
-
// URL's 'to' after normalization) or an additional peer (bot). Only an
|
|
273
|
-
// offer can introduce a new peer; answer/ice without a PC is stale.
|
|
274
|
-
const isPrimary = norm(sig.from) === norm(state.primary);
|
|
275
|
-
log("new peer offering: " + sig.from + (isPrimary ? " (primary)" : " (additional)"));
|
|
276
|
-
createPeer(sig.from, isPrimary);
|
|
277
|
-
entry = findPeerEntry(sig.from);
|
|
278
|
-
}
|
|
279
|
-
if (!entry) {
|
|
280
|
-
log("signal from unknown peer " + sig.from + " kind=" + sig.kind + " (dropped)", "err");
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
const { pc } = entry;
|
|
284
|
-
try {
|
|
285
|
-
if (sig.kind === "offer") {
|
|
286
|
-
await pc.setRemoteDescription({ type: "offer", sdp: sig.sdp });
|
|
287
|
-
const ans = await pc.createAnswer();
|
|
288
|
-
await pc.setLocalDescription(ans);
|
|
289
|
-
await sendSignal({ kind: "answer", callId: state.callId, from: state.cfg.localName, to: sig.from, sdp: ans.sdp });
|
|
290
|
-
log("<- offer from " + sig.from + " \u2192 answered");
|
|
291
|
-
} else if (sig.kind === "answer") {
|
|
292
|
-
await pc.setRemoteDescription({ type: "answer", sdp: sig.sdp });
|
|
293
|
-
log("<- answer from " + sig.from);
|
|
294
|
-
} else if (sig.kind === "ice") {
|
|
295
|
-
await pc.addIceCandidate(sig.candidate);
|
|
296
|
-
}
|
|
297
|
-
} catch (err) {
|
|
298
|
-
log(sig.kind + " handling error from " + sig.from + ": " + err.message, "err");
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
async function join(e) {
|
|
303
|
-
e?.preventDefault();
|
|
304
|
-
const cfg = state?.cfg || await loadConfig();
|
|
305
|
-
if (!cfg) return;
|
|
306
|
-
|
|
307
|
-
const to = $("to").value.trim();
|
|
308
|
-
const callId = $("callId").value.trim();
|
|
309
|
-
if (!to || !callId) return;
|
|
310
|
-
|
|
311
|
-
log("joining call " + callId + " with peer=" + to + (botName ? " + bot=" + botName : ""));
|
|
312
|
-
|
|
313
|
-
let localStream;
|
|
314
|
-
try {
|
|
315
|
-
localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
|
|
316
|
-
} catch (err) {
|
|
317
|
-
log("getUserMedia failed: " + err.message, "err");
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
$("local").srcObject = localStream;
|
|
321
|
-
|
|
322
|
-
state = { cfg, localStream, callId, primary: to, peers: new Map(), es: null };
|
|
323
|
-
|
|
324
|
-
// Subscribe to inbound signals BEFORE sending any offer so we don't miss
|
|
325
|
-
// the answer or ICE candidates from the callee. The broker's 30s buffer
|
|
326
|
-
// also covers late subscribes.
|
|
327
|
-
const esUrl = "/webrtc/events?callId=" + encodeURIComponent(callId) + "&as=" + encodeURIComponent(cfg.localName);
|
|
328
|
-
const es = new EventSource(esUrl);
|
|
329
|
-
state.es = es;
|
|
330
|
-
es.addEventListener("signal", (evt) => {
|
|
331
|
-
let sig; try { sig = JSON.parse(evt.data); } catch { return; }
|
|
332
|
-
handleInboundSignal(sig);
|
|
333
|
-
});
|
|
334
|
-
es.addEventListener("ready", () => log("signaling SSE ready", "ok"));
|
|
335
|
-
es.onerror = () => log("signaling SSE error (will reconnect)", "err");
|
|
336
|
-
|
|
337
|
-
// Create the primary PC to the human peer.
|
|
338
|
-
const primaryPc = createPeer(to, /* isPrimary */ true);
|
|
339
|
-
|
|
340
|
-
// Deterministic caller role between us and the human peer. If we're
|
|
341
|
-
// smaller, we offer; otherwise we wait for the offer (handled in
|
|
342
|
-
// handleInboundSignal).
|
|
343
|
-
const isCaller = norm(cfg.localName) < norm(to);
|
|
344
|
-
log(isCaller ? "role: caller (will offer to " + to + ")" : "role: callee (waiting for offer from " + to + ")");
|
|
345
|
-
if (isCaller) {
|
|
346
|
-
await sendSignal({ kind: "ring", callId, from: cfg.localName, to });
|
|
347
|
-
try {
|
|
348
|
-
const offer = await primaryPc.createOffer();
|
|
349
|
-
await primaryPc.setLocalDescription(offer);
|
|
350
|
-
await sendSignal({ kind: "offer", callId, from: cfg.localName, to, sdp: offer.sdp });
|
|
351
|
-
log("-> offer sent to " + to, "ok");
|
|
352
|
-
} catch (err) {
|
|
353
|
-
log("offer failed: " + err.message, "err");
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// If a bot is requested, ask this daemon to spawn it. The bot will join
|
|
358
|
-
// as a separate peer; the existing signal handler creates its PC when
|
|
359
|
-
// its offer arrives.
|
|
360
|
-
if (botName) {
|
|
361
|
-
try {
|
|
362
|
-
const r = await fetch("/webrtc/bot/invite", {
|
|
363
|
-
method: "POST",
|
|
364
|
-
headers: { "Content-Type": "application/json" },
|
|
365
|
-
body: JSON.stringify({ callId, target: cfg.localName, agentId: botName }),
|
|
366
|
-
});
|
|
367
|
-
if (r.ok) log("bot '" + botName + "' invited", "ok");
|
|
368
|
-
else log("bot invite failed: " + r.status, "err");
|
|
369
|
-
} catch (err) {
|
|
370
|
-
log("bot invite error: " + err.message, "err");
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
$("joinBtn").disabled = true;
|
|
375
|
-
$("hangupBtn").disabled = false;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
function teardown() {
|
|
379
|
-
if (!state) return;
|
|
380
|
-
for (const { pc } of state.peers.values()) { try { pc.close(); } catch {} }
|
|
381
|
-
try { state.es.close(); } catch {}
|
|
382
|
-
try { state.localStream.getTracks().forEach(t => t.stop()); } catch {}
|
|
383
|
-
$("local").srcObject = null;
|
|
384
|
-
$("remote").srcObject = null;
|
|
385
|
-
$("joinBtn").disabled = false;
|
|
386
|
-
$("hangupBtn").disabled = true;
|
|
387
|
-
state = null;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
async function hangup() {
|
|
391
|
-
if (!state) return;
|
|
392
|
-
// Send hangup to every active peer (human + any bots).
|
|
393
|
-
for (const peerName of state.peers.keys()) {
|
|
394
|
-
try {
|
|
395
|
-
await sendSignal({ kind: "hangup", callId: state.callId, from: state.cfg.localName, to: peerName });
|
|
396
|
-
} catch { /* best effort */ }
|
|
397
|
-
}
|
|
398
|
-
log("-> hangup sent to " + state.peers.size + " peer(s)");
|
|
399
|
-
teardown();
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
$("form").addEventListener("submit", join);
|
|
403
|
-
$("hangupBtn").addEventListener("click", hangup);
|
|
404
|
-
loadConfig();
|
|
405
|
-
})();
|
|
406
|
-
</script>
|
|
407
|
-
</body>
|
|
408
|
-
</html>`;var te=null;async function Ys(){if(te)return te;let c;try{c=await import("@roamhq/wrtc")}catch(s){throw new Error(`WebRTC bot requires "@roamhq/wrtc" \u2014 install it on this node (\`pnpm add @roamhq/wrtc\`) or set channels.webrtc.bot.enabled=false. Original: ${s?.message??s}`)}let e=c.default??c,t=e.RTCPeerConnection,n=e.nonstandard?.RTCAudioSink;if(!t||!n)throw new Error("@roamhq/wrtc loaded but missing expected exports (RTCPeerConnection / nonstandard.RTCAudioSink)");return te={RTCPeerConnection:t,RTCAudioSink:n},te}var An=c=>c.toLowerCase().replace(/[^a-z0-9]/g,""),Ce=class{pc;sinks=new Set;unsubscribe;closed=!1;opts;constructor(e){this.opts=e}async start(){if(this.pc)throw new Error("WebRtcBot already started");let{broker:e,callId:t,botName:n,target:s,iceServers:i,log:r}=this.opts,{RTCPeerConnection:o}=await Ys();if(this.pc=new o({iceServers:i}),this.pc.ontrack=l=>{if(this.closed)return;let d=l.track;if(d.kind!=="audio"){r(`[bot:${n}] non-audio track received (kind=${d.kind}) \u2014 ignored in v1`);return}r(`[bot:${n}] audio track received from ${s}`),this.tapAudio(d)},this.pc.onicecandidate=l=>{!l.candidate||this.closed||this.send({kind:"ice",callId:t,from:n,to:s,candidate:{candidate:l.candidate.candidate,sdpMid:l.candidate.sdpMid,sdpMLineIndex:l.candidate.sdpMLineIndex,usernameFragment:l.candidate.usernameFragment}})},this.pc.onconnectionstatechange=()=>{let l=this.pc?.connectionState;r(`[bot:${n}] pc state: ${l}`),(l==="failed"||l==="disconnected"||l==="closed")&&this.close(`pc state ${l}`)},this.unsubscribe=e.subscribeInternal(t,n,l=>this.handleSignal(l)),await this.send({kind:"ring",callId:t,from:n,to:s}),An(n)<An(s)){let l=await this.pc.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!1});await this.pc.setLocalDescription(l),await this.send({kind:"offer",callId:t,from:n,to:s,sdp:l.sdp}),r(`[bot:${n}] role=caller, offer sent to ${s}`)}else r(`[bot:${n}] role=callee, waiting for offer from ${s}`)}async send(e){let t=await this.opts.broker.handleOutgoing(e);t.ok||this.opts.log(`[bot:${this.opts.botName}] send ${e.kind} -> ${e.to} failed: ${t.error}`)}async handleSignal(e){if(!(this.closed||!this.pc)&&e.callId===this.opts.callId)try{if(e.kind==="offer"){await this.pc.setRemoteDescription({type:"offer",sdp:e.sdp});let t=await this.pc.createAnswer();await this.pc.setLocalDescription(t),await this.send({kind:"answer",callId:this.opts.callId,from:this.opts.botName,to:e.from,sdp:t.sdp})}else e.kind==="answer"?await this.pc.setRemoteDescription({type:"answer",sdp:e.sdp}):e.kind==="ice"?await this.pc.addIceCandidate(e.candidate):e.kind==="hangup"&&this.close(`hangup from ${e.from}`)}catch(t){this.opts.log(`[bot:${this.opts.botName}] signal ${e.kind} from ${e.from} failed: ${t.message}`)}}tapAudio(e){if(!te)throw new Error("WebRtcBot.tapAudio called before loadWrtc \u2014 bug");let{RTCAudioSink:t}=te,n=new t(e);n.ondata=s=>{this.closed||this.opts.onAudioFrame({samples:s.samples,sampleRate:s.sampleRate,channelCount:s.channelCount,receivedAt:Date.now()})},this.sinks.add({stop:()=>{try{n.stop()}catch{}}})}close(e){if(!this.closed){this.closed=!0,this.opts.log(`[bot:${this.opts.botName}] closing (${e})`);for(let t of this.sinks)t.stop();this.sinks.clear();try{this.unsubscribe?.()}catch{}try{this.pc?.close()}catch{}this.pc=void 0,this.opts.onClosed?.(e)}}};var Me={energyThreshold:.012,silenceMs:400,minSpeechMs:600,maxChunkMs:15e3},Re=class{opts;active=null;silenceTimer;constructor(e){this.opts={energyThreshold:e.energyThreshold??Me.energyThreshold,silenceMs:e.silenceMs??Me.silenceMs,minSpeechMs:e.minSpeechMs??Me.minSpeechMs,maxChunkMs:e.maxChunkMs??Me.maxChunkMs,log:e.log,onChunk:e.onChunk},this.silenceTimer=setInterval(()=>this.maybeClose(),100)}push(e){let t=Vs(e.samples,e.channelCount),s=Qs(t)>=this.opts.energyThreshold;if(!this.active){if(!s)return;this.active={samples:[],totalSamples:0,sourceRate:e.sampleRate,startedAt:e.receivedAt,lastVoiceAt:e.receivedAt}}this.active.samples.push(t),this.active.totalSamples+=t.length,s&&(this.active.lastVoiceAt=e.receivedAt)}maybeClose(){if(!this.active)return;let e=Date.now(),t=e-this.active.startedAt,n=e-this.active.lastVoiceAt,s=t-n;if(t>=this.opts.maxChunkMs){this.flush("max-duration");return}s>=this.opts.minSpeechMs&&n>=this.opts.silenceMs&&this.flush("silence-gap")}flush(e="manual"){if(!this.active)return;let t=this.active;this.active=null;let n=Date.now()-t.startedAt;if(t.totalSamples===0)return;let s=Zs(t.samples,t.totalSamples),i=ei(s,t.sourceRate),r=ti(i,16e3);this.opts.log(`audio chunk closed (${e}, ${n}ms, ${(i.length/16e3).toFixed(2)}s) \u2014 ${r.length} bytes`),this.opts.onChunk(r,n)}shutdown(){this.silenceTimer&&clearInterval(this.silenceTimer),this.silenceTimer=void 0,this.flush("shutdown")}};function Vs(c,e){if(e===1)return c;let t=new Int16Array(c.length/e);for(let n=0,s=0;n<c.length;n+=e,s++){let i=0;for(let r=0;r<e;r++)i+=c[n+r];t[s]=i/e}return t}function Qs(c){if(c.length===0)return 0;let e=0;for(let t=0;t<c.length;t++){let n=c[t]/32768;e+=n*n}return Math.sqrt(e/c.length)}function Zs(c,e){let t=new Int16Array(e),n=0;for(let s of c)t.set(s,n),n+=s.length;return t}function ei(c,e){if(e===16e3)return c;let t=e/16e3,n=Math.floor(c.length/t),s=new Int16Array(n);for(let i=0;i<n;i++){let r=i*t,o=Math.floor(r),a=Math.min(o+1,c.length-1),l=r-o;s[i]=(1-l)*c[o]+l*c[a]}return s}function ti(c,e){let t=c.length*2,n=Buffer.alloc(44);n.write("RIFF",0),n.writeUInt32LE(36+t,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(e,24),n.writeUInt32LE(e*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t,40);let s=Buffer.alloc(t);for(let i=0;i<c.length;i++)s.writeInt16LE(c[i],i*2);return Buffer.concat([n,s])}import{spawn as Cn}from"child_process";import{writeFile as ni,mkdtemp as si,rm as ii}from"fs/promises";import{tmpdir as ri}from"os";import{join as ut}from"path";var _e=class{opts;resolvedBackend=null;constructor(e){this.opts=e}async transcribe(e){let t=await this.resolveBackend();if(!t)return this.opts.log("[whisper] no backend available \u2014 chunk dropped"),null;try{return((t==="mlx"?await this.transcribeMlx(e):await this.transcribeOpenAI(e))?.trim()??"")||null}catch(n){return this.opts.log(`[whisper:${t}] transcription failed: ${n.message}`),null}}async resolveBackend(){if(this.resolvedBackend)return this.resolvedBackend;let e=this.opts.backend;return e==="mlx"?this.resolvedBackend=await this.probeMlx()?"mlx":null:e==="openai"?this.resolvedBackend=process.env.OPENAI_API_KEY?"openai":null:await this.probeMlx()?this.resolvedBackend="mlx":process.env.OPENAI_API_KEY&&(this.resolvedBackend="openai"),this.resolvedBackend?this.opts.log(`[whisper] using backend: ${this.resolvedBackend}`):this.opts.log(`[whisper] backend resolution failed (target=${e}, OPENAI_API_KEY=${process.env.OPENAI_API_KEY?"set":"unset"})`),this.resolvedBackend}mlxCmd(){return this.opts.mlxBinary||"mlx_whisper"}async probeMlx(){return new Promise(e=>{let t=Cn(this.mlxCmd(),["--help"],{stdio:"ignore"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}async transcribeMlx(e){let t=await si(ut(ri(),"agentx-whisper-")),n=ut(t,"chunk.wav");try{await ni(n,e);let s=["--model",this.opts.model||"small","--output-format","txt","--output-dir",t];this.opts.language&&this.opts.language!=="auto"&&s.push("--language",this.opts.language),s.push(n);let i=await oi(this.mlxCmd(),s);if(i.trim())return i;let{readFile:r}=await import("fs/promises");try{return await r(ut(t,"chunk.txt"),"utf-8")}catch{return""}}finally{await ii(t,{recursive:!0,force:!0}).catch(()=>{})}}async transcribeOpenAI(e){let t=process.env.OPENAI_API_KEY;if(!t)throw new Error("OPENAI_API_KEY not set");let n=new FormData;n.set("file",new Blob([e],{type:"audio/wav"}),"chunk.wav"),n.set("model",this.opts.model||"whisper-1"),this.opts.language&&this.opts.language!=="auto"&&n.set("language",this.opts.language),n.set("response_format","text");let s=await fetch("https://api.openai.com/v1/audio/transcriptions",{method:"POST",headers:{Authorization:`Bearer ${t}`},body:n});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(`OpenAI ${s.status}: ${i.slice(0,200)}`)}return await s.text()}};function oi(c,e){return new Promise((t,n)=>{let s=Cn(c,e,{stdio:["ignore","pipe","pipe"]}),i="",r="";s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{r+=o.toString()}),s.on("error",n),s.on("exit",o=>{o===0?t(i):n(new Error(`${c} exited ${o}: ${r.slice(0,200)}`))})})}var Mn=50,Pe=class{opts;bots=new Map;whisper;completed=[];constructor(e){this.opts=e,this.whisper=new _e({backend:e.whisperBackend,model:e.whisperModel,language:e.whisperLanguage,mlxBinary:e.mlxBinary,log:e.log})}async invite(e){let t=this.bots.get(e.callId);if(t)return this.opts.log(`[bot-manager] bot already active for call=${e.callId} agent=${t.invite.agentId}`),{ok:!0};let n=`bot:${e.agentId}`;this.opts.log(`[bot-manager] spawning ${n} for call=${e.callId} target=${e.target}`);let s=new Re({log:this.opts.log,onChunk:async(a,l)=>{let d=await this.whisper.transcribe(a);if(d){this.recordTranscriptChunk(e.callId);try{await this.opts.onTranscript({invite:e,text:d,durationMs:l})}catch(g){this.opts.log(`[bot-manager] onTranscript hook threw: ${g.message}`)}}}}),i={callId:e.callId,botName:n,target:e.target,iceServers:this.opts.iceServers,broker:this.opts.broker,log:this.opts.log,onAudioFrame:a=>s.push(a),onClosed:a=>{this.opts.log(`[bot-manager] bot for call=${e.callId} closed (${a})`),this.tearDown(e.callId)}},r=new Ce(i);try{await r.start()}catch(a){return this.opts.log(`[bot-manager] bot.start failed: ${a.message}`),s.shutdown(),{ok:!1,error:a.message}}let o=setTimeout(()=>{this.opts.log(`[bot-manager] hard-cap reached for call=${e.callId} (${this.opts.maxCallMinutes}min) \u2014 closing`),this.tearDown(e.callId)},this.opts.maxCallMinutes*6e4);return this.bots.set(e.callId,{invite:e,bot:r,chunker:s,startedAt:Date.now(),timeoutTimer:o,transcriptChunks:0}),{ok:!0}}tearDown(e,t="teardown"){let n=this.bots.get(e);if(!n)return;this.bots.delete(e),clearTimeout(n.timeoutTimer);try{n.bot.close("manager teardown")}catch{}try{n.chunker.shutdown()}catch{}let s=Date.now(),i=Math.round((s-n.startedAt)/1e3);this.opts.log(`[bot-manager] tore down bot for call=${e} (was up ${i}s)`),this.completed.unshift({callId:e,agentId:n.invite.agentId,target:n.invite.target,startedAt:n.startedAt,endedAt:s,durationSec:i,transcriptChunks:n.transcriptChunks,reason:t}),this.completed.length>Mn&&(this.completed.length=Mn)}active(){let e=Date.now();return[...this.bots.values()].map(t=>({callId:t.invite.callId,agentId:t.invite.agentId,target:t.invite.target,uptimeSec:Math.round((e-t.startedAt)/1e3)}))}history(){return[...this.completed]}recordTranscriptChunk(e){let t=this.bots.get(e);t&&t.transcriptChunks++}shutdown(){for(let e of[...this.bots.keys()])this.tearDown(e,"shutdown")}};var de=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new de(`${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(de.levelOrder[e]<de.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",r=`[${this.module}]`,o=i?`${r} ${i}: ${t}`:`${r} ${t}`;console.error(o)}},ce=de;ue(ce,"levelOrder",{debug:0,info:1,warn:2,error:3});import{randomUUID as Rn}from"crypto";var Ee=class{listeners=new Map;subscribe(e,t){let n=Rn();return this.listeners.set(n,{filter:e,fn:t}),()=>{this.listeners.delete(n)}}publish(e){let t={id:typeof e.id=="string"?e.id:Rn(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e};for(let{filter:n,fn:s}of this.listeners.values())if(ai(n,t))try{s(t)}catch{}}get size(){return this.listeners.size}};function ai(c,e){return!(c.kinds&&c.kinds.length>0&&!c.kinds.includes(e.kind)||c.workflowId&&(e.kind==="run"&&e.workflowId!==c.workflowId||e.kind==="task"&&e.workflowId!==c.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==c.workflowId)||c.runId&&(e.kind==="run"&&e.runId!==c.runId||e.kind==="task"&&e.runId!==c.runId)||c.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(c.actor)||e.submittedBy===c.actor))||c.channel&&(e.kind!=="channel"||e.channel!==c.channel))}function _n(c){if(!c)return;let e=["run","task","signal","mesh","channel","status"],n=c.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as Pn,timingSafeEqual as ci}from"crypto";var Oe=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[]){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],r=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:o,parsed:a}=await this.readBody(e),l=r||this.detectSource(e.headers),d=this.validateSignature(e.headers,o,l,i);if(d){this.log(`Webhook [${l}] -> ${i}: REJECTED (${d})`),this.sendJson(t,401,{error:d});return}let g=this.buildSummary(l,a,e.headers);this.log(`Webhook [${l}] -> ${i}: ${g.slice(0,100)}`);let h=this.extractEventType(l,a,e.headers),p=this.webhookEntries.find(m=>m.enabled&&m.agentId===i&&m.source===l),u=h&&p?.triggers?.[h]||p?.defaultWorkflow||null;if(u&&this.workflowDispatcher)try{let m=await this.workflowDispatcher.dispatchWorkflow({workflowId:u,entityRef:{kind:"webhook",id:`${l}:${i}:${h??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:l,eventType:h,payload:a},trigger:{source:l}});this.log(`Webhook [${l}/${h??"\u2014"}] -> workflow=${u} (claimed=${m.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:l,eventType:h,workflow:u,claimed:m.claimed});return}catch(m){this.log(`Workflow dispatch failed [${l}/${h}/${u}]: ${m.message}`)}let f=this.webhookEntries.find(m=>m.enabled&&m.node&&m.agentId===i&&m.source===l);if(f?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:l,node:f.node,status:"accepted"}),this.mesh.sendTask(f.node,g,i,{context:{channel:`webhook:${l}`,sender:`webhook:${l}`}}).then(m=>this.log(`Mesh-forwarded webhook [${l}] -> ${f.node}/${i}: ${m?.slice(0,100)||"ok"}`),m=>this.log(`Mesh forward failed [${l}] -> ${f.node}/${i}: ${m.message}`));return}try{let m=await this.registry.execute({message:g,agentId:i,context:{channel:`webhook:${l}`,sender:`webhook:${l}`}});this.sendJson(t,m.error?500:200,{ok:!m.error,agent:i,source:l,response:m.content?.slice(0,500),error:m.error,duration:m.duration})}catch(m){this.sendJson(t,500,{error:m.message})}}extractEventType(e,t,n){let s=i=>{let r=n[i.toLowerCase()];return Array.isArray(r)?r[0]:r};if(e==="github"){let i=s("x-github-event");if(!i)return;let r=typeof t.action=="string"?t.action:void 0;return r?`${i}.${r}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource")}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 r=n["x-gitlab-event"]||t.object_kind||"event",o=t.project?.path_with_namespace||"",a=t.user?.name||t.user_username||"";if(s.push(`Event: ${r}`),o&&s.push(`Project: ${o}`),a&&s.push(`User: ${a}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
|
|
409
|
-
`)[0]||"no message"} (${d.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 d=t.object_attributes;s.push(`Pipeline: ${d?.status||""} (${d?.ref||""})`),s.push(`Duration: ${d?.duration||0}s`)}break}case"github":{let r=n["x-github-event"]||"event",o=t.repository?.full_name||"",a=t.sender?.login||"";if(s.push(`Event: ${r}`),o&&s.push(`Repository: ${o}`),a&&s.push(`Sender: ${a}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let g of t.commits.slice(0,3))s.push(` - ${g.message?.split(`
|
|
410
|
-
`)[0]||""} (${g.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 d=t.issue;d&&(s.push(`Issue #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let r=t.type||"event",o=t.data?.object||{};s.push(`Event: ${r}`),o.amount&&s.push(`Amount: ${(o.amount/100).toFixed(2)} ${o.currency?.toUpperCase()||""}`),o.customer_email&&s.push(`Customer: ${o.customer_email}`),o.description&&s.push(`Description: ${o.description}`),o.status&&s.push(`Status: ${o.status}`);break}case"sentry":{let r=n["sentry-hook-resource"]||"event";s.push(`Resource: ${r}`);let o=t.data||t;o.error?.title&&s.push(`Error: ${o.error.title}`),o.error?.culprit&&s.push(`Culprit: ${o.error.culprit}`),o.error?.metadata?.value&&s.push(`Message: ${o.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(r=>r.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
|
|
411
|
-
`)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s){let i=this.webhookEntries.find(l=>l.enabled&&l.agentId===s&&l.source===n);if(!i?.secretEnv)return null;let r=process.env[i.secretEnv];if(!r)return`webhook entry "${i.id}" expects env ${i.secretEnv} but it is unset`;let o=l=>{let d=e[l.toLowerCase()];return Array.isArray(d)?d[0]:d};if(n==="github"){let l=o("x-hub-signature-256");if(!l)return"missing X-Hub-Signature-256";let d="sha256="+Pn("sha256",r).update(t).digest("hex");return je(d,l)}if(n==="gitlab"){let l=o("x-gitlab-token");return l?je(r,l):"missing X-Gitlab-Token"}if(n==="stripe"){let l=o("stripe-signature");if(!l)return"missing Stripe-Signature";let d=Object.fromEntries(l.split(",").map(h=>h.split("=")));if(!d.t||!d.v1)return"malformed Stripe-Signature";let g=Pn("sha256",r).update(`${d.t}.${t}`).digest("hex");return je(g,d.v1)}let a=o("x-webhook-secret");return a?je(r,a):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function je(c,e){if(c.length!==e.length)return"signature mismatch";let t=Buffer.from(c),n=Buffer.from(e);return ci(t,n)?null:"signature mismatch"}import di from"better-sqlite3";import{mkdirSync as li}from"fs";import{dirname as gi,resolve as hi}from"path";var De;function En(c={}){if(c.disabled)return null;if(De)return De;let e=hi(process.cwd(),c.path??".agentx/db.sqlite");try{li(gi(e),{recursive:!0});let t=new di(e);return t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("foreign_keys = ON"),ui(t),De=t,De}catch(t){return console.error(`[storage/sqlite] openDb failed at ${e}: ${t.message}`),null}}function ui(c){c.exec(`
|
|
412
|
-
CREATE TABLE IF NOT EXISTS schema_version (
|
|
413
|
-
v INTEGER PRIMARY KEY
|
|
414
|
-
);
|
|
415
|
-
`);let e=c.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0,t=[{v:1,sql:`
|
|
416
|
-
CREATE TABLE task_history (
|
|
417
|
-
id TEXT PRIMARY KEY,
|
|
418
|
-
agent_id TEXT NOT NULL,
|
|
419
|
-
channel TEXT,
|
|
420
|
-
chat_id TEXT,
|
|
421
|
-
status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'
|
|
422
|
-
message_preview TEXT,
|
|
423
|
-
error TEXT,
|
|
424
|
-
duration_ms INTEGER,
|
|
425
|
-
input_tokens INTEGER,
|
|
426
|
-
output_tokens INTEGER,
|
|
427
|
-
cache_read_tokens INTEGER,
|
|
428
|
-
cache_create_tokens INTEGER,
|
|
429
|
-
started_at TEXT NOT NULL,
|
|
430
|
-
finished_at TEXT NOT NULL
|
|
431
|
-
);
|
|
432
|
-
CREATE INDEX idx_task_history_agent_started
|
|
433
|
-
ON task_history(agent_id, started_at);
|
|
434
|
-
CREATE INDEX idx_task_history_status
|
|
435
|
-
ON task_history(status, started_at);
|
|
436
|
-
`},{v:2,sql:`
|
|
437
|
-
CREATE TABLE usage_daily (
|
|
438
|
-
agent_id TEXT NOT NULL,
|
|
439
|
-
model TEXT NOT NULL,
|
|
440
|
-
day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC
|
|
441
|
-
input_tokens INTEGER DEFAULT 0,
|
|
442
|
-
output_tokens INTEGER DEFAULT 0,
|
|
443
|
-
cache_read_tokens INTEGER DEFAULT 0,
|
|
444
|
-
cache_create_tokens INTEGER DEFAULT 0,
|
|
445
|
-
tasks INTEGER DEFAULT 0,
|
|
446
|
-
PRIMARY KEY (agent_id, model, day)
|
|
447
|
-
);
|
|
448
|
-
CREATE INDEX idx_usage_day ON usage_daily(day);
|
|
449
|
-
`},{v:3,sql:`
|
|
450
|
-
CREATE TABLE rotations (
|
|
451
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
452
|
-
agent_id TEXT NOT NULL,
|
|
453
|
-
channel TEXT NOT NULL,
|
|
454
|
-
chat_id TEXT NOT NULL,
|
|
455
|
-
reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'
|
|
456
|
-
last_turn_input_tokens INTEGER,
|
|
457
|
-
rotated_at TEXT NOT NULL
|
|
458
|
-
);
|
|
459
|
-
CREATE INDEX idx_rotations_agent_at
|
|
460
|
-
ON rotations(agent_id, rotated_at);
|
|
461
|
-
`},{v:4,sql:`
|
|
462
|
-
CREATE TABLE route_traces (
|
|
463
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
464
|
-
channel TEXT NOT NULL,
|
|
465
|
-
chat_id TEXT NOT NULL,
|
|
466
|
-
msg_id TEXT NOT NULL,
|
|
467
|
-
account_id TEXT,
|
|
468
|
-
kind TEXT NOT NULL, -- 'match' | 'drop'
|
|
469
|
-
deciding_stage TEXT,
|
|
470
|
-
agent_id TEXT,
|
|
471
|
-
reason TEXT,
|
|
472
|
-
at TEXT NOT NULL
|
|
473
|
-
);
|
|
474
|
-
CREATE INDEX idx_route_traces_channel_at
|
|
475
|
-
ON route_traces(channel, at);
|
|
476
|
-
`},{v:5,sql:`
|
|
477
|
-
ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;
|
|
478
|
-
ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;
|
|
479
|
-
ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;
|
|
480
|
-
ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;
|
|
481
|
-
`}],n=c.transaction(s=>{c.exec(s.sql),c.prepare("INSERT INTO schema_version (v) VALUES (?)").run(s.v)});for(let s of t)s.v>e&&n(s)}function jn(c,e){let t=Date.now()-e*24*60*60*1e3,n=new Date(t).toISOString(),s=c.prepare("DELETE FROM task_history WHERE started_at < ?").run(n).changes??0,i=c.prepare("DELETE FROM rotations WHERE rotated_at < ?").run(n).changes??0,r=c.prepare("DELETE FROM route_traces WHERE at < ?").run(n).changes??0;if(s+i+r>0)try{c.pragma("incremental_vacuum")}catch{}return{taskHistory:s,rotations:i,routeTraces:r}}function pi(c){return{insertTaskHistory:c.prepare(`
|
|
482
|
-
INSERT OR REPLACE INTO task_history (
|
|
483
|
-
id, agent_id, channel, chat_id, status, message_preview, error,
|
|
484
|
-
duration_ms, input_tokens, output_tokens,
|
|
485
|
-
cache_read_tokens, cache_create_tokens,
|
|
486
|
-
started_at, finished_at
|
|
487
|
-
) VALUES (
|
|
488
|
-
@id, @agent_id, @channel, @chat_id, @status, @message_preview, @error,
|
|
489
|
-
@duration_ms, @input_tokens, @output_tokens,
|
|
490
|
-
@cache_read_tokens, @cache_create_tokens,
|
|
491
|
-
@started_at, @finished_at
|
|
492
|
-
)
|
|
493
|
-
`),upsertUsageDaily:c.prepare(`
|
|
494
|
-
INSERT INTO usage_daily (
|
|
495
|
-
agent_id, model, day,
|
|
496
|
-
input_tokens, output_tokens, cache_read_tokens, cache_create_tokens,
|
|
497
|
-
tier2_input_tokens, tier2_output_tokens,
|
|
498
|
-
tier2_cache_read_tokens, tier2_cache_create_tokens,
|
|
499
|
-
tasks
|
|
500
|
-
) VALUES (
|
|
501
|
-
@agent_id, @model, @day,
|
|
502
|
-
@input_tokens, @output_tokens, @cache_read_tokens, @cache_create_tokens,
|
|
503
|
-
@tier2_input_tokens, @tier2_output_tokens,
|
|
504
|
-
@tier2_cache_read_tokens, @tier2_cache_create_tokens,
|
|
505
|
-
1
|
|
506
|
-
)
|
|
507
|
-
ON CONFLICT(agent_id, model, day) DO UPDATE SET
|
|
508
|
-
input_tokens = input_tokens + excluded.input_tokens,
|
|
509
|
-
output_tokens = output_tokens + excluded.output_tokens,
|
|
510
|
-
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
|
|
511
|
-
cache_create_tokens = cache_create_tokens + excluded.cache_create_tokens,
|
|
512
|
-
tier2_input_tokens = tier2_input_tokens + excluded.tier2_input_tokens,
|
|
513
|
-
tier2_output_tokens = tier2_output_tokens + excluded.tier2_output_tokens,
|
|
514
|
-
tier2_cache_read_tokens = tier2_cache_read_tokens + excluded.tier2_cache_read_tokens,
|
|
515
|
-
tier2_cache_create_tokens = tier2_cache_create_tokens + excluded.tier2_cache_create_tokens,
|
|
516
|
-
tasks = tasks + 1
|
|
517
|
-
`),insertRotation:c.prepare(`
|
|
518
|
-
INSERT INTO rotations (agent_id, channel, chat_id, reason, last_turn_input_tokens, rotated_at)
|
|
519
|
-
VALUES (@agent_id, @channel, @chat_id, @reason, @last_turn_input_tokens, @rotated_at)
|
|
520
|
-
`),insertRouteTrace:c.prepare(`
|
|
521
|
-
INSERT INTO route_traces (channel, chat_id, msg_id, account_id, kind, deciding_stage, agent_id, reason, at)
|
|
522
|
-
VALUES (@channel, @chat_id, @msg_id, @account_id, @kind, @deciding_stage, @agent_id, @reason, @at)
|
|
523
|
-
`)}}function On(c,e="claude-opus-4-7"){let t=X(),n=pi(c),s=new Map,i=d=>{let g=`${d.agentId}:${d.channel}:${d.chatId}`;s.set(g,{agentId:d.agentId,channel:d.channel,chatId:d.chatId,startedAt:d.at,messagePreview:d.messagePreview})},r=d=>{let g=`${d.agentId}:${d.channel}:${d.chatId}`,h=s.get(g);s.delete(g);let p=`${d.agentId}:${d.channel}:${d.chatId}:${d.at}`,u=d.error?"error":"ok";try{n.insertTaskHistory.run({id:p,agent_id:d.agentId,channel:d.channel,chat_id:d.chatId,status:u,message_preview:h?.messagePreview??null,error:d.error??null,duration_ms:d.durationMs,input_tokens:d.inputTokens??null,output_tokens:d.outputTokens??null,cache_read_tokens:d.cacheReadTokens??null,cache_create_tokens:d.cacheCreateTokens??null,started_at:h?.startedAt??d.at,finished_at:d.at})}catch{}let f=d.inputTokens||d.outputTokens||d.cacheReadTokens||d.cacheCreateTokens||d.tier2InputTokens||d.tier2OutputTokens||d.tier2CacheReadTokens||d.tier2CacheCreateTokens;if(!d.error&&f){let m=d.at.slice(0,10);try{n.upsertUsageDaily.run({agent_id:d.agentId,model:e,day:m,input_tokens:d.inputTokens??0,output_tokens:d.outputTokens??0,cache_read_tokens:d.cacheReadTokens??0,cache_create_tokens:d.cacheCreateTokens??0,tier2_input_tokens:d.tier2InputTokens??0,tier2_output_tokens:d.tier2OutputTokens??0,tier2_cache_read_tokens:d.tier2CacheReadTokens??0,tier2_cache_create_tokens:d.tier2CacheCreateTokens??0})}catch{}}},o=d=>{try{n.insertRotation.run({agent_id:d.agentId,channel:d.channel,chat_id:d.chatId,reason:d.reason,last_turn_input_tokens:d.lastTurnInputTokens??null,rotated_at:d.at})}catch{}},a=d=>{try{n.insertRouteTrace.run({channel:d.channel,chat_id:d.chatId,msg_id:d.msgId,account_id:d.accountId??null,kind:"match",deciding_stage:d.decidingStage,agent_id:d.agentId,reason:null,at:d.at})}catch{}},l=d=>{try{n.insertRouteTrace.run({channel:d.channel,chat_id:d.chatId,msg_id:d.msgId,account_id:d.accountId??null,kind:"drop",deciding_stage:d.decidingStage,agent_id:null,reason:d.reason,at:d.at})}catch{}};return t.on("task:started",i),t.on("task:completed",r),t.on("session:rotated",o),t.on("message:matched",a),t.on("message:dropped",l),()=>{t.off("task:started",i),t.off("task:completed",r),t.off("session:rotated",o),t.off("message:matched",a),t.off("message:dropped",l)}}function mi(c){return{tasks:c.tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cacheReadTokens:c.cache_read_tokens,cacheCreateTokens:c.cache_create_tokens,tier2InputTokens:c.tier2_input_tokens,tier2OutputTokens:c.tier2_output_tokens,tier2CacheReadTokens:c.tier2_cache_read_tokens,tier2CacheCreateTokens:c.tier2_cache_create_tokens,totalDuration:0,errors:0,model:c.model}}function fi(c,e){if(!c)return null;let t=c.prepare("SELECT * FROM usage_daily WHERE day = ?").all(e);if(t.length===0)return null;let n={};for(let s of t){let i=n[s.agent_id],r=mi(s);i?(i.tasks+=r.tasks,i.inputTokens+=r.inputTokens,i.outputTokens+=r.outputTokens,i.cacheReadTokens+=r.cacheReadTokens,i.cacheCreateTokens+=r.cacheCreateTokens,i.tier2InputTokens=(i.tier2InputTokens||0)+(r.tier2InputTokens||0),i.tier2OutputTokens=(i.tier2OutputTokens||0)+(r.tier2OutputTokens||0),i.tier2CacheReadTokens=(i.tier2CacheReadTokens||0)+(r.tier2CacheReadTokens||0),i.tier2CacheCreateTokens=(i.tier2CacheCreateTokens||0)+(r.tier2CacheCreateTokens||0),i.model=r.model):n[s.agent_id]=r}return{date:e,agents:n}}function Dn(c,e){let t=e??new Date().toISOString().slice(0,10);return fi(c,t)??{date:t,agents:{}}}function Nn(c=process.env){let e=(c.AGENTX_USAGE_READ??"").toLowerCase().trim();return e==="sqlite"||e==="json"||e==="sqlite-then-json"?e:"sqlite-then-json"}import{z as Ne}from"zod";var pt=Ne.object({name:Ne.string().min(1,"manifest.name is required"),version:Ne.string().min(1,"manifest.version is required"),agentxRange:Ne.string().optional()});function mt(c){let e=[],t=[],n=X(),s=`[plugin:${c.packageName}]`;return{ctx:{log:(...r)=>c.log(s,...r),on(r,o){let a=d=>{try{o(d)}catch(g){c.log(s,`subscriber for "${String(r)}" threw:`,g?.stack??g)}};n.on(r,a);let l=()=>n.off(r,a);return t.push(l),l},addChannel(r){if(!r||typeof r.name!="string"||!r.name){c.log(s,"addChannel: adapter is missing a string name; skipped");return}if(c.isChannelNameTaken?.(r.name)){c.log(s,`addChannel: name "${r.name}" already in use; skipped`);return}if(e.some(o=>o.name===r.name)){c.log(s,`addChannel: name "${r.name}" already added by this plugin; skipped`);return}e.push(r)},agents:c.agents,config:c.config},channels:e,disposeSubscriptions:()=>{for(let r of t)try{r()}catch{}t.length=0}}}var yi=15e3;async function ft(c){let e=c.config.plugins??[];if(e.length===0)return[];let t=c.importer??(i=>import(i)),n=c.setupTimeoutMs??yi,s=[];for(let i of e){let r;try{r=await t(i)}catch(h){c.log(`[plugins] import failed for "${i}": ${h?.message??h}`);continue}let o=bi(r);if(!wi(o)){c.log(`[plugins] "${i}" did not export a default AgentXPlugin (no manifest/setup pair found)`);continue}let a=o,l=pt.safeParse(a.manifest);if(!l.success){let h=l.error.issues.map(p=>p.message).join("; ");c.log(`[plugins] "${i}" manifest invalid: ${h}`);continue}if(l.data.agentxRange&&c.daemonVersion&&!ki(l.data.agentxRange,c.daemonVersion)){c.log(`[plugins] "${i}" requires agentx ${l.data.agentxRange}, daemon is ${c.daemonVersion}; skipped`);continue}let d=mt({packageName:i,agents:c.agents,config:c.config,log:c.log,isChannelNameTaken:c.isChannelNameTaken}),g=!1;try{await vi(Promise.resolve(a.setup(d.ctx)),n,`setup() exceeded ${n}ms`),g=!0}catch(h){c.log(`[plugins] "${i}" setup() failed: ${h?.message??h}`),d.disposeSubscriptions();continue}g&&(c.log(`[plugins] loaded ${l.data.name} v${l.data.version}`),s.push({manifest:l.data,packageName:i,channels:d.channels,dispose:async()=>{try{typeof a.teardown=="function"&&await a.teardown()}catch(h){c.log(`[plugins] "${i}" teardown() threw: ${h?.message??h}`)}finally{d.disposeSubscriptions()}}}))}return s}function bi(c){if(c==null||typeof c!="object")return c;let e=c;if(e.default&&typeof e.default=="object"){let t=e.default;if(t.manifest&&typeof t.setup=="function")return t;if(t.default&&typeof t.default=="object"){let n=t.default;if(n.manifest&&typeof n.setup=="function")return n}}return e.manifest&&typeof e.setup=="function"?e:e.default??e}function wi(c){return!!c&&typeof c=="object"&&"manifest"in c&&"setup"in c&&typeof c.setup=="function"}function ki(c,e){let t=c.replace(/^[\^~=v]+/,"").split("."),n=e.replace(/^v/,"").split(".");return t[0]===n[0]&&(t[1]??"")===(n[1]??"")}function vi(c,e,t){return new Promise((n,s)=>{let i=setTimeout(()=>s(new Error(t)),e);c.then(r=>{clearTimeout(i),n(r)},r=>{clearTimeout(i),s(r)})})}function $i(c,e,t=Date.now){return{ts:t(),source:"mesh",sourceEventId:null,project:c.context?.project??null,subject:c.context?.chatId?`chat:${c.context.chatId}`:`mesh:agent:${c.agentId}`,intent:c.context?.channel?`mesh.${c.context.channel}`:"mesh.task",rawJson:e}}function Si(c){return{decidedBy:"mesh-receiver",decide:()=>({agentId:c.agentId,outcome:c.outcome==="deduped"?"halted":c.outcome,reason:c.outcome==="deduped"?`legacy-dedup: ${c.reason??""}`.trim():c.reason??null})}}function Ln(c,e,t,n,s=Date.now){let i=$i(e,t,s),r=Si(n),o=F(c,i,r,s);return H(c,"mesh",o,n,s),o}function Bn(c,e){return c?c.intents.length===0||!e?!0:c.intents.includes(e):!1}function Ii(c,e,t,n=6*60*60*1e3){if(!e||!t)return 0;let s=Date.now()-n;return c.db.prepare(`
|
|
524
|
-
SELECT DISTINCT d.agent_id
|
|
525
|
-
FROM intent_decisions d
|
|
526
|
-
JOIN intent_events e ON e.id = d.event_id
|
|
527
|
-
WHERE e.project = ? AND e.subject = ?
|
|
528
|
-
AND d.outcome = 'dispatched'
|
|
529
|
-
AND d.agent_id IS NOT NULL
|
|
530
|
-
AND d.decided_at >= ?
|
|
531
|
-
`).all(e,t,s).length}function Gn(c,e,t,n,s){if(!e)return!1;let i=e.maxDelegationDepth;if(i<=0)return!1;let r=Ii(c,n,s);return(c.db.prepare(`
|
|
532
|
-
SELECT 1
|
|
533
|
-
FROM intent_decisions d
|
|
534
|
-
JOIN intent_events e ON e.id = d.event_id
|
|
535
|
-
WHERE e.project = ? AND e.subject = ?
|
|
536
|
-
AND d.agent_id = ?
|
|
537
|
-
AND d.outcome = 'dispatched'
|
|
538
|
-
LIMIT 1
|
|
539
|
-
`).get(n,s,t)?r:r+1)<=i}var le=class{cache=new Map;config;meshPeers=[];constructor(e){this.config=e}fingerprint="";build(e){e&&(this.meshPeers=e),this.cache.clear(),this.fingerprint=this.computeFingerprint();for(let t of Object.keys(this.config.agents))this.cache.set(t,this.renderForAgent(t))}computeFingerprint(){return[...this.meshPeers].sort((t,n)=>t.peer.localeCompare(n.peer)).map(t=>`${t.peer}:${t.skills.map(n=>n.id).sort().join(",")}`).join("|")}getForAgent(e){return this.cache.get(e)}refresh(e){this.meshPeers=e,!(this.computeFingerprint()===this.fingerprint&&this.cache.size>0)&&this.build()}renderForAgent(e){let t=["[Landscape]"],n=this.config.agents[e];t.push(`Node: ${this.config.node.name} (${this.config.node.id})`);let s=this.getPrimaryHandle(e),i=this.extractCapability(n),r=s?` (${s})`:"";t.push(`You: ${n.name}${r} \u2014 ${i}`),t.push("");let o=Object.entries(this.config.agents).filter(([h])=>h!==e);t.push(`Available agents on this node (${o.length} \u2014 not all may be in the current group):`);for(let[h,p]of o){let u=this.getPrimaryHandle(h),f=this.extractCapability(p),m=u?` (${u})`:"";t.push(`\u2022 ${p.name}${m} \u2014 ${f}`)}let a=this.meshPeers.filter(h=>h.skills.length>0);if(a.length){t.push(""),t.push("Remote agents (on mesh peers \u2014 address by id via /mesh/task or A2A):");let h=[...a].sort((p,u)=>p.peer.localeCompare(u.peer));for(let p of h){let u=[...p.skills].sort((f,m)=>f.id.localeCompare(m.id));for(let f of u){let m=(f.description||"").slice(0,80),y=f.name&&f.name!==f.id?` (${f.name})`:"";t.push(`\u2022 ${f.id}${y} [${p.peer}] \u2014 ${m}`)}}}t.push(""),t.push(this.renderChannels()),t.push(""),t.push("[Rules]");let l=[s,e].filter(Boolean).join(" / ");t.push(`- Only respond when YOU (${l}) are mentioned or this is a DM to you`),t.push("- If another agent was mentioned and you were NOT, stay silent \u2014 they will handle it"),t.push("- The agent list above shows all agents on the node \u2014 do NOT assume they are all in the current chat group"),t.push("- When asked about group members, only mention agents you have seen in the conversation history"),t.push("- To delegate on Telegram: mention the agent's handle in your response"),t.push("- On GitLab: reply directly, no Telegram handles. To send to other channels, use the /send API below"),t.push("- On WhatsApp: mention another agent's handle to delegate (shared number \u2014 name prefixed automatically). To send to other channels, use /send API");let[,d]=this.config.node.bind.split(":"),g=d||"19900";return t.push(""),t.push("[Cross-Channel Messaging]"),t.push("You can send messages to ANY channel proactively (not just reply):"),t.push(` curl -X POST http://localhost:${g}/send -H "Content-Type: application/json" -d '{"channel":"<channel>","chatId":"<id>","text":"<message>"}'`),t.push("Channels: telegram, whatsapp, gitlab, discord"),t.push("ChatId formats:"),t.push(' telegram: numeric (e.g. "-1001234567890" for group, "123456" for DM)'),t.push(' gitlab: "group/project:issue:123" or "group/project:merge_request:45"'),t.push(' whatsapp: JID (e.g. "+21612345678@s.whatsapp.net")'),t.push("Use this when asked to notify someone on a different channel, post to an issue, or broadcast updates."),t.push(""),t.push("[Conversation Recall \u2014 short/long memory]"),t.push(`If a message references prior context you don't have ("that", "it", "yes please", "continue", "correct me if I'm wrong", "as discussed"), recall the actual prior turns BEFORE replying \u2014 do not guess, do not invent context from other tools, and do not ask the user to repeat themselves.`),t.push(""),t.push("ALWAYS pass `channel` and `chatId` from the [Current Conversation] block above so you scope to the right thread:"),t.push(` curl -s -X POST http://localhost:${g}/recall -H "Content-Type: application/json" -d '{"agent":"<your-agent-id>","channel":"<from prompt>","chatId":"<from prompt>","limit":10}'`),t.push(""),t.push("Short memory (default \u2014 today only): omit `lookbackDays`. Returns last ~10 turns of THIS chat from today UTC."),t.push("Long memory (opt-in): set `lookbackDays` only when the user message has a clear long-memory cue:"),t.push(' - "yesterday" / "\u0623\u0645\u0633" \u2192 lookbackDays: 2'),t.push(' - "few days ago" / "couple of days" \u2192 lookbackDays: 4'),t.push(' - "last week" / "week ago" \u2192 lookbackDays: 8'),t.push(' - "remember when \u2026" / "we discussed \u2026" \u2192 lookbackDays: 3'),t.push("If unsure, start short and paginate backward using `oldestTs` from the previous response as the next call's `before`."),t.push(""),t.push("Other optional fields: `query` (substring filter, e.g. an issue number or name), `participants` (filter by sender username), `after`/`before` (ISO ts overrides). Response shape: { turns: [{ ts, role, senderName, content, channel, chatId }], oldestTs, hasMore, totalScanned }."),t.push("Scope rule: omit chatId to span all of YOUR chats on the channel; omit channel to span all channels. Store is per-agent \u2014 you cannot read another agent's chats."),t.push(""),t.push("[Background Monitoring]"),t.push("You can watch things in the background while continuing to work:"),t.push("- Tail log files and react to errors as they appear"),t.push("- Poll CI/CD pipelines and report when status changes"),t.push("- Watch directories for file changes"),t.push("Use the Monitor tool for this \u2014 it runs a script in the background and streams output to you."),t.push(""),t.push("[Agent Teams]"),t.push("For complex tasks that benefit from parallel work, you can spawn an agent team:"),t.push("- Tell Claude Code to 'create an agent team' with specialized teammates"),t.push("- Each teammate works independently with its own context window"),t.push("- Teammates coordinate via shared task list and direct messaging"),t.push("- Best for: code review (security + performance + tests), debugging with competing hypotheses, multi-module features"),t.push("- Use teams when work can be parallelized. Use single session for sequential/simple tasks."),t.join(`
|
|
540
|
-
`)}renderChannels(){let e=[],t=this.config.channels;if(t.telegram.enabled){let n=t.telegram.policy;e.push(`telegram(groups:${n.group}, DMs:${n.dm}, delegation:yes)`)}return t.gitlab?.enabled&&e.push("gitlab(webhooks, no delegation)"),t.whatsapp.enabled&&e.push("whatsapp(DMs only, no delegation)"),t.discord?.enabled&&e.push("discord(enabled)"),`Channels: ${e.join(", ")}`}getPrimaryHandle(e){let t=this.config.agents[e];if(t)return t.mentions.find(n=>n.startsWith("@"))}extractCapability(e){if(!e.systemPrompt)return e.name;let t=e.systemPrompt.split(/[.\n]/)[0]?.trim()||e.name;return t.length>80?t.slice(0,77)+"...":t}};import{existsSync as Ti,readFileSync as xi}from"fs";import{resolve as Ai}from"path";var Ci=".agentx/contacts.json",Le=class{contacts=[];filePath;log;constructor(e=process.cwd(),t=()=>{}){this.filePath=Ai(e,Ci),this.log=t,this.reload()}reload(){if(!Ti(this.filePath))return this.contacts=[],{count:0};try{let e=xi(this.filePath,"utf-8"),t=JSON.parse(e),s=(Array.isArray(t.contacts)?t.contacts:[]).filter(i=>!(!i||typeof i.id!="string"||!i.id||typeof i.name!="string"||!i.name||!i.channels||typeof i.channels!="object"));return this.contacts=s,{count:s.length}}catch(e){return this.log(`[contacts] reload failed: ${e.message}`),{count:this.contacts.length,error:e.message}}}size(){return this.contacts.length}list(){return this.contacts.slice()}getById(e){return this.contacts.find(t=>t.id===e)}resolve(e){let t=(e||"").trim();if(!t)return{kind:"miss",query:t};let n=t.toLowerCase();for(let r of this.contacts)if(r.id.toLowerCase()===n)return{kind:"exact",contact:r};for(let r of this.contacts){if(r.name.toLowerCase()===n)return{kind:"alias",contact:r};for(let o of r.aliases??[])if(o.toLowerCase()===n)return{kind:"alias",contact:r}}let s=0,i=[];for(let r of this.contacts){let o=[r.id,r.name,...r.aliases??[]],a=0;for(let l of o){let d=l.toLowerCase();if(n.includes(d)||d.includes(n)){let g=Math.min(d.length,n.length);g>a&&(a=g)}}a>s?(s=a,i=[r]):a>0&&a===s&&i.push(r)}return i.length===0?{kind:"miss",query:t}:i.length>1?{kind:"ambiguous",candidates:i}:{kind:"fuzzy",contact:i[0],confidence:s/Math.max(n.length,1)}}pickChannel(e,t){if(t&&e.channels[t])return{channel:t,address:e.channels[t]};let n=Object.entries(e.channels);if(n.length===0)return;let[s,i]=n[0];return{channel:s,address:i}}};import{existsSync as Mi,readFileSync as Ri,unlinkSync as _i,writeFileSync as Pi}from"fs";import{resolve as Ei}from"path";var Un="_agentxManaged";function Fn(c,e){let t=Ei(c,".mcp.json"),n=Mi(t),s=n?ji(t):null,i=s!==null&&s[Un]===!0;if(n&&!i)return"skipped-operator-owned";let r=Object.keys(e).length>0;if(!r&&!n)return"noop";if(!r&&i)return _i(t),"removed";let o={[Un]:!0,mcpServers:e};return Pi(t,JSON.stringify(o,null,2)+`
|
|
541
|
-
`),n?"updated":"installed"}function ji(c){try{return JSON.parse(Ri(c,"utf-8"))}catch{return null}}var Hn="remember.md",Wn=`---
|
|
542
|
-
name: remember
|
|
543
|
-
description: Save a durable memory for yourself that will be inlined into your system prompt on every future session. Use when the user corrects your approach, confirms a non-obvious decision, reveals something durable about themselves or a project, or names an external resource you should reach back to. Writes go through the daemon's agent-memory HTTP API \u2014 no file system access required.
|
|
544
|
-
---
|
|
545
|
-
|
|
546
|
-
# Remember
|
|
547
|
-
|
|
548
|
-
You have a persistent memory layer that is auto-loaded into your system prompt on every task. It is SEPARATE from the shared wiki:
|
|
549
|
-
|
|
550
|
-
- **Wiki** is cross-agent, authoritative, documented. Facts that multiple agents agree on.
|
|
551
|
-
- **Memory** is yours alone, experiential. Things you learned the hard way, preferences that matter only for your work, pointers that help you navigate a specific user's stack.
|
|
552
|
-
|
|
553
|
-
Four memory kinds:
|
|
554
|
-
|
|
555
|
-
| Kind | Save something of type\u2026 |
|
|
556
|
-
|---|---|
|
|
557
|
-
| \`user\` | role, seniority, tone preference, what they are fluent in vs new to |
|
|
558
|
-
| \`feedback\` | corrections ("don't do X, we got burned last Q") + confirmations ("yes the bundled PR was right") |
|
|
559
|
-
| \`project\` | current initiative, known constraints, deadline context not in the code |
|
|
560
|
-
| \`reference\` | external systems and when to use them (Linear, Grafana, a specific dashboard URL) |
|
|
561
|
-
|
|
562
|
-
## When to save
|
|
563
|
-
|
|
564
|
-
**Good triggers** \u2014 save a memory whenever:
|
|
565
|
-
|
|
566
|
-
- The user corrects an approach ("no not that", "stop doing X"). Save as \`feedback\`.
|
|
567
|
-
- The user confirms a non-obvious approach worked ("yes exactly, keep doing that"). Save as \`feedback\`.
|
|
568
|
-
- You learn a durable fact about the user or their role you didn't know before. Save as \`user\`.
|
|
569
|
-
- You learn a project-level fact that is not in the code and not in the wiki. Save as \`project\`.
|
|
570
|
-
- The user points at an external system ("check Linear INGEST for ticket context"). Save as \`reference\`.
|
|
571
|
-
|
|
572
|
-
**Skip** \u2014 do NOT save:
|
|
573
|
-
|
|
574
|
-
- Conversation-specific state, current task TODOs, temporary context. Use the current session for those.
|
|
575
|
-
- Things already in the wiki, or that feel cross-agent authoritative. Propose a wiki article instead.
|
|
576
|
-
- Negative judgements about the user. Memories get re-read every session; stay professional.
|
|
577
|
-
|
|
578
|
-
## How to save
|
|
579
|
-
|
|
580
|
-
The daemon exposes \`POST /api/memory\`. Call it from a Bash tool invocation.
|
|
581
|
-
|
|
582
|
-
\`\`\`bash
|
|
583
|
-
curl -sS -X POST http://localhost:18800/api/memory \\
|
|
584
|
-
-H 'Content-Type: application/json' \\
|
|
585
|
-
-d '{
|
|
586
|
-
"agentId": "<your-agent-id>",
|
|
587
|
-
"type": "feedback",
|
|
588
|
-
"name": "no-mock-db",
|
|
589
|
-
"description": "Tests must hit a real database \u2014 mocks masked a prod migration bug in Q1.",
|
|
590
|
-
"body": "In Q1 2026 the payments migration passed every mocked integration test but failed on prod because the mocks diverged from the real schema. Rule: integration tests run against a throwaway real database (we spin one up in CI). Reason: mock/prod divergence is a silent failure mode. How to apply: when a user asks for tests, propose a real DB setup; flag any suggestion to mock the DB."
|
|
591
|
-
}'
|
|
592
|
-
\`\`\`
|
|
593
|
-
|
|
594
|
-
Your agent id is the name of the workspace directory you're in (e.g. \`atlas\`, \`mtgl-v2\`). When in doubt, run \`basename "$(pwd)"\`.
|
|
595
|
-
|
|
596
|
-
### Update an existing memory
|
|
597
|
-
|
|
598
|
-
Same endpoint, same \`name\`. The daemon keeps \`createdAt\` stable and bumps \`updatedAt\`. If you want to *append* rather than replace, pass \`"append": true\`:
|
|
599
|
-
|
|
600
|
-
\`\`\`bash
|
|
601
|
-
curl -sS -X POST http://localhost:18800/api/memory \\
|
|
602
|
-
-H 'Content-Type: application/json' \\
|
|
603
|
-
-d '{ "agentId":"atlas","type":"feedback","name":"no-mock-db",
|
|
604
|
-
"description":"\u2026", "body":"Also: 2026-04-15 hit the same class of bug on the grant-application webhook. Same rule.","append":true }'
|
|
605
|
-
\`\`\`
|
|
606
|
-
|
|
607
|
-
### Read what you already remember
|
|
608
|
-
|
|
609
|
-
Your CLAUDE.md already includes a sentinel block with every memory you've saved. Skim it first \u2014 if what you're about to save is already there, prefer updating the existing entry over creating a near-duplicate.
|
|
610
|
-
|
|
611
|
-
For the full JSON:
|
|
612
|
-
|
|
613
|
-
\`\`\`bash
|
|
614
|
-
curl -sS 'http://localhost:18800/api/memory?agent=atlas'
|
|
615
|
-
\`\`\`
|
|
616
|
-
|
|
617
|
-
### Remove
|
|
618
|
-
|
|
619
|
-
\`\`\`bash
|
|
620
|
-
curl -sS -X DELETE 'http://localhost:18800/api/memory/no-mock-db?agent=atlas'
|
|
621
|
-
\`\`\`
|
|
622
|
-
|
|
623
|
-
## Structuring the body
|
|
624
|
-
|
|
625
|
-
For **feedback** memories specifically, structure the body so future-you can judge edge cases instead of blindly obeying the rule:
|
|
626
|
-
|
|
627
|
-
\`\`\`
|
|
628
|
-
<the rule itself, one line>
|
|
629
|
-
|
|
630
|
-
Why: <the reason \u2014 often a past incident, a strong preference>
|
|
631
|
-
How to apply: <when/where this guidance kicks in>
|
|
632
|
-
\`\`\`
|
|
633
|
-
|
|
634
|
-
That's the same shape Claude Code's own memory system uses. Keeps the memory useful even when context shifts.
|
|
635
|
-
|
|
636
|
-
## Deduplication
|
|
637
|
-
|
|
638
|
-
Before saving, scan the AGENTX-MEMORY section of your CLAUDE.md. If a similar entry exists, prefer updating it over creating a new one \u2014 the index gets noisy otherwise.
|
|
639
|
-
`;var Be=class{registry;memoryStore;states=new Map;log;constructor(e,t=console.error.bind(console,"[heartbeat]"),n){this.registry=e,this.log=t,this.memoryStore=n}register(e,t){if(!t.enabled)return;this.stop(e);let n={agentId:e,config:t,runCount:0,errors:0},s=(t.intervalMinutes||30)*60*1e3;n.timer=setInterval(()=>{this.runHeartbeat(n).catch(i=>{this.log(`[${e}] heartbeat error: ${i.message}`),n.errors++})},s),this.states.set(e,n),this.log(`Registered heartbeat for "${e}" every ${t.intervalMinutes}min`)}stop(e){let t=this.states.get(e);t?.timer&&(clearInterval(t.timer),t.timer=void 0),this.states.delete(e)}stopAll(){for(let[e]of this.states)this.stop(e)}async runHeartbeat(e){let{agentId:t,config:n}=e;this.log(`[${t}] heartbeat running...`),e.lastRun=new Date,e.runCount++;let s=n.channel||"heartbeat";try{let i=n.prompt;if(this.memoryStore){let o=this.memoryStore.buildRecallContext(t);o&&(i=`${o}
|
|
640
|
-
|
|
641
|
-
${i}`)}let r=await this.registry.execute({message:i,agentId:t,context:{channel:s,sender:"system:heartbeat",chatId:`heartbeat:${t}`}});r.error?(this.log(`[${t}] heartbeat error: ${r.error}`),e.errors++):this.log(`[${t}] heartbeat completed (${r.duration}ms, ${r.content.length} chars)`)}catch(i){this.log(`[${t}] heartbeat failed: ${i.message}`),e.errors++}}async trigger(e){let t=this.states.get(e);if(!t){this.log(`[${e}] no heartbeat registered`);return}await this.runHeartbeat(t)}list(){return Array.from(this.states.values()).map(e=>({agentId:e.agentId,intervalMinutes:e.config.intervalMinutes,lastRun:e.lastRun,runCount:e.runCount,errors:e.errors}))}};var ge=class{services=[];log;constructor(e,t=console.error.bind(console,"[services]")){this.log=t,this.compile(e),this.log(`${this.services.length} service(s) loaded`)}reload(e){return this.compile(e),this.log(`Services reloaded \u2014 ${this.services.length} active`),{count:this.services.length}}compile(e){let t=[];for(let[n,s]of Object.entries(e)){let i={def:{...s,id:n},patterns:[]};for(let r of s.triggers)try{i.patterns.push({regex:new RegExp(r.pattern,"i"),channel:r.channel})}catch(o){this.log(`Invalid regex in service "${n}": ${r.pattern} \u2014 ${o.message}`)}i.patterns.length>0&&t.push(i)}this.services=t}match(e,t,n){for(let s of this.services){if(s.def.allowedContacts?.length){let i=t.replace(/[^0-9]/g,"");if(!s.def.allowedContacts.some(o=>{let a=o.replace(/[^0-9]/g,"");return i.includes(a)||a.includes(i)}))continue}for(let i of s.patterns){if(i.channel&&i.channel!==n)continue;let r=e.match(i.regex);if(r)return z.cat("agent",`Service match: "${s.def.name}" (trigger: ${i.regex.source})`),{service:s.def,trigger:i.regex.source,captured:r[0]}}}return null}async execute(e,t,n,s){this.log(`Executing service "${e.name}" -> agent "${e.agent}"`);try{let i=await t.execute({message:e.prompt,agentId:e.agent,context:{channel:n.channel,sender:n.sender,chatId:`service:${e.id}:${n.chatId}`}});if(i.error){this.log(`Service "${e.name}" failed: ${i.error}`),await s(`Service "${e.name}" encountered an error: ${i.error}`);return}i.content&&await s(i.content),this.log(`Service "${e.name}" completed in ${i.duration}ms`)}catch(i){this.log(`Service "${e.name}" threw: ${i.message}`),await s(`Service error: ${i.message}`)}}getScheduledServices(){return this.services.filter(e=>e.def.schedule).map(e=>e.def)}list(){return this.services.map(e=>({id:e.def.id,name:e.def.name,triggers:e.patterns.length,agent:e.def.agent,scheduled:!!e.def.schedule}))}};var Ge=class{employees=new Map;projects=new Map;constructor(e){for(let[t,n]of Object.entries(e.orgChart)){let s=e.roles[n.role];if(!s)throw new Error(`Org chart references unknown role "${n.role}" for agent "${t}"`);this.employees.set(t,{agentId:t,role:s,roleKey:n.role,reportsTo:n.reportsTo,schedule:n.schedule,utilizationTarget:n.utilizationTarget})}for(let t of this.employees.values())if(t.reportsTo&&!this.employees.has(t.reportsTo))throw new Error(`Agent "${t.agentId}" reports to unknown agent "${t.reportsTo}"`);for(let t of this.employees.values()){let n=new Set,s=t.agentId;for(;s;){if(n.has(s))throw new Error(`Reporting cycle detected involving "${t.agentId}"`);n.add(s),s=this.employees.get(s)?.reportsTo}}for(let t of e.projects??[]){if(t.pm&&!this.employees.has(t.pm))throw new Error(`Project "${t.id}" lists unknown PM "${t.pm}"`);this.projects.set(t.id,t)}}get(e){return this.employees.get(e)}all(){return[...this.employees.values()]}reportsTo(e){return this.employees.get(e)?.reportsTo}directReports(e){return[...this.employees.values()].filter(t=>t.reportsTo===e).map(t=>t.agentId)}chainOfCommand(e){let t=[],n=e;for(;n&&!t.includes(n);)t.push(n),n=this.employees.get(n)?.reportsTo;return t}pmFor(e){if(e)return this.projects.get(e)?.pm}escalationChain(e){return this.chainOfCommand(e).slice(1)}canHandle(e,t,n){return this.employees.size===0?!0:this.employees.has(e)}};var Jn={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};function yt(c,e){let n=new Intl.DateTimeFormat("en-US",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(c),s=(n.find(a=>a.type==="weekday")?.value||"sun").toLowerCase().slice(0,3),i=n.find(a=>a.type==="hour")?.value||"00",r=n.find(a=>a.type==="minute")?.value||"00";return{hour:parseInt(i,10)%24,minute:parseInt(r,10),dow:Jn[s]??0}}function ne(c){let[e,t]=c.split(":").map(Number);return e*60+t}function bt(c,e){return c.days.some(t=>Jn[t]===e)}function Oi(c,e,t){let{hour:n,minute:s,dow:i}=yt(e,t);if(!bt(c,i))return!1;let r=n*60+s,o=ne(c.start),a=ne(c.end);if(r<o||r>=a)return!1;if(c.lunch){let l=ne(c.lunch.start),d=ne(c.lunch.end);if(r>=l&&r<d)return!1}return!0}var Ue=class{constructor(e,t){this.org=e;this.config=t}isOnClock(e,t=new Date){let n=this.org.get(e);return n?Oi(n.schedule,t,this.config.timezone):!1}isDayStart(e,t=new Date){let n=this.org.get(e);if(!n)return!1;let{hour:s,minute:i,dow:r}=yt(t,this.config.timezone);if(!bt(n.schedule,r))return!1;let o=ne(n.schedule.start);return s*60+i===o}isDayEnd(e,t=new Date){let n=this.org.get(e);if(!n)return!1;let{hour:s,minute:i,dow:r}=yt(t,this.config.timezone);if(!bt(n.schedule,r))return!1;let o=ne(n.schedule.end);return s*60+i===o}clockedInAgents(e=new Date){return this.org.all().filter(t=>this.isOnClock(t.agentId,e)).map(t=>t.agentId)}};var Fe=class{constructor(e,t,n,s){this.router=e;this.org=t;this.config=n;this.log=s}async postToMain(e,t){let n=this.config.mainChannel;try{await this.router.sendOutbound({channel:n.channel,chatId:n.chatId,text:e,agentId:t,accountId:n.accountId})}catch(s){this.log(`[business] postToMain failed: ${s.message}`)}}async escalate(e,t,n){let s=this.org.chainOfCommand(e).slice(1),i=s.length?s.slice(0,1):[],r=`\u26A0\uFE0F **Escalation from ${e}** \u2014 ${t}
|
|
642
|
-
|
|
643
|
-
${n}`;if(!i.length){await this.postToMain(r,e);return}await this.postToMain(`${r}
|
|
644
|
-
|
|
645
|
-
cc: ${i.map(o=>`@${o}`).join(" ")}`,e)}};import{writeFileSync as Di,existsSync as zn,mkdirSync as Ni,readFileSync as Li}from"fs";import{resolve as wt}from"path";function kt(){return new Date().toISOString().slice(0,10)}var He=class{constructor(e,t,n){this.org=e;this.schedule=t;this.log=n;this.dir=wt(process.cwd(),".agentx/kpi"),zn(this.dir)||Ni(this.dir,{recursive:!0}),this.stats=this.loadOrInit()}stats;dir;onClockTick=new Map;loadOrInit(){let e=wt(this.dir,`${kt()}.json`);if(zn(e))try{return JSON.parse(Li(e,"utf-8"))}catch{}let t={};for(let n of this.org.all())t[n.agentId]={tasksCompleted:0,timeLoggedSeconds:0,onClockSeconds:0,blockers:0,utilization:0};return{date:kt(),perAgent:t}}tick(){let e=Date.now();for(let t of this.org.all()){if(!this.schedule.isOnClock(t.agentId)){this.onClockTick.delete(t.agentId);continue}let n=this.onClockTick.get(t.agentId);if(n){let s=Math.min(e-n,12e4)/1e3,i=this.stats.perAgent[t.agentId];i&&(i.onClockSeconds+=s)}this.onClockTick.set(t.agentId,e)}this.recomputeUtil(),this.persist()}recordTaskCompletion(e){let t=this.stats.perAgent[e.agentId];t&&(t.tasksCompleted+=1,t.timeLoggedSeconds+=e.durationSeconds,this.recomputeUtil(),this.persist())}recordBlocker(e){let t=this.stats.perAgent[e];t&&(t.blockers+=1,this.persist())}recomputeUtil(){for(let e of Object.values(this.stats.perAgent))e.utilization=e.onClockSeconds>0?Math.min(1,e.timeLoggedSeconds/e.onClockSeconds):0}persist(){this.stats.date!==kt()&&(this.flush(),this.stats=this.loadOrInit());try{Di(wt(this.dir,`${this.stats.date}.json`),JSON.stringify(this.stats,null,2))}catch(e){this.log(`[business] KPI persist failed: ${e.message}`)}}flush(){this.persist()}snapshot(){return JSON.parse(JSON.stringify(this.stats))}dailySummaryText(){let e=[`\u{1F4CA} **Daily report \u2014 ${this.stats.date}**`,""],t=0,n=0;for(let[i,r]of Object.entries(this.stats.perAgent)){t+=r.timeLoggedSeconds,n+=r.onClockSeconds;let o=(r.timeLoggedSeconds/3600).toFixed(1),a=(r.utilization*100).toFixed(0);e.push(`\u2022 **${i}** \u2014 ${r.tasksCompleted} tasks, ${o}h logged, ${a}% utilization${r.blockers?`, ${r.blockers} blocker(s)`:""}`)}e.push("");let s=n>0?(t/n*100).toFixed(0):"0";return e.push(`**Team:** ${(t/3600).toFixed(1)}h logged / ${(n/3600).toFixed(1)}h on-clock \u2192 ${s}% utilization`),e.join(`
|
|
646
|
-
`)}};function R(c,e,t){c.statusCode=e,c.setHeader("Content-Type","application/json"),c.end(JSON.stringify(t))}async function We(c){return new Promise((e,t)=>{let n=[];c.on("data",s=>n.push(s)),c.on("end",()=>{let s=Buffer.concat(n).toString("utf-8");if(!s)return e({});try{e(JSON.parse(s))}catch(i){t(i)}}),c.on("error",t)})}async function Xn(c,e,t,n){if(c==="GET /business/status"){let s=new Date,i=n.schedule.clockedInAgents(s);return R(t,200,{time:s.toISOString(),onClock:i,employees:n.org.all().map(r=>({agentId:r.agentId,role:r.role.title,reportsTo:r.reportsTo,onClock:i.includes(r.agentId)})),kpi:n.kpi.snapshot()}),!0}if(c.startsWith("GET /business/work")){let i=new URL(e.url||"/","http://x").searchParams.get("agent");if(!i)return R(t,400,{error:"?agent= required"}),!0;try{let r=await n.workSource.listOpen(i);R(t,200,{items:r})}catch(r){R(t,500,{error:r.message})}return!0}if(c==="POST /business/claim"){let s=await We(e),{agent:i,itemId:r}=s;if(!i||!r)return R(t,400,{error:"agent and itemId required"}),!0;try{await n.workSource.claim(i,r),R(t,200,{ok:!0})}catch(o){R(t,500,{error:o.message})}return!0}if(c==="POST /business/report"){let s=await We(e);if(!s.itemId||!s.status)return R(t,400,{error:"itemId and status required"}),!0;if(!["in-progress","done","blocked"].includes(s.status))return R(t,400,{error:"status must be in-progress | done | blocked"}),!0;try{await n.workSource.report(s.itemId,{status:s.status,note:s.note,timeSeconds:s.timeSeconds,blocker:s.blocker}),R(t,200,{ok:!0})}catch(i){R(t,500,{error:i.message})}return!0}if(c==="POST /business/escalate"){let s=await We(e);return!s.agent||!s.subject?(R(t,400,{error:"agent and subject required"}),!0):(await n.reporter.escalate(s.agent,s.subject,s.detail||""),n.kpi.recordBlocker(s.agent),R(t,200,{ok:!0}),!0)}if(c==="POST /business/post"){let s=await We(e);return s.text?(await n.reporter.postToMain(s.text,s.agent),R(t,200,{ok:!0}),!0):(R(t,400,{error:"text required"}),!0)}return!1}function vt(c){return`## Business Layer Tools
|
|
647
|
-
|
|
648
|
-
During business hours you'll receive lifecycle prompts ([STANDUP], [WORK], [WRAP]).
|
|
649
|
-
Use these HTTP endpoints on the local daemon to act on them.
|
|
650
|
-
|
|
651
|
-
- **List your work:**
|
|
652
|
-
\`curl -s ${c}/business/work?agent=<your-id>\`
|
|
653
|
-
- **Claim an item** (optional \u2014 some sources no-op):
|
|
654
|
-
\`curl -s -X POST ${c}/business/claim -d '{"agent":"<your-id>","itemId":"<id>"}'\`
|
|
655
|
-
- **Report progress or completion:**
|
|
656
|
-
\`curl -s -X POST ${c}/business/report \\
|
|
657
|
-
-d '{"itemId":"<id>","status":"done","timeSeconds":1800,"note":"shipped"}'\`
|
|
658
|
-
status: \`in-progress\` | \`done\` | \`blocked\`
|
|
659
|
-
- **Escalate a blocker** up the org chart:
|
|
660
|
-
\`curl -s -X POST ${c}/business/escalate \\
|
|
661
|
-
-d '{"agent":"<your-id>","subject":"short","detail":"why it's stuck"}'\`
|
|
662
|
-
- **Post to the main channel** (daily plans, reports):
|
|
663
|
-
\`curl -s -X POST ${c}/business/post \\
|
|
664
|
-
-d '{"agent":"<your-id>","text":"your update"}'\`
|
|
665
|
-
|
|
666
|
-
Your org chart, role, and schedule are fixed in agentx.json under \`business.orgChart\`.
|
|
667
|
-
`}var Bi=6e4,Je=class{constructor(e,t,n,s,i,r,o,a,l){this.config=e;this.org=t;this.schedule=n;this.registry=s;this.reporter=i;this.kpi=r;this.workSource=o;this.daemonBase=a;this.log=l;for(let d of t.all())this.day.set(d.agentId,{})}timer;day=new Map;currentDate=new Date().toISOString().slice(0,10);runningTask=new Set;start(){this.log("[business] day cycle starting"),this.tick().catch(e=>this.log(`[business] tick error: ${e.message}`)),this.timer=setInterval(()=>{this.tick().catch(e=>this.log(`[business] tick error: ${e.message}`))},Bi)}stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,this.kpi.flush()}async tick(){let e=new Date,t=e.toISOString().slice(0,10);if(t!==this.currentDate){this.currentDate=t;for(let n of this.day.keys())this.day.set(n,{})}this.kpi.tick();for(let n of this.org.all()){let s=this.day.get(n.agentId)||{};if(this.day.set(n.agentId,s),!this.runningTask.has(n.agentId)){if(this.schedule.isDayStart(n.agentId,e)&&!s.standupFiredAt){s.standupFiredAt=Date.now(),this.fireStandup(n.agentId).catch(i=>this.log(`[business] standup err: ${i.message}`));continue}if(this.schedule.isDayEnd(n.agentId,e)&&!s.wrapFiredAt){s.wrapFiredAt=Date.now(),this.fireWrap(n.agentId).catch(i=>this.log(`[business] wrap err: ${i.message}`));continue}this.schedule.isOnClock(n.agentId,e)&&(s.lastWorkTickAt?(Date.now()-s.lastWorkTickAt)/6e4:1/0)>=this.config.workTickMinutes&&(s.lastWorkTickAt=Date.now(),this.fireWorkTick(n.agentId).catch(r=>this.log(`[business] work-tick err: ${r.message}`)))}}}roleContext(e){let t=this.org.get(e);if(!t)return"";let n=t.reportsTo?`reporting to ${t.reportsTo}`:"(no manager \u2014 top of org chart)",s=t.role.responsibilities.length?`
|
|
668
|
-
Responsibilities:
|
|
669
|
-
${t.role.responsibilities.map(r=>`- ${r}`).join(`
|
|
670
|
-
`)}`:"",i=t.role.sopPath?`
|
|
671
|
-
SOP: @${t.role.sopPath}`:"";return`You are ${e}, role: ${t.role.title} ${n}.${s}${i}
|
|
672
|
-
|
|
673
|
-
${vt(this.daemonBase)}`}async runLifecycle(e,t){if(this.runningTask.has(e))return;this.runningTask.add(e);let n=Date.now();try{let s=await this.registry.execute({message:t,agentId:e,context:{channel:"business",chatId:`day-cycle:${this.currentDate}:${e}`}}),i=Math.round((s.duration??Date.now()-n)/1e3);return s.error||this.kpi.recordTaskCompletion({agentId:e,durationSeconds:i,success:!0,channel:"business"}),s.content}finally{this.runningTask.delete(e)}}async fireStandup(e){this.log(`[business] STANDUP \u2192 ${e}`);let n=`${this.roleContext(e)}
|
|
674
|
-
|
|
675
|
-
[STANDUP] It's the start of your work day.
|
|
676
|
-
1. Call GET /business/work?agent=${e} to see your open work items.
|
|
677
|
-
2. Pick your top 3 for today, in priority order.
|
|
678
|
-
3. Post your plan to the main channel via POST /business/post \u2014 keep it to 4-6 short lines.
|
|
679
|
-
4. Flag any blockers via POST /business/escalate.`;if(await this.runLifecycle(e,n)){let i=this.day.get(e)||{};i.hadWorkToday=!0,this.day.set(e,i)}}async fireWorkTick(e){let t=await this.workSource.listOpen(e).catch(()=>[]);if(!t.length)return;this.log(`[business] WORK-TICK \u2192 ${e} (${t.length} open)`);let s=`${this.roleContext(e)}
|
|
680
|
-
|
|
681
|
-
[WORK] Continue your highest-priority open task.
|
|
682
|
-
- Call GET /business/work?agent=${e} to see what's assigned to you.
|
|
683
|
-
- If you complete one, POST /business/report with status:done and the time you spent.
|
|
684
|
-
- If blocked, POST /business/escalate with a concise blocker description.
|
|
685
|
-
- Then move on to the next item. Keep working until you hit a real stopping point \u2014 don't idle.`;if(await this.runLifecycle(e,s)){let r=this.day.get(e)||{};r.hadWorkToday=!0,this.day.set(e,r)}}async fireWrap(e){if(!(this.day.get(e)||{}).hadWorkToday){this.log(`[business] WRAP skipped for ${e} (no work done today)`);return}this.log(`[business] WRAP \u2192 ${e}`);let s=`${this.roleContext(e)}
|
|
686
|
-
|
|
687
|
-
[WRAP] End of work day. Post a concise daily report to the main channel via POST /business/post:
|
|
688
|
-
- Tasks closed today
|
|
689
|
-
- Time logged (total)
|
|
690
|
-
- Carry-overs to tomorrow
|
|
691
|
-
- Any outstanding blockers
|
|
692
|
-
Keep it under 8 lines.`;await this.runLifecycle(e,s)}};var ze=class{org;schedule;workSource;reporter;kpi;dayCycle;constructor(e,t,n,s,i){this.org=new Ge(e),this.schedule=new Ue(this.org,e),this.workSource=Ft(e,t,i),this.reporter=new Fe(s,this.org,e,i),this.kpi=new He(this.org,this.schedule,i);let[r,o]=t.node.bind.split(":"),a=`http://${r==="0.0.0.0"?"127.0.0.1":r}:${o||"18800"}`;this.dayCycle=new Je(e,this.org,this.schedule,n,this.reporter,this.kpi,this.workSource,a,i)}start(){this.dayCycle.start()}stop(){this.dayCycle.stop()}recordTaskCompletion(e,t,n,s){this.kpi.recordTaskCompletion({agentId:e,durationSeconds:t,success:n,channel:s})}async handleHttp(e,t,n){let s={workSource:this.workSource,org:this.org,schedule:this.schedule,reporter:this.reporter,kpi:this.kpi};return Xn(e,t,n,s)}summary(){let e=this.schedule.clockedInAgents().length;return`Business layer: ${this.org.all().length} employees, ${e} on-clock now`}};var Yn=class{config;registry;router;cron;mesh;hooks;landscape;heartbeat;business;httpServer;webhooks;github;webrtc;botManager;workflowDispatcher;workflowStore;workflowRuns;db=null;loadedPlugins=[];agentMemory=new Mt;contacts;events=new Ee;log;sseClients=new Set;configPath;configWatcher;reloadTimer;constructor(e){let n=new ce("agentx").asConsoleLog();this.log=(...r)=>{n(...r);let o=r.map(a=>typeof a=="string"?a:JSON.stringify(a)).join(" ");this.broadcastSSE("log",o)},this.log("Loading configuration..."),this.configPath=e,this.config=Ve(e),this.contacts=new Le(process.cwd(),this.log);let s=jt(this.config);for(let r of s)this.log(` \u26A0 ${r}`);let[,i]=this.config.node.bind.split(":");Ut(this.config.agents,i||"19900",this.log),this.hooks=new At,Ye(process.cwd(),this.hooks),this.landscape=new le(this.config),this.registry=new _t(this.config,this.log),Rt(this.registry),this.registry.setLandscape(this.landscape),this.heartbeat=new Be(this.registry,this.log);for(let[r,o]of Object.entries(this.config.agents))o.heartbeat?.enabled&&this.heartbeat.register(r,o.heartbeat);if(this.router=new oe(this.registry,this.config,this.hooks,this.log),Object.keys(this.config.services).length>0){let r=new ge(this.config.services,this.log);this.router.setServiceMatcher(r)}this.cron=new Qe(this.config,this.registry,this.hooks,this.log),this.cron.setNotifyCallback(async(r,o,a,l)=>{let d=`Cron "${r}" failed (${l}x)
|
|
693
|
-
Agent: ${o}
|
|
694
|
-
Error: ${a.slice(0,300)}`;this.log(`[CRON ALERT] ${d}`),this.broadcastSSE("cron-failure",JSON.stringify({jobId:r,agent:o,error:a,consecutiveErrors:l}));let g=this.config.crons[r];if(g?.notify)try{await this.router.sendOutbound({channel:g.notify.channel,chatId:g.notify.chatId,text:`\u{1F534} **Cron "${r}" failed** (${l}x)
|
|
695
|
-
${a.slice(0,300)}`,agentId:o,accountId:g.notify.accountId})}catch(h){this.log(`[CRON ALERT] notify send failed: ${h.message}`)}}),this.config.mesh.enabled&&(this.mesh=new me(this.config,this.log),this.router.setMesh(this.mesh),this.mesh.onPeerChange(r=>{this.events.publish({kind:"mesh",peer:r.peer,healthy:r.healthy,skills:r.skills,delta:r.delta})}),this.registry.setMeshFallback({findPeerWithSkill:r=>this.mesh.findPeerWithSkill(r),sendTask:(r,o,a)=>this.mesh.sendTask(r,o,a),directory:()=>this.mesh.directory()})),this.webhooks=new Oe(this.registry,{},this.log,this.mesh,this.config.webhooks);try{let r=En();this.db=r,r?(On(r),this.log(` SQLite: ${r.name}`)):this.log(" SQLite: not opened (native binding unavailable or path unwritable)")}catch(r){this.log(` SQLite: skipped (${r.message})`)}if(this.config.business?.enabled)try{if(this.business=new ze(this.config.business,this.config,this.registry,this.router,this.log),this.router.setBusiness(this.business),process.env.INTENT_PM_GATE_ENABLED==="true"||process.env.INTENT_PM_GATE_ENABLED==="1"){let r=this.business.org,o=this.config.agents;Ot({pmFor:a=>r.pmFor(a),canHandle:(a,l,d)=>r.canHandle(a,l,d)?Bn(o[a],d):!1,withinDelegationBudget:(a,l,d)=>Gn(_(),o[a],a,l,d)}),this.log(" Ledger governance: PM gate + capability + delegation-depth ENABLED")}}catch(r){this.log(`[business] initialization failed: ${r.message}`)}}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("");try{if(["telegram","slack","whatsapp","discord","gitlab","github","workflow","cron","mesh"].some(o=>E(o)!=="off")){let o=_().cleanupOrphanedDispatches("daemon-restart");o>0&&this.log(` Ledger: cleaned up ${o} orphaned in-flight dispatch(es) from previous process`)}}catch(r){this.log(` Ledger orphan-cleanup failed: ${r?.message??r}`)}try{let r=new Set(["telegram","whatsapp","discord","slack","gitlab","github"]);this.loadedPlugins=await ft({config:this.config,agents:new Map(Object.entries(this.config.agents)),log:this.log,isChannelNameTaken:o=>r.has(o),daemonVersion:process.env.npm_package_version}),this.loadedPlugins.length>0&&this.log(` Plugins: ${this.loadedPlugins.length} loaded \u2014 ${this.loadedPlugins.map(o=>o.manifest.name).join(", ")}`)}catch(r){this.log(` Plugins: loader threw (${r?.message??r}) \u2014 continuing without plugins`),this.loadedPlugins=[]}await this.startChannels();for(let r of this.loadedPlugins)for(let o of r.channels)try{this.router.addChannel(o),await o.start(),this.log(` Plugin channel: ${o.name} (from ${r.manifest.name})`)}catch(a){this.log(` Plugin channel "${o.name}" failed to start: ${a?.message??a}`)}await this.cron.start(),this.mesh&&await this.mesh.start();let e=this.mesh?.directory().map(r=>({peer:r.peer,healthy:r.healthy,skills:r.skills}))||[];this.landscape.build(e),this.log(` Landscape: built for ${Object.keys(this.config.agents).length} agents`),this.scheduleMidnightHook();try{let r=new Date(Date.now()-864e5).toISOString().slice(0,10),o=this.registry.getTokenTracker().catchUpTokenCosts(r);o.length>0&&this.log(` Cost tracking: caught up ${o.length} missed day${o.length===1?"":"s"} (${o[0]}${o.length>1?` \u2192 ${o[o.length-1]}`:""})`)}catch(r){this.log(` Cost tracking: catch-up failed (non-fatal): ${r.message}`)}this.business&&(this.business.start(),this.log(` ${this.business.summary()}`)),await this.startHttpApi(),this.log(""),this.log(" Agents:");for(let r of this.registry.list())this.log(` ${r.id} (${r.tier}) \u2192 ${r.workspace}`);this.installAgentMemorySurface(),this.installAgentMcpConfig();let t=this.cron.list();if(t.length){this.log(""),this.log(" Cron Jobs:");for(let r of t){let o=r.enabled?"enabled":"disabled";this.log(` ${r.id} [${o}] \u2192 ${r.agent} (${r.schedule})`)}}if(this.mesh){this.log(""),this.log(" Mesh Peers:");for(let r of this.mesh.directory()){let o=r.healthy?"\u2713":"\u2717";this.log(` ${o} ${r.peer} (${r.peerUrl})`)}}process.env.AGENTX_AUTO_RELOAD!=="false"&&this.startConfigWatcher();try{let r=this.registry.pruneTaskHistory();r>0&&this.log(` Pruned ${r} old task-history folder(s)`)}catch{}try{if(this.db){let r=jn(this.db,90),o=r.taskHistory+r.rotations+r.routeTraces;o>0&&this.log(` Pruned ${o} old SQLite row(s) (task_history=${r.taskHistory}, rotations=${r.rotations}, route_traces=${r.routeTraces})`)}}catch(r){this.log(` SQLite prune skipped: ${r?.message??r}`)}try{let r=this.registry.hydrateLastSummariesFromDisk();r>0&&this.log(` Loaded last-activity summaries for ${r} agent(s)`)}catch{}this.log(""),this.log(" Ready."),this.log("");let n=B(process.cwd(),".agentx/daemon.pid");Kn(Hi(n),{recursive:!0}),qn(n,String(process.pid)),this.log(` PID: ${process.pid} (${n})`),process.on("uncaughtException",r=>{this.log(`UNCAUGHT EXCEPTION: ${r.message}`),this.log(r.stack||"")}),process.on("unhandledRejection",r=>{this.log(`UNHANDLED REJECTION: ${r}`)});let s=!1,i=async r=>{s||(s=!0,this.log(`
|
|
696
|
-
Received ${r}, shutting down gracefully...`),await this.stop())};process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("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{let t=parseInt(process.env.AGENTX_DRAIN_TIMEOUT_MS||"300000",10),n=Date.now(),s=()=>this.registry.getActiveTaskCount()+this.router.getActiveMeshForwardCount(),i=s();if(i>0){for(this.log(` Draining ${i} in-flight task(s) \u2014 local=${this.registry.getActiveTaskCount()}, mesh-forwards=${this.router.getActiveMeshForwardCount()} (max ${Math.round(t/1e3)}s)...`);i>0&&Date.now()-n<t;)await new Promise(o=>setTimeout(o,500)),i=s();let r=Date.now()-n;i===0?this.log(` Drain complete (${r}ms)`):this.log(` Drain timeout after ${r}ms \u2014 ${i} task(s) still in flight (local=${this.registry.getActiveTaskCount()}, mesh-forwards=${this.router.getActiveMeshForwardCount()}), exiting anyway`)}}catch(t){this.log(` Drain error: ${t.message}`)}try{this.router.flushPersistence?.()}catch(t){this.log(` Router flush error: ${t.message}`)}try{this.log(" Stopping crons (saving last run times)..."),await this.cron.stop()}catch{}try{this.log(" Stopping heartbeats..."),this.heartbeat.stopAll()}catch{}try{this.business&&(this.log(" Stopping business layer..."),this.business.stop())}catch{}try{this.mesh&&(this.log(" Stopping mesh..."),await this.mesh.stop())}catch{}try{this.botManager&&this.botManager.shutdown()}catch{}try{this.webrtc&&this.webrtc.shutdown()}catch{}for(let t of this.loadedPlugins)try{await t.dispose()}catch(n){this.log(` Plugin dispose error (${t.manifest.name}): ${n?.message??n}`)}if(this.midnightTimer&&clearTimeout(this.midnightTimer),this.reloadTimer&&clearTimeout(this.reloadTimer),this.configWatcher)try{this.configWatcher.close()}catch{}this.httpServer&&this.httpServer.close();try{let t=B(process.cwd(),".agentx/daemon.pid");he(t)&&Ui(t)}catch{}this.log(` Shutdown complete (${Date.now()-e}ms)`),process.exit(0)}midnightTimer;startConfigWatcher(){let e=this.configPath||B(process.cwd(),"agentx.json");if(he(e))try{this.configWatcher=Fi(e,{persistent:!1},t=>{t==="change"&&(this.reloadTimer&&clearTimeout(this.reloadTimer),this.reloadTimer=setTimeout(()=>{this.reload().catch(n=>this.log(`[reload] failed: ${n?.message||n}`))},500))}),this.log(` Watching ${e} for config changes`)}catch(t){this.log(` Config watcher failed to start: ${t.message}`)}}async reload(){let e;try{e=Ve(this.configPath)}catch(u){return this.log(`[reload] config invalid, keeping previous: ${u.message}`),{applied:[],restartRequired:[],error:u.message}}let t=[],n=[];if(JSON.stringify(this.config.crons)!==JSON.stringify(e.crons))try{await this.cron.stop(),this.cron=new Qe(e,this.registry,this.hooks,this.log),this.cron.setNotifyCallback(async(u,f,m,y)=>{this.log(`[CRON ALERT] Cron "${u}" failed (${y}x) \u2014 ${m.slice(0,200)}`),this.broadcastSSE("cron-failure",JSON.stringify({jobId:u,agent:f,error:m,consecutiveErrors:y}));let b=e.crons[u];if(b?.notify)try{await this.router.sendOutbound({channel:b.notify.channel,chatId:b.notify.chatId,text:`Cron "${u}" failed (${y}x)
|
|
697
|
-
${m.slice(0,300)}`,agentId:f,accountId:b.notify.accountId})}catch(w){this.log(`[CRON ALERT] notify send failed: ${w.message}`)}}),await this.cron.start(),t.push("crons")}catch(u){this.log(`[reload] cron reload failed: ${u.message}`)}let s=this.config.channels?.telegram,i=e.channels?.telegram,r=JSON.stringify(s)!==JSON.stringify(i),o=!1;if(r&&i?.enabled){let u=this.router.getChannel("telegram");if(u)try{let f=await u.reloadAccounts(i.accounts,i.policy);this.router.updateConfig(e);let m=[];f.added.length&&m.push(`+${f.added.join(",")}`),f.removed.length&&m.push(`-${f.removed.join(",")}`),f.tokenChanged.length&&m.push(`~${f.tokenChanged.join(",")}`),t.push(m.length?`telegram(${m.join(" ")})`:"telegram"),o=!0}catch(f){this.log(`[reload] telegram hot-reload failed: ${f.message}`)}}else r&&!i?.enabled&&s?.enabled||r&&i?.enabled&&!s?.enabled?o=!1:r||(o=!0);if(JSON.stringify(this.config.providers)!==JSON.stringify(e.providers))try{this.registry.setProviders(e.providers),t.push("providers")}catch(u){this.log(`[reload] providers hot-reload failed: ${u.message}`)}let a=this.config.mesh,l=e.mesh,d=JSON.stringify(a)!==JSON.stringify(l),g=!d;if(d&&l.enabled&&a.enabled&&this.mesh&&!(JSON.stringify(a.healthCheck)!==JSON.stringify(l.healthCheck)))try{let f=await this.mesh.reloadPeers(e),m=[];f.added.length&&m.push(`+${f.added.join(",")}`),f.removed.length&&m.push(`-${f.removed.join(",")}`),f.updated.length&&m.push(`~${f.updated.join(",")}`),t.push(m.length?`mesh(${m.join(" ")})`:"mesh"),g=!0}catch(f){this.log(`[reload] mesh hot-reload failed: ${f.message}`)}if(JSON.stringify(this.config.services)!==JSON.stringify(e.services))try{let u=this.router.getServiceMatcher();if(u){let{count:f}=u.reload(e.services);t.push(`services(${f})`)}else if(Object.keys(e.services).length>0){let f=new ge(e.services,this.log);this.router.setServiceMatcher(f),t.push(`services(${Object.keys(e.services).length})`)}}catch(u){this.log(`[reload] services hot-reload failed: ${u.message}`)}try{let u=this.hooks.size?.()??0;this.hooks.clear(),Ye(process.cwd(),this.hooks);let f=this.hooks.size?.()??0;u!==f&&t.push(`hooks(${f})`)}catch(u){this.log(`[reload] hooks reload failed: ${u.message}`)}if(JSON.stringify(this.config.business)!==JSON.stringify(e.business)||JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){try{this.landscape=new le(e),this.registry.setLandscape(this.landscape),t.push("landscape")}catch(u){this.log(`[reload] landscape rebuild failed: ${u.message}`)}if(this.mesh&&this.mesh.peerCount()>0)try{let u=await this.mesh.refreshAll(),f=u.filter(m=>m.healthy).length;t.push(`mesh.refresh(${f}/${u.length})`)}catch(u){this.log(`[reload] mesh refresh failed: ${u.message}`)}}if(JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){let u=Object.keys(this.config.agents).sort().join(","),f=Object.keys(e.agents).sort().join(",");u===f&&(this.registry.setConfig(e),t.push("agents.meta"));let m=zi(this.config.agents,e.agents);m.length>0&&n.push(`agents(${m.join(",")})`)}g||n.push("mesh"),JSON.stringify(this.config.node)!==JSON.stringify(e.node)&&n.push("node");let h={...this.config.channels,telegram:void 0},p={...e.channels,telegram:void 0};JSON.stringify(h)!==JSON.stringify(p)?n.push("channels"):r&&!o&&n.push("channels.telegram");{let u=this.contacts.size(),f=this.contacts.reload();f.error?this.log(`[reload] contacts.json invalid: ${f.error}`):f.count!==u&&t.push(`contacts(${f.count})`)}if(JSON.stringify(this.config.webhooks)!==JSON.stringify(e.webhooks))try{this.webhooks.setWebhookEntries(e.webhooks),t.push(`webhooks(${e.webhooks.length})`)}catch(u){this.log(`[reload] webhooks hot-reload failed: ${u.message}`)}return this.config=e,this.router.updateConfig(e),t.length&&this.log(`[reload] applied: ${t.join(", ")}`),n.length?(this.log(`[reload] restart required to apply changes in: ${n.join(", ")}`),this.broadcastSSE("reload-partial",JSON.stringify({applied:t,restartRequired:n}))):t.length&&this.broadcastSSE("reload-complete",JSON.stringify({applied:t})),{applied:t,restartRequired:n}}scheduleMidnightHook(){let e=()=>{let t=new Date,n=t.toLocaleString("en-US",{timeZone:"Africa/Tunis"}),s=new Date(n),i=new Date(s);i.setDate(i.getDate()+1),i.setHours(0,0,5,0);let r=s.getTime()-t.getTime(),o=i.getTime()-r-t.getTime();this.log(` Cost tracking: next run in ${Math.round(o/6e4)}min`),this.midnightTimer=setTimeout(async()=>{await this.runDailyCostReport(),e()},Math.max(o,6e4))};e()}async runDailyCostReport(){let e=new Date(Date.now()-864e5).toISOString().slice(0,10),t=this.registry.getTokenTracker();if(t.hasTokenCostsEntry(e)){this.log(` Cost tracking: ${e} already logged, skipping`);return}let n=t.generateDailyReport(e);if(!n||n.totalTasks===0){this.log(` Cost tracking: no usage for ${e}, skipping`);return}t.appendToTokenCosts(n),this.log(` Cost tracking: ${e} \u2014 ${n.totalTasks} tasks, $${n.totalCost.toFixed(4)} (top: ${n.topAgent} $${n.topCost.toFixed(4)})`)}async startChannels(){if(this.config.channels.telegram.enabled){let e=this.config.channels.telegram.accounts;if(Object.keys(e).length>0){let t=this.config.channels.telegram.policy,n=new K(e,{policy:{allowFrom:t?.allowFrom}},this.log);this.router.addChannel(n);let s=t?.allowFrom?.length??0,i=Object.entries(e).filter(([,r])=>!r.allowFrom&&s===0).length;i>0?this.log(` Telegram: enabled \u2014 WARNING: ${i} account(s) have no allowFrom (global or per-account). All incoming messages will be DROPPED.`):this.log(` Telegram: enabled \u2014 global allowFrom entries: ${s}`)}}if(this.config.channels.whatsapp.enabled){let{setWhatsAppQR:e,setWhatsAppStatus:t}=await import("./whatsapp-state-XMTCSRXU.js"),n=new ve({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes,throttle:{minMsBetweenCalls:this.config.channels.whatsapp.ingest?.throttle?.minMsBetweenCalls,maxCallsPerMinute:this.config.channels.whatsapp.ingest?.throttle?.maxCallsPerMinute},onQR:e,onStatus:t},this.log);this.router.addChannel(n),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 $e({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.slack?.enabled&&this.config.channels.slack.botToken&&this.config.channels.slack.appToken){let e=new Se({botToken:this.config.channels.slack.botToken,appToken:this.config.channels.slack.appToken,agentBinding:this.config.channels.slack.agentBinding},this.log);this.router.addChannel(e),this.log(" Slack: enabled")}else this.config.channels.slack?.enabled&&this.log(" Slack: enabled in config but missing botToken/appToken \u2014 skipped");if(this.config.channels.gitlab?.enabled&&this.config.channels.gitlab.token){let e=new Te({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,knownAgentIds:Object.keys(this.config.agents)},this.log,this.hooks);this.mesh&&(e.setReactForwarder(async(t,n,s,i,r,o)=>{let a=this.mesh.directory().find(d=>d.peer===t&&d.healthy);if(!a){this.log(`[gitlab] react forward: peer "${t}" not found or unhealthy`);return}let l=`${a.peerUrl}/gitlab/react`;try{let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,noteId:r,agentId:o})}),g=await d.text().catch(()=>"");this.log(`[gitlab] react forward -> ${l} : ${d.status} ${g.slice(0,200)}`)}catch(d){this.log(`[gitlab] react forward FAILED -> ${l} : ${d.message}`)}}),e.setSendNoteForwarder(async(t,n,s,i,r,o)=>{let a=this.mesh.directory().find(d=>d.peer===t&&d.healthy);if(!a)return this.log(`[gitlab] send-note forward: peer "${t}" not found or unhealthy`),"";let l=`${a.peerUrl}/gitlab/send-note`;try{let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:r,text:o})}),g=await d.json().catch(()=>({}));return this.log(`[gitlab] send-note forward -> ${l} : ${d.status} noteId=${g.noteId||"?"}`),g.noteId||""}catch(d){return this.log(`[gitlab] send-note forward FAILED -> ${l} : ${d.message}`),""}}),e.setLogTimeForwarder(async(t,n,s,i,r,o)=>{let a=this.mesh.directory().find(d=>d.peer===t&&d.healthy);if(!a){this.log(`[gitlab] log-time forward: peer "${t}" not found or unhealthy`);return}let l=`${a.peerUrl}/gitlab/log-time`;try{let d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:r,durationMs:o})}),g=await d.text().catch(()=>"");this.log(`[gitlab] log-time forward -> ${l} : ${d.status} ${g.slice(0,160)}`)}catch(d){this.log(`[gitlab] log-time forward FAILED -> ${l} : ${d.message}`)}})),this.router.addChannel(e),this.log(` GitLab: enabled (${this.config.channels.gitlab.routes.length} project routes, webhook :${this.config.channels.gitlab.webhookPort})`)}if(this.config.channels.github?.enabled){let e=this.config.channels.github;this.github=new xe({token:e.token,tokenFile:e.tokenFile,appId:e.appId,clientId:e.clientId,privateKeyFile:e.privateKeyFile,webhookSecret:e.webhookSecret,routes:e.routes,agentMappings:e.agentMappings},this.log),this.mesh&&this.github.setSendCommentForwarder(async(t,n,s,i,r)=>{let o=this.mesh.directory().find(l=>l.peer===t&&l.healthy);if(!o)return this.log(`[github] send-comment forward: peer "${t}" not found or unhealthy`),"";let a=`${o.peerUrl}/github/send-comment`;try{let l=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:n,issueNumber:s,agentId:i,text:r})}),d=await l.json().catch(()=>({}));return this.log(`[github] send-comment forward -> ${a} : ${l.status} commentId=${d.commentId||"?"}`),d.commentId||""}catch(l){return this.log(`[github] send-comment forward FAILED -> ${a} : ${l.message}`),""}}),this.router.addChannel(this.github),this.log(` GitHub: enabled (${e.routes.length} repo routes)`)}if(this.config.channels.webrtc?.enabled){let e=this.config.channels.webrtc;if(this.webrtc=new Ae(this.config.node.name,e.allowedCallers,this.log),this.mesh&&this.webrtc.setForwarder(async(t,n)=>{try{return await this.mesh.sendSignal(t,n)}catch(s){return this.log(`[webrtc] forward to "${t}" failed: ${s.message}`),!1}}),e.ringNotify.length>0){let t=e.callUrlBase||`http://${this.config.node.bind}`;this.webrtc.setRingHandler(async n=>{let s=`${t}/call?to=${encodeURIComponent(n.from)}&callId=${encodeURIComponent(n.callId)}`,i=`\u{1F4DE} ${n.from} is calling \u2014 tap to join: ${s}`;for(let r of e.ringNotify)try{await this.router.sendOutbound({channel:r.channel,chatId:r.chatId,text:i,parseMode:"plain",...r.accountId?{accountId:r.accountId}:{}})}catch(o){this.log(`[webrtc] ring notify via ${r.channel}:${r.chatId} failed: ${o.message}`)}})}if(e.bot.enabled){let t=e.bot,n=[...e.stunServers.map(s=>({urls:s})),...e.turnServers];this.botManager=new Pe({broker:this.webrtc,iceServers:n,whisperBackend:t.whisperBackend,whisperModel:t.whisperModel,whisperLanguage:t.whisperLanguage,mlxBinary:t.mlxBinary,maxCallMinutes:t.maxCallMinutes,log:this.log,onTranscript:async({invite:s,text:i,durationMs:r})=>{let o=t.transcriptChannel;if(!o)return;let a=`[${new Date().toLocaleTimeString()} \u2022 ${(r/1e3).toFixed(1)}s \u2022 ${s.target}]`;try{await this.router.sendOutbound({channel:o.channel,chatId:o.chatId,text:`${a}
|
|
698
|
-
${i}`,parseMode:"plain",...o.accountId?{accountId:o.accountId}:{}})}catch(l){this.log(`[bot-manager] transcript send via ${o.channel}:${o.chatId} failed: ${l.message}`)}}}),this.log(` WebRTC bot: enabled (whisper=${t.whisperBackend}, default-agent=${t.defaultAgentId||"(none)"}, transcript=${t.transcriptChannel?`${t.transcriptChannel.channel}:${t.transcriptChannel.chatId}`:"(none)"})`)}this.log(` WebRTC signaling: enabled (stun=${e.stunServers.length}, turn=${e.turnServers.length}, allowedCallers=${e.allowedCallers.length||"all"}, ringNotify=${e.ringNotify.length}, bot=${e.bot.enabled?"on":"off"})`)}await this.bootWorkflowEngine(),this.registry.getSessionStore().setAdapterResolver(e=>this.router.getChannel(e)),await this.router.startAll()}async bootWorkflowEngine(){let e=this.config.workflows;if(!e?.enabled){this.log(" Workflows: disabled (set workflows.enabled to turn the engine on)");return}let t=new Dt({baseDir:B(process.cwd(),e.dir)}),n=new Nt({baseDir:B(process.cwd(),e.dir),nodeId:this.config.node.id}),s={};for(let S of this.router.getChannelNames()){let T=this.router.getChannel(S);T&&(s[S]=T)}let i={execute:async S=>{let T=Date.now();try{let x=S.workflowRunId?`workflow:${S.workflowRunId}`:"workflow:adhoc",C=await this.registry.execute({agentId:S.agentId,message:S.message,workflowRunId:S.workflowRunId,timeoutMinutes:S.timeoutMinutes,context:{channel:"workflow",chatId:x,sender:"workflow"}});return{content:C.content??"",error:C.error,taskId:`wf-${S.workflowRunId??"na"}-${T.toString(36)}`,durationMs:Date.now()-T}}catch(x){return{content:"",error:x.message}}}},r=this.mesh?{forwardTransition:async(S,T)=>{let x=this.mesh.directory().find(A=>A.peer===S&&A.healthy);if(!x){this.log(`[workflows] forward to "${S}" skipped \u2014 peer not found or unhealthy`);return}let C=`${x.peerUrl}/workflow/event`;try{let A=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:T})});A.ok||this.log(`[workflows] forward ${C} -> ${A.status}`)}catch(A){this.log(`[workflows] forward ${C} failed: ${A.message}`)}},broadcastTrigger:async S=>{let T=this.mesh.directory().filter(C=>C.healthy);if(T.length===0)return;let x=this.config.node.id;this.log(`[workflows/mesh] broadcasting trigger source="${S.trigger.source}" chat="${S.trigger.chat??"*"}" -> ${T.length} peer(s): ${T.map(C=>C.peer).join(", ")}`),await Promise.allSettled(T.map(async C=>{let A=`${C.peerUrl}/workflow/event`;try{let O=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"trigger",fromPeer:x,payload:S}),signal:AbortSignal.timeout(5e3)});O.ok||this.log(`[workflows/mesh] broadcastTrigger ${C.peer} -> ${O.status}`)}catch(O){this.log(`[workflows/mesh] broadcastTrigger ${C.peer} failed: ${O.message}`)}}))},forwardChannelSend:async S=>{let T=this.mesh.directory().filter(N=>N.healthy&&N.channels?.includes(S.channel));if(T.length===0)throw new Error(`no healthy mesh peer hosts channel "${S.channel}"`);let x=T[0],C=`${x.peerUrl}/channel/send`,A=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:AbortSignal.timeout(15e3)});if(!A.ok){let N=await A.text().catch(()=>"");throw new Error(`peer ${x.peer} /channel/send -> ${A.status} ${N.slice(0,200)}`)}return{messageId:(await A.json().catch(()=>({}))).messageId??null}}}:void 0,{ActorStore:o}=await import("./store-BAPDZHXE.js"),{TaskStore:a}=await import("./task-store-RHISEU6V.js"),l=new o,d=new a(e.dir?{baseDir:B(process.cwd(),e.dir)}:void 0),g=process.env.AGENTX_INBOX_BASE_URL||"",h=[],p=s.telegram;if(p?.sendMessage){let{createTelegramTaskRenderer:S}=await import("./telegram-PIYDRM46.js");h.push(S({actors:l,tasks:d,adapter:{sendMessage:p.sendMessage.bind(p),sendWithInlineButtons:p.sendWithInlineButtons?.bind(p)},inboxBaseUrl:g,log:T=>this.log(T)}))}let u=s.whatsapp;if(u?.send){let{createWhatsappTaskRenderer:S}=await import("./whatsapp-PFRDMUMT.js");h.push(S({actors:l,tasks:d,adapter:{send:u.send.bind(u)},inboxBaseUrl:g,log:T=>this.log(T)}))}let f=s.slack;if(f?.send){let{createSlackTaskRenderer:S}=await import("./slack-6P7ZJ32Y.js");h.push(S({actors:l,tasks:d,adapter:{send:f.send.bind(f)},inboxBaseUrl:g,log:T=>this.log(T)}))}let m=h.length?async S=>{for(let T of h)try{await T(S)}catch{}}:void 0,{TimerService:y}=await import("./timers-5LPZN55J.js"),b=new y({baseDir:e.dir?B(process.cwd(),e.dir):void 0,log:S=>this.log(S)}),w=new Lt({store:t,runs:n,nodeId:this.config.node.id,channels:s,agents:i,forwarder:r,actors:l,tasks:d,timers:b,events:this.events,renderUserTask:m,log:S=>this.log(S)});b.start();let v=Bt(w);for(let[S,T]of Object.entries(v))T&&this.hooks.registerHandler(S,`workflows:${S}`,T,50);this.workflowDispatcher=w,this.workflowStore=t,this.workflowRuns=n,this.webhooks.setWorkflowDispatcher(w);let{cronTimers:$,hookSubscribers:I}=Gt({store:t,dispatcher:w,hooks:this.hooks,log:S=>this.log(S)}),k=t.list().length;this.log(` Workflows: enabled (${k} definition${k===1?"":"s"} loaded from ${e.dir}, editor=${e.editor}, cron=${$}, hook=${I})`);try{let{detectConflicts:S}=await import("./conflict-detector-D7VIYPDI.js"),T=S(t.list(),this.config);if(T.length>0){this.log(` Workflows: ${T.length} dispatch conflict(s) detected`);for(let x of T)this.log(` [${x.severity}] ${x.workflowId}: ${x.summary}`),this.log(` \u2192 ${x.suggestion}`)}}catch(S){this.log(` Workflows: conflict-detector failed: ${S.message}`)}}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=Gi(async(s,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){i.writeHead(204),i.end();return}await this.handleHttp(s,i)}),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}`)})}broadcastSSE(e,t){if(this.sseClients.size===0)return;let n=`event: ${e}
|
|
699
|
-
data: ${JSON.stringify({time:new Date().toISOString(),message:t})}
|
|
700
|
-
|
|
701
|
-
`;for(let s of this.sseClients)try{s.write(n)}catch{this.sseClients.delete(s)}}handleSSE(e,t){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"});let n=new URL(e.url||"/",`http://${e.headers.host||"_"}`),i={kinds:_n(n.searchParams.get("type")),workflowId:n.searchParams.get("workflow")||void 0,actor:n.searchParams.get("actor")||void 0,runId:n.searchParams.get("run")||void 0,channel:n.searchParams.get("channel")||void 0},r=this.registry.list(),o=r.filter(l=>l.active>0);t.write(`event: status
|
|
702
|
-
data: ${JSON.stringify({node:this.config.node.name,agents:r.length,active:o.map(l=>({id:l.id,name:l.name,tasks:l.active})),mesh:this.mesh?.directory().map(l=>({peer:l.peer,healthy:l.healthy}))||[]})}
|
|
703
|
-
|
|
704
|
-
`),this.sseClients.add(t);let a=this.events.subscribe(i,l=>{try{t.write(`event: ${l.kind}
|
|
705
|
-
data: ${JSON.stringify(l)}
|
|
706
|
-
|
|
707
|
-
`)}catch{}});e.on("close",()=>{a(),this.sseClients.delete(t)})}handleTaskStream(e,t,n,s){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","X-Accel-Buffering":"no"});let i=!1,r=(l,d)=>{if(!i)try{t.write(`event: ${l}
|
|
708
|
-
data: ${JSON.stringify(d)}
|
|
709
|
-
|
|
710
|
-
`)}catch{i=!0}},o=this.registry.subscribeToTaskOutput(s,l=>r("chunk",{text:l}));if(!o){r("error",{message:"task not found or already evicted"}),t.end();return}if(r("start",{taskId:s,initial:o.initial,done:o.done}),o.done){r("end",{reason:"already finished"}),t.end();return}let a=setInterval(()=>{if(!i)try{t.write(`: ping
|
|
711
|
-
|
|
712
|
-
`)}catch{}},15e3);e.on("close",()=>{i=!0,clearInterval(a),o.unsubscribe()})}handleWebRtcSSE(e,t,n){if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let s=n.searchParams.get("callId"),i=n.searchParams.get("as");if(!s||!i){this.json(t,400,{error:"Missing ?callId= and ?as="});return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*","X-Accel-Buffering":"no"}),t.write(`event: ready
|
|
713
|
-
data: ${JSON.stringify({callId:s,as:i})}
|
|
714
|
-
|
|
715
|
-
`);let r=this.webrtc.subscribe(s,i,t),o=setInterval(()=>{try{t.write(`: ping
|
|
716
|
-
|
|
717
|
-
`)}catch{}},15e3);e.on("close",()=>{clearInterval(o),r()})}serveCallPage(e){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(xn)}async handleHttp(e,t){let n=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),s=n.pathname;try{if(e.method==="GET"&&s==="/events"){this.handleSSE(e,t);return}if(e.method==="GET"&&s==="/webrtc/events"){this.handleWebRtcSSE(e,t,n);return}if(e.method==="POST"&&(s==="/workflow/event"||s==="/workflow/transition")){await this.handleWorkflowEvent(e,t);return}if(e.method==="POST"&&s==="/channel/send"){await this.handleChannelSend(e,t);return}let i=e.method==="GET"&&s.match(/^\/channels\/([^/]+)\/chats$/);if(i){let g=n.searchParams.get("local")==="1";await this.handleChannelChats(t,decodeURIComponent(i[1]),{localOnly:g});return}let r=e.method==="POST"&&s.match(/^\/workflows\/([^/]+)\/run$/);if(r){await this.handleWorkflowManualRun(e,t,decodeURIComponent(r[1]));return}if(s.startsWith("/api/memory")&&await this.handleMemoryApi(e,t,s,n)||s.startsWith("/api/workflows/tasks")&&this.workflowDispatcher&&await this.handleTaskApi(e,t,s))return;if(e.method==="GET"&&s==="/api/workflows/kpis"&&this.workflowDispatcher){let{computeKpis:g}=await import("./task-store-RHISEU6V.js");this.json(t,200,g(this.workflowDispatcher.tasks));return}if(e.method==="GET"&&this.workflowRuns&&this.workflowStore){if(s==="/api/workflows"){this.json(t,200,{workflows:this.workflowStore.list()});return}if(s==="/api/workflows/runs"){let h=Math.max(1,Math.min(500,Number(n.searchParams.get("limit")||50))),p=n.searchParams.get("workflowId")||void 0;this.json(t,200,{runs:this.workflowRuns.list({workflowId:p,limit:h})});return}let g=s.match(/^\/api\/workflows\/runs\/([^\/]+)$/);if(g){let h=this.workflowRuns.get(decodeURIComponent(g[1]));if(!h){this.json(t,404,{error:"run not found"});return}this.json(t,200,{run:h});return}}if(e.method==="POST"&&s==="/api/workflows/editor/chat"&&this.workflowDispatcher){let g;try{g=await Y(e)}catch(v){this.json(t,400,{error:"invalid JSON body",message:v.message});return}let h=Array.isArray(g?.messages)?g.messages:[];if(!h.length){this.json(t,400,{error:"messages array required"});return}let p=h.filter(v=>v&&(v.role==="user"||v.role==="assistant")&&typeof v.content=="string").map(v=>({role:v.role,content:v.content}));if(!p.length){this.json(t,400,{error:"messages must contain at least one {role: 'user'|'assistant', content}"});return}let u=typeof g?.agentId=="string"&&g.agentId?g.agentId:process.env.AGENTX_WORKFLOW_AUTHOR_AGENT||this.registry.list()[0]?.id;if(!u){this.json(t,503,{error:"no authoring agent available \u2014 register an agent or set AGENTX_WORKFLOW_AUTHOR_AGENT"});return}let{buildWorkflowAuthorPrompt:f,extractWorkflowJson:m}=await import("./editor-chat-RVLCKKB7.js"),y=Object.keys(this.workflowDispatcher.channels).sort(),b=this.registry.list().map(v=>({id:v.id,description:v.name})),w=f({messages:p,store:this.workflowStore,actors:this.workflowDispatcher.actors,availableAgents:b,availableChannels:y,currentWorkflow:g?.currentWorkflow});try{let v=await this.registry.execute({agentId:u,message:w,context:{channel:"workflow-editor",chatId:"editor",sender:"editor"}});if(v.error){this.json(t,502,{error:v.error,agentId:u});return}let $=v.content??"",I=m($);this.json(t,200,{reply:$,workflow:I,agentId:u})}catch(v){this.json(t,500,{error:"agent execute failed",message:v.message})}return}if(e.method==="POST"&&s.startsWith("/api/workflows/signal/")&&this.workflowDispatcher){let g=decodeURIComponent(s.replace(/^\/api\/workflows\/signal\//,""));if(!g){this.json(t,400,{error:"signal name required"});return}let h;try{h=await Y(e)}catch(u){this.json(t,400,{error:"invalid JSON body",message:u.message});return}let p=this.workflowDispatcher.emitSignal({name:g,scope:h?.scope,workflowId:h?.workflowId,payload:h?.payload});this.json(t,200,{ok:!0,emission:p});return}if(e.method==="GET"&&s==="/inbox"){let{renderInboxPage:g}=await import("./inbox-BIN2S5XN.js"),h=n.searchParams,p=g({actor:h.get("actor")||void 0});t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(p);return}if(e.method==="GET"&&s==="/processes"){let{renderProcessesPage:g}=await import("./processes-RJ6RDP32.js");t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(g({}));return}let o=e.method==="GET"&&s.match(/^\/t\/([^\/]+)\/(primary|secondary)$/);if(o&&this.workflowDispatcher){let g=decodeURIComponent(o[1]),h=o[2],p=n.searchParams.get("actor")||"anonymous",u=await this.workflowDispatcher.submitTask(g,{action:h,values:{}},p);t.writeHead(u.ok?200:400,{"Content-Type":"text/html; charset=utf-8"}),u.ok?t.end(`<!doctype html><meta charset=utf-8><title>Submitted</title>
|
|
718
|
-
<body style="font-family:system-ui;max-width:520px;margin:48px auto;padding:0 16px;text-align:center">
|
|
719
|
-
<h1 style="color:#27ae60">\u2713 Submitted</h1>
|
|
720
|
-
<p>Your <strong>${h==="primary"?"approval":"rejection"}</strong> has been recorded. You can close this tab.</p>
|
|
721
|
-
<p style="color:#888;font-size:13px">Run <code>${u.runId}</code></p>
|
|
722
|
-
</body>`):t.end(`<!doctype html><meta charset=utf-8><title>Submit failed</title>
|
|
723
|
-
<body style="font-family:system-ui;max-width:520px;margin:48px auto;padding:0 16px;text-align:center">
|
|
724
|
-
<h1 style="color:#c0392b">\u2717 ${u.error}</h1>
|
|
725
|
-
${Array.isArray(u.fieldErrors)&&u.fieldErrors.length?`<p>This task has required fields. Please open the <a href="/inbox?actor=${encodeURIComponent(p)}">inbox</a> instead.</p>`:""}
|
|
726
|
-
</body>`);return}if(e.method==="GET"&&s==="/call"){this.serveCallPage(t);return}if(e.method==="POST"&&s.startsWith("/webhook/")){if(this.github&&e.headers["x-github-event"]){let g=await new Promise(p=>{let u="";e.on("data",f=>u+=f.toString()),e.on("end",()=>p(u)),e.on("error",()=>p(""))}),h;try{(e.headers["content-type"]||"").includes("form-urlencoded")&&g.startsWith("payload=")?h=JSON.parse(decodeURIComponent(g.slice(8))):h=g?JSON.parse(g):{}}catch{h={}}this.log(`[github] webhook body keys: ${Object.keys(h).slice(0,5).join(", ")} | repo: ${h.repository?.full_name||"MISSING"}`),t.writeHead(202,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channel:"github",status:"accepted"})),this.github.handleWebhook(e.headers,h,g).catch(p=>this.log(`[github] webhook handler error: ${p.message}`));return}await this.webhooks.handle(e,t,s);return}let a=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks\/([^/]+)\/stream$/);if(a){this.handleTaskStream(e,t,a[1],a[2]);return}let l=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks$/);if(l){let g=Math.max(1,Math.min(500,parseInt(n.searchParams.get("limit")||"50",10)||50));this.json(t,200,this.registry.listTaskHistory(l[1],g));return}let d=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks\/([^/]+)$/);if(d){let g=this.registry.getTaskRecord(d[1],d[2]);if(!g){this.json(t,404,{error:"not found"});return}this.json(t,200,g);return}if(e.method==="POST"&&(s==="/v1/chat/completions"||s.match(/^\/llm\/[^/]+\/v1\/chat\/completions$/))){await this.handleOpenAICompat(e,t,s);return}if(this.business&&s.startsWith("/business")&&await this.business.handleHttp(`${e.method} ${s}`,e,t))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(g=>({id:g.id,enabled:g.enabled,nextRun:g.nextRun})),mesh:this.mesh?.directory()||[],usage:this.resolveTodayUsage()});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 /whatsapp/state":{let{getWhatsAppState:g}=await import("./whatsapp-state-XMTCSRXU.js");this.json(t,200,g());break}case"GET /whatsapp/qr.svg":{let{getWhatsAppState:g}=await import("./whatsapp-state-XMTCSRXU.js"),h=g();if(!h.qr){t.writeHead(204,{"Cache-Control":"no-store"}),t.end();break}try{let p=await import("qrcode"),f=await(p.default||p).toString(h.qr,{type:"svg",errorCorrectionLevel:"L",margin:1,color:{dark:"#000",light:"#fff"}});t.writeHead(200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"no-store"}),t.end(f)}catch(p){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("qrcode package not installed or failed: "+(p?.message||"unknown"))}break}case"GET /whatsapp/chats":{let g=this.router.getChannel("whatsapp");if(!g){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{chats:g.listChats()});break}case"GET /whatsapp/contacts":{let g=this.router.getChannel("whatsapp");if(!g){this.json(t,503,{error:"WhatsApp channel not enabled"});break}this.json(t,200,{contacts:g.listContacts()});break}case"POST /whatsapp/ingest":{let g=this.router.getChannel("whatsapp");if(!g){this.json(t,503,{error:"WhatsApp channel not enabled"});break}let h=await M(e),p=this.config.channels.whatsapp.ingest;if(!p.enabled&&!h.force){this.json(t,400,{error:'channels.whatsapp.ingest.enabled is false. Set it to true in agentx.json or pass {"force": true}.'});break}let u=typeof h.agent=="string"&&h.agent||this.config.channels.whatsapp.defaultAgent||this.config.node.defaultAgent;if(!u){this.json(t,400,{error:"No agent to own the entries. Pass {agent: '...'} or set channels.whatsapp.defaultAgent."});break}let f=!!h.dryRun,{runSweep:m}=await import("./ingest-whatsapp-LZE62INA.js"),y=this.registry.getWikiHub().getAgentWiki(u),b=p;if(typeof h.onlyJid=="string"){let v=h.onlyJid,$=v.endsWith("@g.us"),I=h.forceMode==="metadata-only"||h.forceMode==="messages"?h.forceMode:void 0;b={...p,enabled:!0,mode:I??p.mode,allowContacts:$||h.onlyKind==="group"?[]:[v],allowGroups:$||h.onlyKind==="group"?[v]:[],denyContacts:[],denyGroups:[]}}let w=await m({source:g,store:y,config:b,agentId:u,dryRun:f});this.json(t,200,w);break}case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /crons/health":this.json(t,200,this.cron.health());break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"GET /debug":{let{getDebugState:g,getDebugLogs:h}=await import("./debug-N3B5NVJU.js");this.json(t,200,{...g(),recentLogs:h(50)});break}case"POST /debug/on":{let{setDebug:g}=await import("./debug-N3B5NVJU.js"),h=n.searchParams.get("categories")?.split(",")||["all"];g(!0,h),this.log(`Debug enabled: ${h.join(", ")}`),this.json(t,200,{enabled:!0,categories:h});break}case"POST /debug/off":{let{setDebug:g}=await import("./debug-N3B5NVJU.js");g(!1),this.log("Debug disabled"),this.json(t,200,{enabled:!1});break}case"POST /gitlab/react":{let g=await M(e),{project:h,noteableType:p,noteableIid:u,noteId:f,agentId:m}=g,b=(this.config.channels.gitlab?.agentMappings||[]).find(k=>k.agentId===m),w=b?.token||this.config.channels.gitlab?.token,v=this.config.channels.gitlab?.host;if(this.log(`[gitlab/react] agent="${m}" project="${h}" mappingFound=${!!b} mappingToken=${!!b?.token} globalToken=${!!this.config.channels.gitlab?.token}(len=${(this.config.channels.gitlab?.token||"").length}) host=${v||"MISSING"}`),!w||!v){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:m,mappingFound:!!b,hasMappingToken:!!b?.token,hasGlobalToken:!!this.config.channels.gitlab?.token,hasHost:!!v}});break}let $=encodeURIComponent(h),I=p==="issue"?`${v}/api/v4/projects/${$}/issues/${u}/notes/${f}/award_emoji`:`${v}/api/v4/projects/${$}/merge_requests/${u}/notes/${f}/award_emoji`;try{let k=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":w},body:JSON.stringify({name:"eyes"})}),S=await k.text().catch(()=>"");this.log(`[gitlab/react] -> POST ${I} : ${k.status} ${S.slice(0,120)}`),this.json(t,200,{ok:k.ok,status:k.status,gitlabResponse:S.slice(0,200)})}catch(k){this.log(`[gitlab/react] FETCH ERROR: ${k.message}`),this.json(t,500,{error:k.message})}break}case"POST /gitlab/send-note":{let g=await M(e),{project:h,noteableType:p,noteableIid:u,agentId:f,text:m}=g,w=(this.config.channels.gitlab?.agentMappings||[]).find(k=>k.agentId===f)?.token||this.config.channels.gitlab?.token,v=this.config.channels.gitlab?.host;if(!w||!v){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:f,hasToken:!!w,hasHost:!!v}});break}let $=encodeURIComponent(h),I=p==="issue"?`${v}/api/v4/projects/${$}/issues/${u}/notes`:`${v}/api/v4/projects/${$}/merge_requests/${u}/notes`;try{let k=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":w},body:JSON.stringify({body:m})}),S=await k.text().catch(()=>""),T="";try{T=String(JSON.parse(S).id||"")}catch{}this.log(`[gitlab/send-note] agent="${f}" -> POST ${I} : ${k.status} noteId=${T||"?"}`),this.json(t,200,{ok:k.ok,status:k.status,noteId:T})}catch(k){this.log(`[gitlab/send-note] FETCH ERROR: ${k.message}`),this.json(t,500,{error:k.message})}break}case"POST /gitlab/log-time":{let g=await M(e),{project:h,noteableType:p,noteableIid:u,agentId:f,durationMs:m}=g,w=(this.config.channels.gitlab?.agentMappings||[]).find(A=>A.agentId===f)?.token||this.config.channels.gitlab?.token,v=this.config.channels.gitlab?.host;if(!w||!v){this.json(t,404,{error:"no gitlab token for agent"});break}let $=Math.max(60,Math.round(Number(m)/1e3)),I=Math.floor($/3600),k=Math.ceil($%3600/60),S=I>0?`${I}h${k>0?` ${k}m`:""}`:`${k}m`,T=encodeURIComponent(h),C=`${v}/api/v4/projects/${T}/${p==="merge_request"?"merge_requests":"issues"}/${u}/add_spent_time`;try{let A=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":w},body:JSON.stringify({duration:S})});this.log(`[gitlab/log-time] agent="${f}" duration=${S} -> POST ${C} : ${A.status}`),this.json(t,200,{ok:A.ok,status:A.status,duration:S})}catch(A){this.log(`[gitlab/log-time] FETCH ERROR: ${A.message}`),this.json(t,500,{error:A.message})}break}case"POST /github/send-comment":{let g=await M(e),{repo:h,issueNumber:p,agentId:u,text:f}=g,m=this.config.channels.github,b=(m?.agentMappings||[]).find($=>$.agentId===u),w;if(b?.tokenFile)try{w=Xe(b.tokenFile,"utf-8").trim().split(`
|
|
727
|
-
`)[0].trim()}catch{}if(w=w||b?.token,!w&&m?.tokenFile)try{w=Xe(m.tokenFile,"utf-8").trim().split(`
|
|
728
|
-
`)[0].trim()}catch{}if(w=w||m?.token,!w){this.json(t,404,{error:"no github token for agent",debug:{agentId:u,hasMapping:!!b}});break}let v=`https://api.github.com/repos/${h}/issues/${p}/comments`;try{let $=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${w}`,"User-Agent":"AgentX"},body:JSON.stringify({body:f})}),I=await $.text().catch(()=>""),k="";try{k=String(JSON.parse(I).id||"")}catch{}this.log(`[github/send-comment] agent="${u}" -> POST ${v} : ${$.status} commentId=${k||"?"}`),this.json(t,200,{ok:$.ok,status:$.status,commentId:k})}catch($){this.log(`[github/send-comment] FETCH ERROR: ${$.message}`),this.json(t,500,{error:$.message})}break}case"POST /github/react":{let g=await M(e),{repo:h,commentId:p,agentId:u}=g,f=this.config.channels.github,y=(f?.agentMappings||[]).find(v=>v.agentId===u),b;if(y?.tokenFile)try{b=Xe(y.tokenFile,"utf-8").trim().split(`
|
|
729
|
-
`)[0].trim()}catch{}if(b=b||y?.token,!b&&f?.tokenFile)try{b=Xe(f.tokenFile,"utf-8").trim().split(`
|
|
730
|
-
`)[0].trim()}catch{}if(b=b||f?.token,!b){this.json(t,404,{error:"no github token for agent"});break}let w=`https://api.github.com/repos/${h}/issues/comments/${p}/reactions`;try{let v=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b}`,"User-Agent":"AgentX"},body:JSON.stringify({content:"eyes"})});this.log(`[github/react] agent="${u}" -> POST ${w} : ${v.status}`),this.json(t,200,{ok:v.ok,status:v.status})}catch(v){this.log(`[github/react] FETCH ERROR: ${v.message}`),this.json(t,500,{error:v.message})}break}case"POST /reload":{try{let g=await this.reload();this.json(t,200,{ok:!0,...g})}catch(g){this.json(t,500,{ok:!1,error:g?.message||String(g)})}break}case"POST /recall":{let g=await M(e);if(!g.agent){this.json(t,400,{error:"Required: agent (id of the agent whose sessions to recall)"});break}try{let h=this.registry.getSessionStore().recallTurns({agentId:String(g.agent),channel:g.channel?String(g.channel):void 0,chatId:g.chatId?String(g.chatId):void 0,before:g.before?String(g.before):void 0,after:g.after?String(g.after):void 0,lookbackDays:typeof g.lookbackDays=="number"?g.lookbackDays:void 0,limit:typeof g.limit=="number"?g.limit:void 0,query:g.query?String(g.query):void 0,participants:Array.isArray(g.participants)?g.participants.map(p=>String(p)):void 0});this.json(t,200,h)}catch(h){this.json(t,500,{error:h?.message||String(h)})}break}case"POST /chat/recent":{let g=await M(e);if(!g.channel||!g.chatId){this.json(t,400,{error:"Required: channel, chatId"});break}try{let h=this.registry.getSessionStore().recentByChatId({channel:String(g.channel),chatId:String(g.chatId),sinceISO:typeof g.sinceISO=="string"?g.sinceISO:void 0,limit:typeof g.limit=="number"?g.limit:void 0});this.json(t,200,{messages:h,count:h.length})}catch(h){this.json(t,500,{error:h?.message||String(h)})}break}case"POST /send/agent":{let g=await M(e);if(!g.agentId||!g.text){this.json(t,400,{error:"Required: agentId, text"});break}let h=String(g.agentId),p=String(g.text);if(this.registry.getAgent(h)){try{let y=g.senderAgentId?String(g.senderAgentId):void 0,b=await this.registry.execute({agentId:h,message:p,context:{channel:"a2a",sender:y?`agent:${y}`:"agent",chatId:y||"a2a"}});this.json(t,b.error?500:200,{ok:!b.error,content:b.content,error:b.error})}catch(y){this.json(t,500,{error:y.message})}break}if(!this.mesh){this.json(t,400,{error:`Unknown agent "${h}" \u2014 mesh disabled, no remote lookup possible`});break}let f=this.mesh.directory(),m=f.find(y=>y.healthy&&y.skills.some(b=>b.id===h));if(!m){let y=[...Object.keys(this.config.agents),...f.flatMap(b=>b.skills.map(w=>w.id))];this.json(t,404,{error:`Unknown agent "${h}"`,known:y});break}try{let y=g.senderAgentId?String(g.senderAgentId):void 0,b=await this.mesh.sendTask(m.peer,p,h,{senderAgentId:y});this.json(t,200,{ok:!0,messageId:b,peer:m.peer})}catch(y){this.json(t,500,{error:y.message,peer:m.peer})}break}case"POST /send/contact":{let g=await M(e);if(!g.contactName||!g.text){this.json(t,400,{error:"Required: contactName, text"});break}let h=String(g.contactName),p=String(g.text),u=g.channel?String(g.channel):void 0,f=g.confirmed===!0,m=this.contacts.resolve(h);if(m.kind==="miss"){this.json(t,404,{error:`No contact matches "${h}"`,hint:"Add the contact to .agentx/contacts.json and POST /reload."});break}if(m.kind==="ambiguous"){this.json(t,409,{error:"ambiguous",candidates:m.candidates.map(v=>({id:v.id,name:v.name,channels:Object.keys(v.channels)}))});break}if(m.kind==="fuzzy"&&!f){this.json(t,409,{error:"fuzzy-match-needs-confirmation",candidate:{id:m.contact.id,name:m.contact.name,channels:Object.keys(m.contact.channels)},confidence:m.confidence,hint:"Re-call with confirmed:true once the user has confirmed this is the intended recipient."});break}let y=!!this.registry.getAgent(h),b=this.mesh?.directory()?.some(v=>v.skills.some($=>$.id.toLowerCase()===h.toLowerCase()));if(y||b){this.json(t,409,{error:"ambiguous",hint:`"${h}" resolves to BOTH a contact (id=${m.contact.id}) and an agent. Use /send/agent for the agent, or pass contactId="${m.contact.id}" to /send/contact for the contact.`});break}let w=this.contacts.pickChannel(m.contact,u);if(!w){this.json(t,400,{error:`Contact "${m.contact.id}" has no channels configured`});break}if(u&&w.channel!==u){this.json(t,400,{error:`Contact "${m.contact.id}" has no "${u}" channel`,available:Object.keys(m.contact.channels)});break}try{let v=await this.router.sendOutbound({channel:w.channel,chatId:w.address,text:p,agentId:g.agentId,accountId:g.accountId});this.json(t,200,{ok:!0,messageId:v||null,contactId:m.contact.id,channel:w.channel})}catch(v){this.json(t,400,{error:v.message})}break}case"POST /send":{let g=await M(e);if(!g.channel||!g.chatId||!g.text){this.json(t,400,{error:"Required: channel, chatId, text"});return}try{let h=await this.router.sendOutbound({channel:g.channel,chatId:g.chatId,text:g.text,replyTo:g.replyTo,parseMode:g.parseMode,agentId:g.agentId,accountId:g.accountId});this.json(t,200,{ok:!0,messageId:h||null})}catch(h){this.json(t,400,{error:h.message})}break}case"GET /channels":this.json(t,200,this.router.getChannelNames());break;case"GET /services":this.json(t,200,this.router.serviceMatcher?.list()||[]);break;case"POST /task":{let g=await M(e),h=g.agent||this.config.node.defaultAgent;if(!h||!g.message){this.json(t,400,{error:"Missing: message (and no defaultAgent configured)"});return}let p=typeof g.senderAgentId=="string"?g.senderAgentId:void 0;!g.context&&!p&&this.log(`[a2a] /task accepted without senderAgentId for agent="${h}" from ${e.socket?.remoteAddress||"unknown"} \u2014 caller should upgrade. Required in next release.`);let f=g.contextStrategy==="layered"||g.contextStrategy==="planner"?g.contextStrategy:void 0,m;if(E("mesh")!=="off")try{let b=Ln(_(),{agentId:h,senderAgentId:p,context:g.context},JSON.stringify({agentId:h,senderAgentId:p,context:g.context,message:typeof g.message=="string"?g.message.slice(0,200):""}),{agentId:h,outcome:"dispatched",reason:p?`from ${p}`:null});b.outcome==="dispatched"&&(m={eventId:b.eventId,decidedBy:b.decidedBy})}catch(b){this.log(`[ledger] mesh /task agent="${h}" record failed: ${b?.message??b}`)}let y=await this.registry.execute({agentId:h,message:g.message,context:g.context,contextStrategy:f,intentRef:m},()=>{});this.json(t,y.error?500:200,y);break}case"POST /ask":case"GET /ask":{let g=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),h=g.searchParams.get("q")||g.searchParams.get("message")||"";if(e.method==="POST"){let y=await M(e);h=y.message||y.q||h}let p=this.config.node.defaultAgent;if(!p){this.json(t,400,{error:"No defaultAgent configured in node config"});return}if(!h){this.json(t,400,{error:"Missing message (pass as ?q=... or {message:...})"});return}let u=`[VOICE MODE \u2014 Your response will be spoken aloud by a TTS engine. Keep it to 2-3 short sentences. Use plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.]
|
|
731
|
-
|
|
732
|
-
${h}`,f=await this.registry.execute({agentId:p,message:u,context:{channel:"voice",sender:"Siri"}}),m=Ji(f.content);this.json(t,f.error?500:200,{text:m,full:f.content,error:f.error,duration:f.duration});break}case"POST /mesh/task":{let g=await M(e);if(!g.peer||!g.message){this.json(t,400,{error:"Missing: peer, message"});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let h=await this.mesh.sendTask(g.peer,g.message,g.agent);this.json(t,200,{response:h});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let h=await M(e);if(!h.kind||!h.callId||!h.from||!h.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let p=await this.webrtc.handleOutgoing(h);this.json(t,p.ok?200:400,p);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let h=await M(e);if(!h.kind||!h.callId||!h.from||!h.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let p=this.webrtc.handleIncoming(h);this.json(t,p.ok?200:400,p);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let g=await M(e),h=g.callId,p=g.target,u=g.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!h||!p||!u){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let f=await this.botManager.invite({callId:h,target:p,agentId:u});this.json(t,f.ok?200:500,f);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let g=this.config.channels.webrtc;if(!g?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...g.stunServers.map(h=>({urls:h})),...g.turnServers],peers:this.mesh?.directory().map(h=>({name:h.peer,healthy:h.healthy}))||[]});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(g=>{let h=this.config.agents[g.id]||{},p=typeof h.description=="string"&&h.description.trim()||Wi(h.systemPrompt)||`Agent "${g.name}" (${g.tier})`,u=Array.isArray(h.mentions)?h.mentions.slice(0,4):[];return{id:g.id,name:g.name,description:p,tags:[g.tier,...u]}}),channels:this.router.getChannelNames(),defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let g=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:g.summary()});break}case"GET /wiki/entries":{let g=this.registry.getWikiHub(),h=n.searchParams.get("agent")||void 0,p=n.searchParams.get("after")||void 0,u=h?g.getAgentEntries(h):g.getSharedStore().listEntries({after:p});this.json(t,200,{nodeId:this.config.node.id,count:u.length,entries:u.map(f=>({id:f.id,date:f.date,agentId:f.agentId,source:f.source,sourceContext:f.sourceContext,content:f.content}))});break}case"GET /wiki/articles":{let g=this.registry.getWikiHub(),h=n.searchParams.get("agent");if(!h){this.json(t,400,{error:"?agent= required"});break}let u=g.getAgentWiki(h).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:h,articles:u.articles});break}case"GET /wiki/article":{let g=this.registry.getWikiHub(),h=n.searchParams.get("agent"),p=n.searchParams.get("path");if(!h||!p){this.json(t,400,{error:"?agent= and ?path= required"});break}let f=g.getAgentWiki(h).readArticle(p);if(!f){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:h,path:f.path,title:f.meta.title,tags:f.meta.tags,owner:f.meta.owner,created:f.meta.created,lastUpdated:f.meta.lastUpdated,sources:f.meta.sources,content:f.content});break}case"GET /graph/schema":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:g.loadSchema()});break}case"GET /graph/nodes":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...g.loadNodes()});break}case"GET /graph/classifications":{let g=this.registry.getGraphStore();if(!g){this.json(t,404,{error:"graph disabled on this node"});break}let h=n.searchParams.get("status")||"approved",p=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),u=g.listByStatus(h,p);this.json(t,200,{nodeId:this.config.node.id,status:h,count:u.length,classifications:u});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context? }","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await M(e),i=n.match(/^\/llm\/([^/]+)\//),r=Object.keys(this.config.agents)[0]||"default",o=i?.[1]||s.model||r,a=s.messages||[],l=[...a].reverse().find(p=>p.role==="user");if(!l?.content){this.json(t,400,{error:{message:"No user message found",type:"invalid_request_error"}});return}let d=a.slice(0,-1).map(p=>`${p.role==="user"?"User":"Assistant"}: ${p.content.slice(0,200)}`),g=d.length>0?`[Conversation]
|
|
733
|
-
${d.slice(-10).join(`
|
|
734
|
-
`)}
|
|
735
|
-
|
|
736
|
-
`:"";if(s.stream===!0){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let p=`chatcmpl-${Date.now().toString(36)}`,u=await this.registry.execute({agentId:o,message:g+l.content,context:{channel:"api",sender:"openai-compat"}}),f=u.error||u.content||"",m={id:p,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,delta:{role:"assistant",content:f},finish_reason:"stop"}]};t.write(`data: ${JSON.stringify(m)}
|
|
737
|
-
|
|
738
|
-
`),t.write(`data: [DONE]
|
|
739
|
-
|
|
740
|
-
`),t.end()}else{let p=await this.registry.execute({agentId:o,message:g+l.content,context:{channel:"api",sender:"openai-compat"}}),u=p.error||p.content||"",f=Math.ceil(u.length/4);this.json(t,200,{id:`chatcmpl-${Date.now().toString(36)}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,message:{role:"assistant",content:u},finish_reason:"stop"}],usage:{prompt_tokens:Math.ceil(l.content.length/4),completion_tokens:f,total_tokens:Math.ceil(l.content.length/4)+f}})}}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveTodayUsage(){let e=Nn();if(e==="json")return this.registry.getTodayUsage();let t=Dn(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){for(let e of this.registry.list()){let t=e.workspace;if(!(!t||!he(t)))try{let n=B(t,".claude","skills");Kn(n,{recursive:!0});let s=B(n,Hn);he(s)||(qn(s,Wn),this.log(` memory-skill: installed remember.md \u2192 ${e.id}`)),this.agentMemory.syncToWorkspace(e.id,t)}catch(n){this.log(` memory-skill: ${e.id} install failed \u2014 ${n?.message??n}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!he(n))continue;let s=t.mcp??{};try{switch(Fn(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(s).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}async handleMemoryApi(e,t,n,s){let i=this.agentMemory;if(e.method==="GET"&&n==="/api/memory"){let a=s.searchParams.get("agent")||"";return a?(this.json(t,200,{agent:a,memories:i.list(a),index:i.indexMarkdown(a)}),!0):(this.json(t,400,{error:"missing agent query param"}),!0)}let r=e.method==="GET"&&n.match(/^\/api\/memory\/([^\/?]+)$/);if(r){let a=s.searchParams.get("agent")||"";if(!a)return this.json(t,400,{error:"missing agent query param"}),!0;let l=i.get(a,decodeURIComponent(r[1]));return l?(this.json(t,200,{memory:l}),!0):(this.json(t,404,{error:"no such memory"}),!0)}if(e.method==="POST"&&n==="/api/memory"){let a;try{a=await Y(e)}catch(f){return this.json(t,400,{error:"invalid JSON body",message:f.message}),!0}let l=typeof a?.agentId=="string"?a.agentId:"",d=typeof a?.type=="string"?a.type:"",g=typeof a?.name=="string"?a.name:"",h=typeof a?.description=="string"?a.description:"",p=typeof a?.body=="string"?a.body:"",u=a?.append===!0;if(!l||!d||!g||!h||!p)return this.json(t,400,{error:"required fields: agentId, type, name, description, body"}),!0;try{let f=p;if(u){let b=i.get(l,g);b&&(f=`${b.body.trimEnd()}
|
|
741
|
-
|
|
742
|
-
${p.trim()}`)}let m=i.save({agentId:l,type:d,name:g,description:h,body:f}),y=this.workspaceFor(l);if(y)try{i.syncToWorkspace(l,y)}catch{}this.json(t,200,{ok:!0,memory:m,syncedToWorkspace:!!y})}catch(f){this.json(t,400,{error:f?.message||"save failed"})}return!0}let o=e.method==="DELETE"&&n.match(/^\/api\/memory\/([^\/?]+)$/);if(o){let a=s.searchParams.get("agent")||"";if(!a)return this.json(t,400,{error:"missing agent query param"}),!0;if(!i.remove(a,decodeURIComponent(o[1])))return this.json(t,404,{error:"no such memory"}),!0;let d=this.workspaceFor(a);if(d)try{i.syncToWorkspace(a,d)}catch{}return this.json(t,200,{ok:!0}),!0}return!1}async handleTaskApi(e,t,n){let s=this.workflowDispatcher;if(!s)return!1;let{formSubmissionSchema:i}=await import("./types-ZRLHHCGB.js");if(e.method==="GET"&&(n==="/api/workflows/tasks"||n.startsWith("/api/workflows/tasks?"))){let d=new URL(e.url||"/","http://_").searchParams.get("actor")||void 0,g=d?s.tasks.listForActor(d):s.tasks.listOpen();return this.json(t,200,{tasks:g}),!0}let o=n.replace(/^\/api\/workflows\/tasks/,"").match(/^\/([^\/?]+)(\/submit)?$/);if(!o)return!1;let a=decodeURIComponent(o[1]);if(o[2]){if(e.method!=="POST")return this.json(t,405,{error:"method not allowed"}),!0;let l;try{l=await Y(e)}catch(u){return this.json(t,400,{error:"invalid JSON body",message:u.message}),!0}let d=l&&typeof l=="object"&&"submission"in l?l.submission:l,g=i.safeParse(d);if(!g.success)return this.json(t,400,{error:"invalid submission",issues:g.error.issues.map(u=>({path:u.path.join("."),message:u.message}))}),!0;let h=typeof l?.submittedBy=="string"?l.submittedBy:"anonymous",p=await s.submitTask(a,g.data,h);return p.ok?(this.json(t,200,{ok:!0,runId:p.runId}),!0):(this.json(t,400,{error:p.error,fieldErrors:p.fieldErrors}),!0)}if(e.method==="GET"){let l=s.tasks.get(a);return l?(this.json(t,200,{task:l}),!0):(this.json(t,404,{error:"task not found"}),!0)}return!1}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await Y(e)}catch(a){this.json(t,400,{error:"invalid JSON body",message:a.message});return}let s=n?.payload??n,i=s?.event,r=s?.entityRef;if(!i?.id||!r?.backend||!r?.id){this.json(t,400,{error:"missing event or entityRef"});return}let o=n?.kind;try{if(o==="trigger"&&s.trigger){let h=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${h}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let p=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:r,event:i,fromRemote:{peer:h}});this.log(`[workflows/mesh] dispatched broadcast: matched=${p.claimed.length} ${p.claimed.length?`(${p.claimed.map(u=>u.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:p.claimed.map(u=>u.id)});return}let d=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(h=>h.type.startsWith("trigger."))?.config??{},g={source:String(d.source??"hook"),project:d.filter?.project,repo:d.filter?.repo,chat:d.filter?.chat,labels:d.filter?.labels};await this.workflowDispatcher.dispatch({trigger:g,entityRef:r,event:i}),this.json(t,202,{ok:!0})}catch(a){this.log(`[workflows] /workflow/event failed: ${a.message}`),this.json(t,500,{error:a.message})}}async handleChannelSend(e,t){let n;try{n=await Y(e)}catch(a){this.json(t,400,{error:"invalid JSON body",message:a.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),r=String(n?.text??"");if(!s||!i||!r){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}try{let a=await this.router.sendOutbound({channel:s,chatId:i,text:r,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0});this.json(t,200,{ok:!0,messageId:a??null})}catch(a){this.log(`[mesh] /channel/send "${s}" failed: ${a.message}`),this.json(t,500,{error:a.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],r=[],o=(l,d)=>{let g=0;for(let h of l)!h.id||s.has(h.id)||(s.add(h.id),i.push({...h,source:d}),g++);g>0&&r.push(`${d}:${g}`)},a=this.router.getChannel(t);if(a?.listKnownChats)try{o(a.listKnownChats(),"local")}catch{}else if(a?.listChats)try{o(a.listChats().map(l=>({id:l.jid,name:l.name,kind:l.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let l=this.mesh.directory().filter(d=>d.healthy&&d.channels?.includes(t));await Promise.allSettled(l.map(async d=>{try{let g=await fetch(`${d.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{signal:AbortSignal.timeout(5e3)});if(!g.ok)return;let h=await g.json();Array.isArray(h.chats)&&o(h.chats.map(p=>({id:p.id,name:p.name,kind:p.kind??"dm",accountId:p.accountId})),`mesh:${d.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:r.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s=this.workflowStore.get(n);if(!s){this.json(t,404,{error:`unknown workflow "${n}"`});return}let i=s.nodes.find(u=>u.type.startsWith("trigger."));if(!i){this.json(t,400,{error:`workflow "${n}" has no trigger node`});return}let r;try{r=await Y(e)}catch{r={}}let o=!!r?.force,a=r?.payload||{};if(i.type!=="trigger.manual"&&!o){this.json(t,409,{error:`workflow "${n}" trigger is "${i.type}"`,hint:'pass { "force": true } to fire anyway with a synthesized event (for testing)'});return}let l=i.config??{},d=o?String(l.source??"manual"):"manual",g=String(a.entityId||a.chatId||`manual-${Date.now().toString(36)}`),h={backend:o&&l.source?"channel":"manual",id:g},p=`manual:${n}:${g}:${Date.now()}`;try{let f=(await this.workflowDispatcher.dispatch({trigger:o?{source:d,project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels}:{source:"manual"},entityRef:h,event:{id:p,payload:a}})).runs[0]?.id;this.json(t,f?200:202,{ok:!0,runId:f,entityRef:h,source:d,force:o})}catch(u){this.log(`[workflows] manual run "${n}" failed: ${u.message}`),this.json(t,500,{error:u.message})}}};function Wi(c){if(typeof c!="string")return"";let e=c.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function Y(c){return new Promise((e,t)=>{let n="";c.setEncoding("utf8"),c.on("data",s=>{n+=s}),c.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),c.on("error",t)})}function Ji(c){let e=c;return e=e.replace(/```[\s\S]*?```/g,". "),e=e.replace(/`[^`]*`/g,""),e=e.replace(/\*\*(.*?)\*\*/g,"$1"),e=e.replace(/__(.*?)__/g,"$1"),e=e.replace(/\*([^*]+)\*/g,"$1"),e=e.replace(/_([^_]+)_/g,"$1"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"image$1 "),e=e.replace(/^#{1,6}\s+/gm,""),e=e.replace(/^[\s]*[-*+]\s+/gm,". "),e=e.replace(/^[\s]*\d+\.\s+/gm,". "),e=e.replace(/^[-=_]{3,}$/gm,""),e=e.replace(/^>\s*/gm,""),e=e.replace(/https?:\/\/\S+/g,"link"),e=e.replace(/\/\w+(\/\w+)+/g,t=>t.split("/").filter(Boolean).join(" slash ")),e=e.replace(/&/g," and "),e=e.replace(/@/g," at "),e=e.replace(/=>/g," returns "),e=e.replace(/->/g," to "),e=e.replace(/\|/g," or "),e=e.replace(/\be\.g\./gi,"for example"),e=e.replace(/\bi\.e\./gi,"that is"),e=e.replace(/\betc\./gi,"etcetera"),e=e.replace(/\bvs\.?\b/gi,"versus"),e=e.replace(/\n{2,}/g,". "),e=e.replace(/\n/g," "),e=e.replace(/\s+/g," "),e=e.replace(/\.\s*\./g,"."),e=e.replace(/\s+([.,!?])/g,"$1"),e=e.trim().replace(/^[.,:;]+\s*/,""),e.length>800&&(e=e.slice(0,800).replace(/\s+\S*$/,"")+"..."),e}function zi(c,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(c),...Object.keys(e)]);for(let i of s){let r=c[i],o=e[i];if(!r||!o){n.add("add/remove");continue}for(let a of t)JSON.stringify(r[a])!==JSON.stringify(o[a])&&n.add(`${i}.${a}`)}return Array.from(n).slice(0,6)}async function M(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)})}function Bc(c){typeof c=="string"&&(pe.error(c),process.exit(1)),c instanceof Error&&(pe.error(c.message),process.exit(1)),pe.error("Something went wrong. Please try again."),process.exit(1)}import $t from"path";import Vn from"fs-extra";function Hc(){let c=[];try{let e=import.meta.dirname;e&&(c.push($t.resolve(e,"..","package.json")),c.push($t.resolve(e,"package.json")))}catch{}c.push($t.resolve(process.cwd(),"package.json"));for(let e of c)try{if(Vn.existsSync(e)){let t=Vn.readJSONSync(e);if(t&&t.name)return t}}catch{}return{name:"agentix-cli",version:"0.0.0"}}export{Zi as a,ee as b,me as c,oe as d,K as e,ve as f,En as g,pt as h,Yn as i,Bc as j,Hc as k};
|
|
743
|
-
//# sourceMappingURL=chunk-6B74TO2J.js.map
|