agentix-cli 0.22.0 → 0.23.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-Y4U4R3ZZ.js → agent-FSE4KRLX.js} +2 -2
- package/dist/{board-dashboard-2CPBWFOB.js → board-dashboard-PUACKWAN.js} +4 -4
- package/dist/builtin-TQKMR42Z.js +2 -0
- package/dist/{chunk-OPKQNLGX.js → chunk-3SHMHYPD.js} +71 -71
- package/dist/chunk-3SHMHYPD.js.map +1 -0
- package/dist/{chunk-KX626FN4.js → chunk-4INOOHND.js} +2 -2
- package/dist/{chunk-OZOQKPJV.js → chunk-72PAN7UI.js} +51 -50
- package/dist/chunk-72PAN7UI.js.map +1 -0
- package/dist/chunk-BOUKM2PS.js +163 -0
- package/dist/chunk-BOUKM2PS.js.map +1 -0
- package/dist/{chunk-P3TJHGO5.js → chunk-DXTIG5YV.js} +2 -2
- package/dist/chunk-EK37JHJI.js +13 -0
- package/dist/chunk-EK37JHJI.js.map +1 -0
- package/dist/chunk-EQPUB7CZ.js +685 -0
- package/dist/chunk-EQPUB7CZ.js.map +1 -0
- package/dist/{chunk-WHP4I44J.js → chunk-KWUWZQGV.js} +2 -2
- package/dist/{chunk-ABVZHJUO.js → chunk-PD5Q7D6Z.js} +2 -2
- package/dist/{chunk-VYLZ7UYM.js → chunk-Q6CAFGXT.js} +2 -2
- package/dist/chunk-ZZFXI3CS.js +8 -0
- package/dist/chunk-ZZFXI3CS.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/{config-BLOKGMER.js → config-ADS54KLC.js} +2 -2
- package/dist/config-mutator-WTRMBZTO.js +2 -0
- package/dist/doctor-T6RB4Q5X.js +2 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/program-V7NGFB2R.js +2 -0
- package/dist/registry-42HEWCLA.js +2 -0
- package/dist/scheduler-C56ABAVP.js +2 -0
- package/dist/scheduler-C56ABAVP.js.map +1 -0
- package/dist/web/workflow-editor.global.js +11 -11
- package/dist/web/workflow-editor.global.js.map +1 -1
- package/package.json +2 -1
- package/dist/chunk-2HXSJYAJ.js +0 -15
- package/dist/chunk-2HXSJYAJ.js.map +0 -1
- package/dist/chunk-CO4YCIIA.js +0 -13
- package/dist/chunk-CO4YCIIA.js.map +0 -1
- package/dist/chunk-OPKQNLGX.js.map +0 -1
- package/dist/chunk-OZOQKPJV.js.map +0 -1
- package/dist/chunk-X5D5AV5N.js +0 -833
- package/dist/chunk-X5D5AV5N.js.map +0 -1
- package/dist/config-mutator-RG7QY2EL.js +0 -2
- package/dist/doctor-ZTECTUHX.js +0 -2
- package/dist/program-GZOJIWTB.js +0 -2
- package/dist/registry-QZIUSQ5J.js +0 -2
- package/dist/scheduler-B2BQPV4M.js +0 -2
- /package/dist/{agent-Y4U4R3ZZ.js.map → agent-FSE4KRLX.js.map} +0 -0
- /package/dist/{board-dashboard-2CPBWFOB.js.map → board-dashboard-PUACKWAN.js.map} +0 -0
- /package/dist/{config-BLOKGMER.js.map → builtin-TQKMR42Z.js.map} +0 -0
- /package/dist/{chunk-KX626FN4.js.map → chunk-4INOOHND.js.map} +0 -0
- /package/dist/{chunk-P3TJHGO5.js.map → chunk-DXTIG5YV.js.map} +0 -0
- /package/dist/{chunk-WHP4I44J.js.map → chunk-KWUWZQGV.js.map} +0 -0
- /package/dist/{chunk-ABVZHJUO.js.map → chunk-PD5Q7D6Z.js.map} +0 -0
- /package/dist/{chunk-VYLZ7UYM.js.map → chunk-Q6CAFGXT.js.map} +0 -0
- /package/dist/{config-mutator-RG7QY2EL.js.map → config-ADS54KLC.js.map} +0 -0
- /package/dist/{doctor-ZTECTUHX.js.map → config-mutator-WTRMBZTO.js.map} +0 -0
- /package/dist/{program-GZOJIWTB.js.map → doctor-T6RB4Q5X.js.map} +0 -0
- /package/dist/{registry-QZIUSQ5J.js.map → program-V7NGFB2R.js.map} +0 -0
- /package/dist/{scheduler-B2BQPV4M.js.map → registry-42HEWCLA.js.map} +0 -0
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
import{a as Vt,b as Yt,c as Qt,d as Zt,e as nt,f as en,g as tn,h as nn,n as on,o as an,q as cn,r as dn,s as ln,y as gn}from"./chunk-BOUKM2PS.js";import{A as Ft,B as Ht,h as Et,n as Dt,o as Ye}from"./chunk-Q6CAFGXT.js";import{b as Rt}from"./chunk-SFQUP3BP.js";import{a as Jt,b as et,c as zt,d as Kt,h as qt}from"./chunk-ZZFXI3CS.js";import{a as D,b as Xt,c as H,d as W,f as tt}from"./chunk-PD5Q7D6Z.js";import{e as Ze,f as Wt}from"./chunk-EK37JHJI.js";import{a as sn,d as rn}from"./chunk-BHSPAP4U.js";import{a as Qe,b as Ot,c as Nt,h as Bt,i as q,j as Gt,q as Ut}from"./chunk-72PAN7UI.js";import{a as Lt}from"./chunk-5F3J55LG.js";import{c as j}from"./chunk-GOLZ6NEL.js";import{a as me}from"./chunk-VJUTQAPJ.js";import{a as _t,d as jt}from"./chunk-DJEZ2HVU.js";import{e as K}from"./chunk-DSYKYZMT.js";import{b as pe}from"./chunk-4YCH6IZV.js";var vs={name:"agentx",version:"0.1.0"},$s="2024-11-05",Ss={tools:{},elicitation:{form:{}}},Is=0;async function hn(d,e){let t=++Is;return X({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:d,requestedSchema:e}}),new Promise(n=>{ie.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{ie.has(`elicit-${t}`)&&(ie.delete(`elicit-${t}`),n(null))},6e4)})}var ie=new Map,E=process.env.AGENTX_DAEMON_URL||"http://localhost:19900",Ts=/\x1B\[[0-9;]*[A-Za-z]/g;function ee(d){return d.replace(Ts,"")}var xs=[{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 Cs(d,e){let t=e.cwd||process.cwd();switch(d){case"agentx_generate":{let n=e.task,s=e.type||"auto",i=e.output_dir,r=await Ht({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 Ft(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
|
+
${Rt(n.techStack)}
|
|
12
|
+
|
|
13
|
+
${JSON.stringify(s,null,2)}`}]}}case"agentx_skill_match":{let n=e.task,s=await _t(t),i=jt(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: ${Et(void 0,n)}`}]}}case"agentx_send":{let n=e.channel,s=e.chatId,i=e.text;if(!n||!s||!i){let a=await fetch(`${E}/channels`).catch(()=>null),c=a?await a.json():["telegram","whatsapp","gitlab","discord"],l=await hn("Please provide the message details:",{type:"object",properties:{channel:{type:"string",title:"Channel",description:"Target channel",enum:c,default:n||c[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(!l)return{content:[{type:"text",text:"Send cancelled."}]};n=l.channel,s=l.chatId,i=l.text}let r=await fetch(`${E}/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(`${E}/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 c=Array.isArray(o?.known)?` Known agents: ${o.known.join(", ")}.`:"";return{content:[{type:"text",text:`Error: ${o.error||r.statusText}.${c}`}]}}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(`${E}/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 c=a.messages||[];return c.length===0?{content:[{type:"text",text:`No messages in ${n}/${s} within the requested window.`}]}:{content:[{type:"text",text:c.map(p=>{let u=p.ts.slice(11,16),f=p.ts.slice(0,10),m=p.role==="agent"?`${p.agentId}`:p.senderName||"user";return`[${f} ${u}] ${m}: ${p.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(`${E}/send/contact`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contactName:n,text:s,channel:i,confirmed:r,agentId:o})}),c=await a.json();return a.status===409?{content:[{type:"text",text:`Refused: ${JSON.stringify(c,null,2)}`}]}:a.ok?{content:[{type:"text",text:`Message sent to contact ${c.contactId} via ${c.channel}. ID: ${c.messageId||"ok"}`}]}:{content:[{type:"text",text:`Error: ${c.error||a.statusText}`}]}}case"agentx_task":{let n=e.agent,s=e.message;if(!n||!s){let o=await fetch(`${E}/agents`).catch(()=>null),a=o?(await o.json()).map(l=>l.id):[],c=await hn("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(!c)return{content:[{type:"text",text:"Task cancelled."}]};n=c.agent,s=c.message}let r=await(await fetch(`${E}/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(`${E}/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(`${E}/health`)).json();return{content:[{type:"text",text:JSON.stringify(s,null,2)}]}}case"agentx_crons":{let s=await(await fetch(`${E}/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"),c=e.agent||"";if(!c){let{existsSync:h}=await import("fs");for(let y of a.listAgents()){let b=r(a.getAgentWiki(y).baseDir,"_index.md");if(h(b)){c=y;break}}}if(!c)return{content:[{type:"text",text:"Error: no agent has a wiki catalog yet. Run `agentx wiki absorb` first."}]};let l=a.getAgentWiki(c),p=typeof e.max_hops=="number"?Math.min(3,Math.max(0,e.max_hops)):2,u=await i(n,l,c,{maxHops:p});if(u.status!=="ok")return{content:[{type:"text",text:`Query returned status "${u.status}"${u.error?`: ${u.error}`:""}`}]};let f=u.citations.map(h=>` - ${h.title} [${h.type||"?"}] (${h.path})`).join(`
|
|
25
|
+
`),m=u.walked.length;return{content:[{type:"text",text:`${u.answer}
|
|
26
|
+
|
|
27
|
+
Citations (${m} article${m===1?"":"s"} walked):
|
|
28
|
+
${f}`}]}}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"),c=["wiki","patch",n,s,i,"--patch-model",r,...o?["--no-commit"]:["--yes"]];try{let l=a(process.execPath,[process.argv[1],...c],{cwd:t,encoding:"utf-8",timeout:18e4,maxBuffer:8388608});return{content:[{type:"text",text:ee(l).trim()||"(no output)"}]}}catch(l){return{content:[{type:"text",text:`patch failed:
|
|
29
|
+
${[l.stdout,l.stderr,l.message].filter(Boolean).map(u=>ee(String(u))).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,c=r[r.length-1]?.toLowerCase(),l=["save","edit","scrap"].includes(c)?r:[...r,"save"],{execFileSync:p}=await import("child_process"),{writeFileSync:u,mkdtempSync:f}=await import("fs"),{tmpdir:m}=await import("os"),{join:g}=await import("path"),h=f(g(m(),"agentx-mcp-interview-")),y=g(h,"answers.txt");u(y,l.join(`
|
|
31
|
+
`));let b=["wiki","interview","--agent",n,"--topic",s,"--type",i,"--model",o,"--answers",y,...a?[]:["--no-commit"]];try{let w=p(process.execPath,[process.argv[1],...b],{cwd:t,encoding:"utf-8",timeout:24e4,maxBuffer:8388608});return{content:[{type:"text",text:ee(w).trim()||"(no output)"}]}}catch(w){return{content:[{type:"text",text:`interview failed:
|
|
32
|
+
${[w.stdout,w.stderr,w.message].filter(Boolean).map(S=>ee(String(S))).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:ee(a).trim()||"(no output)"}]}}catch(a){return{content:[{type:"text",text:`graph review failed:
|
|
34
|
+
${[a.stdout,a.stderr,a.message].filter(Boolean).map(l=>ee(String(l))).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(`${E}/debug/on?categories=${s}`,{method:"POST"}),{content:[{type:"text",text:`Debug enabled: ${s}`}]}}else{if(n==="off")return await fetch(`${E}/debug/off`,{method:"POST"}),{content:[{type:"text",text:"Debug disabled."}]};{let i=await(await fetch(`${E}/debug`)).json();return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}}}}default:throw new Error(`Unknown tool: ${d}`)}}function un(d,e){let t;try{t=JSON.parse(d)}catch(n){e("Failed to parse message:",n);return}if(t.id&&typeof t.id=="string"&&t.id.startsWith("elicit-")&&t.result){let n=ie.get(t.id);n&&(ie.delete(t.id),n(t.result));return}As(t,e).catch(n=>e("Error:",n))}async function xr(){let d=(...t)=>console.error("[agentx-mcp]",...t);d("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,c=a+o;if(e.length<c)break;let l=e.slice(a,c);e=e.slice(c),un(l,d)}else{let s=e.indexOf(`
|
|
38
|
+
`);if(s===-1)break;let i=e.slice(0,s).trim();e=e.slice(s+1),i&&un(i,d)}}),process.stdin.on("end",()=>{d("stdin closed, shutting down."),process.exit(0)})}function X(d){process.stdout.write(JSON.stringify(d)+`
|
|
39
|
+
`)}async function As(d,e){let{method:t,id:n,params:s}=d;switch(e(`Received: ${t}`),t){case"initialize":{X({jsonrpc:"2.0",id:n,result:{protocolVersion:$s,capabilities:Ss,serverInfo:vs}});break}case"notifications/initialized":{e("Client initialized.");break}case"tools/list":{X({jsonrpc:"2.0",id:n,result:{tools:xs}});break}case"tools/call":{let i=s?.name,r=s?.arguments||{};try{let o=await Cs(i,r);X({jsonrpc:"2.0",id:n,result:o})}catch(o){X({jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:`Error: ${o.message}`}],isError:!0}})}break}case"ping":{X({jsonrpc:"2.0",id:n,result:{}});break}default:n!==void 0&&X({jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${t}`}})}}var te=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:c}=await i.read();if(a)break;o+=r.decode(c,{stream:!0});let l=o.split(`
|
|
40
|
+
`);o=l.pop()||"";for(let p of l)if(p.startsWith("data: "))try{let u=JSON.parse(p.slice(6));yield{state:u.state,message:u.message?.parts?.[0]?.text,final:u.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 Ps,fetch as Ms}from"undici";var Rs=new Ps({headersTimeout:0,bodyTimeout:0}),st=3,fe=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 te(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,c]of n){let l=this.peers.get(a);if(!l){let p={peer:c,client:new te(c.url,c.token),healthy:!1,agents:[],consecutiveFailures:0};this.peers.set(a,p),s.push(a),o.push([a,p]);continue}l.peer.url!==c.url||l.peer.token!==c.token?(l.peer=c,l.client=new te(c.url,c.token),l.healthy=!1,l.consecutiveFailures=0,r.push(a),o.push([a,l])):l.peer=c}return o.length&&await Promise.allSettled(o.map(([a,c])=>this.discoverPeer(a,c))),{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(p=>p.id));t.healthy=!0,t.lastCheck=new Date,t.agentCard=r,t.agents=r.skills||[],t.consecutiveFailures=0,t.lastError=void 0;let c=new Set(t.agents.map(p=>p.id)),l=a.size!==c.size||[...c].some(p=>!a.has(p));o?(this.log(`Peer "${e}" recovered: ${r.name} (${t.agents.length} skills)`),this.peerChangeCallback?.({peer:e,healthy:!0,skills:[...c],delta:"recovered"})):(this.log(`Peer "${e}" healthy: ${r.name} (${t.agents.length} skills)`),l&&this.peerChangeCallback?.({peer:e,healthy:!0,skills:[...c],delta:"skills-changed"}))}catch(s){t.lastCheck=new Date,t.lastError=s.message,t.consecutiveFailures++,t.consecutiveFailures>=st&&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<st&&this.log(`Peer "${e}" probe failed (${t.consecutiveFailures}/${st}): ${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 c=s.timeoutMs??30*60*1e3,l=new AbortController,p=setTimeout(()=>l.abort(),c),u;try{u=await Ms(o,{method:"POST",headers:a,body:JSON.stringify({agent:r,message:t,...s.senderAgentId?{senderAgentId:s.senderAgentId}:{},...s.context?{context:s.context}:{}}),signal:l.signal,dispatcher:Rs})}catch(m){throw clearTimeout(p),l.signal.aborted?new Error(`Peer "${e}" /task timed out after ${Math.round(c/1e3)}s`):m}if(clearTimeout(p),!u.ok)throw new Error(`Peer "${e}" /task error: ${u.status}`);let f=await u.json();if(f.error)throw new Error(`Peer "${e}" agent error: ${f.error}`);return f.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 _s,writeFileSync as js,existsSync as Es,mkdirSync as Ds}from"fs";import{resolve as pn}from"path";function re(d,e,t="\u2026"){if(!d)return"";if(d.length<=e)return d;let n=e-t.length;if(n<=0)return d.slice(0,e);let s=d.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 it(d,e,t){if(!d)return"";let s=d.split(`
|
|
43
|
+
`).slice(0,e).join(`
|
|
44
|
+
`);return re(s,t)}var Os=30,mn=6e3,Ns=1500,Ls=6e4;function Bs(d){let e=new Date(d),t=e.getUTCHours().toString().padStart(2,"0"),n=Math.floor(e.getUTCMinutes()/15)*15;return`${t}:${n.toString().padStart(2,"0")}`}var ye=class{dir;cache=new Map;constructor(e=pn(process.cwd(),".agentx/groups")){this.dir=e,Ds(this.dir,{recursive:!0})}add(e,t,n){let s=this.load(e),i=Date.now(),r=re(n,Ns),o=s[s.length-1];if(!(o&&o.sender===t&&o.text===r&&i-o.timestamp<Ls)){for(s.push({sender:t,text:r,timestamp:i});s.length>Os;)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 c=i.repeat>1?`${i.line} [\xD7${i.repeat}]`:i.line;if(s+c.length>mn)return!1;if(r.push(c),s+=c.length,i.bucket!==o){let l=`\u2014 ${i.bucket} \u2014`;if(s+l.length>mn)return i=null,!1;r.push(l),s+=l.length,o=i.bucket}return i=null,!0};for(let c=t.length-2;c>=0;c--){let l=t[c],p=`${l.sender}: ${l.text}`,u=Bs(l.timestamp);if(i&&i.line===p&&i.bucket===u){i.repeat++;continue}if(!a())break;i={line:p,repeat:1,bucket:u}}a();for(let c=r.length-1;c>=0;c--)n.splice(1,0,r[c]);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 pn(this.dir,`${t}.json`)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.filePath(e);if(!Es(t))return this.cache.set(e,[]),[];try{let n=JSON.parse(_s(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{js(this.filePath(e),JSON.stringify(t))}catch{}}};var Gs={minChars:80,maxChars:4e3,idleFlushMs:2e3,minIntervalMs:1500,humanPacing:!1},Us={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}},be=class{config;buffer="";emitter;lastEmitTime=0;idleTimer;insideCodeFence=!1;fencePattern=/^```/;lastEmission=Promise.resolve();constructor(e,t,n){let s=n?Us[n]:{};this.config={...Gs,...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 Rn,writeFileSync as _n,existsSync as ot,mkdirSync as jn,appendFileSync as Mn}from"fs";import{resolve as at,dirname as En}from"path";function fn(d){let e=d.group?{type:"group",chatId:d.group.id,name:d.group.name}:d.channel==="gitlab"||d.channel==="github"?d.channel==="gitlab"?{type:"project",project:d.sender.id}:{type:"repo",repo:d.sender.id}:{type:"dm",chatId:d.sender.id};return{id:d.id,channel:d.channel,accountId:d.accountId,sender:{id:d.sender.id,name:d.sender.name,username:d.sender.username,isBot:d.sender.isBot===!0},conversation:e,content:{text:d.text,replyTo:d.replyToText},raw:d}}function yn(d,e,t){let n={...t,atMentionsOnly:!1,trace:[]};for(let s of e){let i=s.run(d,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 c={kind:"drop",reason:`unknown_agent:${i.agentId}`};return n.trace[n.trace.length-1]={stage:s.name,decision:c},{decidingStage:s.name,kind:"drop",reason:c.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 bn=/<!--\s*agentx:([^\s-][^\s>]*?)\s*-->/;function oe(d,e){return bn.test(d)?d:`${d}
|
|
51
|
+
|
|
52
|
+
<!-- agentx:${e} -->`}function J(d){if(!d)return null;let e=d.match(bn);return e?e[1]:null}function rt(d){return d.replace(/\n*<!--\s*agentx:[^>]*?\s*-->/g,"")}var wn={name:"self-reply-guard",run(d,e){if(d.sender.isAgent)return{kind:"drop",reason:`self-reply (agent=${d.sender.agentId??"?"})`};let t=J(d.content.text);return t?{kind:"drop",reason:`agentx-marker (agent=${t})`}:{kind:"pass"}}};var kn={name:"handover",run(d,e){let t=d.conversation.type==="group"||d.conversation.type==="dm"?d.conversation.chatId:d.sender.id,n=e.handoverStore.get(d.channel,t,d.accountId);return n?{kind:"match",agentId:n.toAgent}:{kind:"pass"}}};var vn={name:"adapter-resolved",run(d,e){if(d.channel==="gitlab"){let t=d.raw.resolvedAgent;return t?{kind:"match",agentId:t}:{kind:"drop",reason:"gitlab username has no agent mapping"}}return d.raw.resolvedAgent?{kind:"match",agentId:d.raw.resolvedAgent}:{kind:"pass"}}};var $n={name:"dm-binding",run(d,e){if(d.conversation.type!=="dm")return{kind:"pass"};if(d.channel==="telegram"){let t=e.config.channels.telegram.accounts[d.accountId];return t?.agentBinding?{kind:"match",agentId:t.agentBinding}:{kind:"drop",reason:`telegram dm: no agentBinding for account "${d.accountId}"`}}if(d.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 Sn={name:"bot-policy",run(d,e){return d.sender.isBot&&(e.atMentionsOnly=!0),{kind:"pass"}}};var In={name:"mention",run(d,e){let t=d.channel==="telegram"&&d.conversation.type==="group"&&e.config.channels.telegram.policy.group==="mention-required",n=e.atMentionsOnly||t,s=e.registry.findByMention(d.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 Tn={name:"fallback-binding",run(d,e){if(d.channel==="telegram"){let t=e.config.channels.telegram.accounts[d.accountId];return t?.agentBinding?{kind:"match",agentId:t.agentBinding}:{kind:"drop",reason:`no telegram agentBinding for account "${d.accountId}"`}}if(d.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 xn=[wn,kn,vn,$n,Sn,In,Tn];function Cn(d,e,t,n){let s=[];for(let[o,a]of Object.entries(d))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 Fs=new Set(["telegram","slack","whatsapp","discord"]);function An(d){return Fs.has(d)?d:null}function Hs(d,e,t,n=Date.now){let s=d.accountId||"default",i=d.group?.id||d.sender.id;return{ts:n(),source:e,sourceEventId:`${s}/${d.id}`,project:null,subject:`chat:${i}`,intent:d.replyTo?"message.reply":"message.received",rawJson:t}}function Ws(d){return{decidedBy:"channel-router",decide:()=>({agentId:d.agentId,outcome:d.outcome==="deduped"?"halted":d.outcome,reason:d.outcome==="deduped"?`legacy-dedup: ${d.reason??""}`.trim():d.reason??null})}}function Pn(d,e,t,n,s,i=Date.now){let r=Hs(e,t,n,i),o=Ws(s),a=H(d,r,o,i);return W(d,t,a,s,i),a}var ct=class{filePath;constructor(e){this.filePath=at(e,".agentx/router/inflight.jsonl"),jn(En(this.filePath),{recursive:!0})}start(e){try{let t=JSON.stringify({type:"start",ts:Date.now(),...e})+`
|
|
53
|
+
`;Mn(this.filePath,t)}catch{}}done(e){try{Mn(this.filePath,JSON.stringify({type:"done",id:e,ts:Date.now()})+`
|
|
54
|
+
`)}catch{}}loadUnfinished(){if(!ot(this.filePath))return[];try{let e=Rn(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
|
+
`:"");_n(this.filePath,t)}catch{}}};var Js=4e3,dt=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 ye,this.handoverStore=new Lt({log:(...i)=>s("[handover]",...i)}),this.inflight=new ct(process.cwd()),this.loadDedupFromDisk()}loadDedupFromDisk(){try{let e=at(process.cwd(),this.DEDUP_STORE_PATH);if(!ot(e))return;let t=JSON.parse(Rn(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=at(process.cwd(),this.DEDUP_STORE_PATH),s=En(n);ot(s)||jn(s,{recursive:!0}),_n(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=An(e.channel);if(n&&D(n)!=="off")try{let s=Pn(j(),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,c=this.serviceMatcher.match(t.text,t.sender.id,t.channel);if(c){this.log(`Service matched: "${c.service.name}" for ${t.sender.name} (trigger: ${c.trigger})`),this.recordRouterDecisionInLedger(t,{agentId:null,outcome:"halted",reason:`service-match: ${c.service.name} (trigger: ${c.trigger})`});let l=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",l);let p=this.startTypingLoop(e,a,l);await this.serviceMatcher.execute(c.service,this.registry,{channel:t.channel,sender:t.sender.name,chatId:a},async u=>{clearInterval(p),await this.adapterSend(e,{channel:t.channel,chatId:a,text:u,replyTo:t.id,accountId:l})});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),c=typeof e.editMessage=="function",l,p="",u=c?new be(async S=>{if(p+=S,l)try{await this.adapterEdit(e,s,l,p,void 0,o)}catch{}else{let v=p.length>20?p:`_${r} is writing..._
|
|
58
|
+
|
|
59
|
+
${p}`;try{l=await this.adapterSend(e,{channel:t.channel,chatId:s,text:v,replyTo:t.id,accountId:o})}catch{}}},void 0,t.channel):void 0,f=u?(S,v)=>{u.push(S)}:void 0;if(t.channelMeta?.agents){for(let S of t.channelMeta.agents)if(!S.handle){let v=this.registry.getAgent(S.id);v&&(S.handle=v.mentions.find($=>$.startsWith("@")),S.name=v.name)}}let m=t.group?this.groupLog.buildContext(s):"",g=m?`${m}
|
|
60
|
+
|
|
61
|
+
${t.sender.name}: ${t.text}`:t.text,h=await this.registry.execute({message:g,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}},f);if(clearInterval(a),await u?.flush(),h.error){if(h.error.startsWith("__queued__")){clearInterval(a),this.log(`Message queued for ${r}`);return}this.log(`Agent error: ${h.error}`);let S=`Error: ${h.error}`;l?await this.adapterEdit(e,s,l,S,"plain",o):await this.adapterSend(e,{channel:t.channel,chatId:s,text:S,replyTo:t.id,parseMode:"plain",accountId:o});return}let y=h.content;if(this.hooks?.has("post:channel-message")){let S=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:y,agentId:n});if(S.blocked){this.log(`Response blocked by hook: ${S.message}`);return}S.modified?.response&&(y=S.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&&(l?(await this.adapterEdit(e,s,l,y,void 0,o),b=l):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&&h.duration){let S=(w.longTaskThreshold||30)*1e3;if(h.duration>=S&&!h.error&&w.on?.taskComplete||h.error&&w.on?.taskError){let $=Math.round(h.duration/1e3),k=h.error?"failed":"completed",I=it(t.text,6,300),C=h.error?re(h.error,300):it(h.content,6,400),x=`${k==="failed"?"\u{1F534}":"\u2705"} **${r}** ${k} (${$}s)
|
|
66
|
+
${t.channel}/${t.sender.name}: ${I}
|
|
67
|
+
${C}`;this.sendOutbound({channel:w.destination.channel,chatId:w.destination.chatId,text:x,agentId:n,accountId:w.destination.accountId}).catch(A=>{this.log(`Task notification failed: ${A.message}`)})}}if(this.business&&h.duration&&this.business.recordTaskCompletion(n,Math.round(h.duration/1e3),!h.error,t.channel),t.channel==="gitlab"&&h.duration&&!h.error){let S=this.channels.get("gitlab");S&&S.logTimeSpent(s,h.duration,n).catch(v=>{this.log(`GitLab time tracking failed: ${v.message}`)})}y&&b&&["telegram","whatsapp","discord","slack"].includes(t.channel)&&this.handleBotToBotChain(e,t,n,y,b,0).catch(S=>{this.log(`Bot-to-bot error: ${S.message}`)})}async handleBotToBotChain(e,t,n,s,i,r,o=new Set){if(r>=dt.MAX_BOT_CHAIN_DEPTH){this.log(`Bot-to-bot: max depth (${r}) reached, stopping`);return}o.add(n);for(let[a,c]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(!c.mentions.filter(g=>g.startsWith("@")).some(g=>s.toLowerCase().includes(g.toLowerCase())))continue;this.log(`Bot-to-bot [${r+1}]: "${n}" -> "${a}"`);let u=t.group?.id||t.sender.id,f=this.getAccountForAgent(a),m=this.getAccountForAgent(n);try{this.adapterReact(e,u,i,"\u{1F440}",f);let g=this.startTypingLoop(e,u,f),h=r===0?`[Original from ${t.sender.name}]: ${t.text}
|
|
68
|
+
|
|
69
|
+
[${n} said]: ${s}`:s,y=await this.registry.execute({message:h,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(g),y.content&&!y.error){let b=y.content;t.channel==="whatsapp"&&(b=`*${c.name}*
|
|
70
|
+
|
|
71
|
+
${b}`);let w=await this.adapterSend(e,{channel:t.channel,chatId:u,text:b,accountId:f});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(g){this.log(`Bot-to-bot "${a}" failed: ${g.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,Js)}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?q().emit("message:matched",{channel:e.channel,chatId:String(r),msgId:e.id,accountId:e.accountId,agentId:i,decidingStage:s,at:o}):t==="drop"&&q().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=fn(e);return yn(t,xn,{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 c=this.startTypingLoop(e,o,a);try{let l=await this.mesh.sendTask(i.peer,t.text,r.id,{context:this.buildMeshContext(t,o)});if(clearInterval(c),l){let p=`**${r.name}** _(${i.peer})_:
|
|
72
|
+
|
|
73
|
+
`;await this.adapterSend(e,{channel:t.channel,chatId:o,text:p+l,replyTo:t.id,accountId:a})}return!0}catch(l){return clearInterval(c),this.log(`Mesh routing error: ${l.message}`),await this.adapterSend(e,{channel:t.channel,chatId:o,text:`Error from ${i.peer}/${r.name}: ${l.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(l=>l.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 c=this.startTypingLoop(e,o,a);try{let l=await this.mesh.sendTask(i.peer,t.text,n,{context:this.buildMeshContext(t,o)});return clearInterval(c),l&&await this.adapterSend(e,{channel:t.channel,chatId:o,text:l,replyTo:t.id,accountId:a}),!0}catch(l){return clearInterval(c),this.log(`Mesh routing error for ${n}: ${l.message}`),await this.adapterSend(e,{channel:t.channel,chatId:o,text:`Error from ${i.peer}/${r.name}: ${l.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(u=>u.peer===s);if(!r||!r.healthy)return!1;let o=r.skills.find(u=>u.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,c=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",c);let l=this.startTypingLoop(e,a,c),p=Date.now();this.activeMeshForwards++;try{let u=await this.mesh.sendTask(s,t.text,n,{context:this.buildMeshContext(t,a)}),f=Date.now()-p;if(clearInterval(l),u&&await this.adapterSend(e,{channel:t.channel,chatId:a,text:u,replyTo:t.id,accountId:c,agentId:n}),t.channel==="gitlab"&&f){let m=this.channels.get("gitlab");m&&m.logTimeSpent(a,f,n).catch(g=>{this.log(`GitLab time tracking (mesh) failed: ${g.message}`)})}return!0}catch(u){return clearInterval(l),this.log(`Mesh routing error for ${s}/${n}: ${u.message}`),await this.adapterSend(e,{channel:t.channel,chatId:a,text:`Error from ${s}/${o.name}: ${u.message}`,replyTo:t.id,parseMode:"plain",accountId:c}),!0}finally{this.activeMeshForwards--}}getAccountForAgent(e,t){let n=this.channels.get("telegram");return Cn(this.config.channels.telegram.accounts,e,t,n?.getGroupBotAccounts?.bind(n))}resolveAgent(e){return this.runRoutingPipeline(e).agentId}},ae=dt;pe(ae,"MAX_BOT_CHAIN_DEPTH",3);function we(d){return d.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ce(d){let t=d.replace(/\\([_*\[\]()~`>#+=|{}.!\\-])/g,"$1").split(`
|
|
74
|
+
`),n=[],s=!1,i="",r=[],o=!1,a=[],c=!1;for(let p=0;p<t.length;p++){let u=t[p];if(u.trimStart().startsWith("```"))if(s){s=!1;let h=we(r.join(`
|
|
75
|
+
`)),y=i?`// ${i}
|
|
76
|
+
`:"";n.push(`<pre><code>${y}${h}</code></pre>`),i="";continue}else{s=!0,i=u.trimStart().slice(3).trim(),r=[];continue}if(s){r.push(u);continue}if(o&&!u.trimStart().startsWith(">")&&(n.push("</blockquote>"),o=!1),c&&!u.trim().startsWith("|")&&(c=!1,a=[]),u.trimStart().startsWith("> ")){let h=u.replace(/^>\s*/,"");o||(n.push("<blockquote>"),o=!0),n.push(L(h));continue}let f=u.match(/^(#{1,6})\s+(.+)$/);if(f){n.push(""),n.push(`<b>${L(f[2])}</b>`);continue}if(/^[-*_]{3,}\s*$/.test(u.trim())){n.push("\u2014\u2014\u2014");continue}if(u.trim().startsWith("|")&&u.trim().endsWith("|")){let h=u.split("|").slice(1,-1).map(y=>y.trim());if(/^\|[\s\-:|]+\|$/.test(u.trim())){c=!0;continue}if(!c){a=h,c=!0;continue}if(a.length>0&&h.length>0)if(h.length>=2){let y=[];for(let b=0;b<h.length;b++)if(b===0)y.push(`<b>${L(h[b])}</b>`);else{let w=a[b]?`${L(a[b])}: `:"";y.push(`${w}${L(h[b])}`)}n.push(`\u2022 ${y.join(" \u2014 ")}`)}else n.push(`\u2022 ${L(h[0])}`);continue}let m=u.match(/^(\s*)[-*+]\s+(.+)$/);if(m){let h=m[1].length>0?" ":"";n.push(`${h}\u2022 ${L(m[2])}`);continue}let g=u.match(/^(\s*)\d+[.)]\s+(.+)$/);if(g){let h=g[1].length>0?" ":"",y=u.match(/^(\s*)(\d+)/)?.[2]||"1";n.push(`${h}${y}. ${L(g[2])}`);continue}if(!u.trim()){n.push("");continue}n.push(L(u))}s&&n.push(`<pre><code>${we(r.join(`
|
|
77
|
+
`))}</code></pre>`),o&&n.push("</blockquote>");let l=n.join(`
|
|
78
|
+
`).trim();return l=Ks(l),l}function L(d){let e=we(d);return e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,n,s)=>`<a href="${we(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 zs=/(?<=\w)\.(ts|js|py|rs|go|rb|cs|sh|md|yml|yaml|toml|json|env|css|html|xml|sql|tf|hcl)(?=[\s,;:)\]}<]|$)/gi;function Ks(d){let e=d.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(zs,"<code>.$1</code>")).join("")}import{readFileSync as ht,writeFileSync as Nn,mkdirSync as Ln,existsSync as ut}from"fs";import{resolve as Bn,dirname as Gn}from"path";import{existsSync as Dn,mkdirSync as qs,readFileSync as Xs,renameSync as Vs,writeFileSync as Ys}from"fs";import{dirname as Qs,resolve as Zs}from"path";var gt=class{filePath;data;constructor(e,t=".agentx/cursors.json"){this.filePath=Zs(e,t),this.data={};try{if(Dn(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=Qs(this.filePath);Dn(e)||qs(e,{recursive:!0});let t=`${this.filePath}.tmp`;Ys(t,JSON.stringify(this.data,null,2)),Vs(t,this.filePath)}},lt;function On(d){return lt||(lt=new gt(d??process.cwd())),lt}var pt=class{data={};filePath;dirty=!1;constructor(e){this.filePath=Bn(e,".agentx/telegram/groups.json"),this.load()}load(){try{ut(this.filePath)&&(this.data=JSON.parse(ht(this.filePath,"utf-8")))}catch{this.data={}}}save(){try{Ln(Gn(this.filePath),{recursive:!0}),Nn(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 V=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 pt(process.cwd()),this.cursors=On(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 c of i)if(c&&(c===r||c===o||c.startsWith("@")&&a&&c.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 l=0;l<o.length;l++){o[l]>0&&await new Promise(p=>setTimeout(p,o[l]));try{i=await this.apiCall(t.token,"getMe"),l>0&&this.log(`Bot account "${e}" verified on retry ${l}`);break}catch(p){r=p,l<o.length-1&&this.log(`Verify attempt ${l+1} failed for "${e}" (${p.message}) \u2014 retrying`)}}if(!i)throw r;let a=i.result?.id,c=i.result?.username;this.log(`Bot @${c} ready (account: ${e})`),a&&this.botInfo.set(e,{userId:a,username:c||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 c=this.accounts.get(a),l=e[a];this.accounts.set(a,l),c.token!==l.token&&(await this.stopAccount(a),await this.startAccount(a,l),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?ce(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),c=String(a.result?.message_id||"");return this.recordOutboundShadow(e.chatId,c,s,e.agentId,e.accountId),c}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?ce(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,c=s!=="html"&&s!=="plain"?ce(a):a,l={chat_id:e,message_id:parseInt(t,10),text:c,parse_mode:"HTML"};s==="html"?(l.parse_mode="HTML",l.text=a):s==="plain"&&(delete l.parse_mode,l.text=a);try{return await this.apiCall(r,"editMessageText",l),!0}catch(p){if(p.message?.includes("message is not modified"))return!0;if(l.parse_mode){delete l.parse_mode,l.text=a;try{return await this.apiCall(r,"editMessageText",l),!0}catch{return!1}}return!1}}async sendDraft(e,t,n,s,i){if(!V.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 c=s!=="html"&&s!=="plain"?ce(a):a,l={chat_id:parseInt(e,10),draft_id:t,text:c,parse_mode:"HTML"};s==="plain"?(delete l.parse_mode,l.text=a):s==="html"&&(l.text=a);try{return await this.apiCall(r,"sendMessageDraft",l),!0}catch{if(l.parse_mode){delete l.parse_mode,l.text=a;try{return await this.apiCall(r,"sendMessageDraft",l),!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 c=a.message,l=c.text||c.caption||"",p,u=c.photo&&c.photo.length>0,f=!!c.voice,m=!!c.audio,g=!!c.video,h=!!c.document;if(u||f||m||g||h){let v,$="application/octet-stream";if(u?(v=c.photo[c.photo.length-1].file_id,$="image/jpeg",l||(l="[Photo attached \u2014 please describe what you see]")):f?(v=c.voice.file_id,$=c.voice.mime_type||"audio/ogg",l||(l="[Voice message \u2014 please transcribe and respond]")):m?(v=c.audio.file_id,$=c.audio.mime_type||"audio/mpeg",l||(l=`[Audio: ${c.audio.title||"audio file"}]`)):g?(v=c.video.file_id,$=c.video.mime_type||"video/mp4",l||(l="[Video attached]")):h&&(v=c.document.file_id,$=c.document.mime_type||"application/octet-stream",l||(l=`[Document: ${c.document.file_name||"file"}]`)),v)try{let I=(await this.apiCall(t.token,"getFile",{file_id:v})).result?.file_path;if(I){let C=`https://api.telegram.org/file/bot${t.token}/${I}`,x=await fetch(C);if(x.ok){let A=Buffer.from(await x.arrayBuffer()),R=$.split("/")[1]?.split(";")[0]||"bin",{mkdirSync:O,writeFileSync:Y}=await import("fs"),{randomUUID:P}=await import("crypto"),{resolve:U,join:N}=await import("path"),Q=U(process.cwd(),".agentx/media/telegram");O(Q,{recursive:!0});let F=c.document?.file_name||`${P()}.${R}`,Z=N(Q,F);Y(Z,A),p={path:Z,type:$,fileName:F}}}}catch(k){this.log(`Media download failed: ${k.message}`)}}if(!l)continue;if(!this.isAllowed(e,c.from?.id,c.chat?.id,c.from?.username)){this.log(`[telegram/${e}] dropped message from ${c.from?.id}${c.from?.username?` (@${c.from.username})`:""} in chat ${c.chat?.id} \u2014 not in allowlist`);continue}let b=c.chat.type!=="private",w=String(c.chat.id),T;b&&(this.groupStore.hasGroup(w)||await this.seedGroupMembership(w,c.chat.title),T=await this.getChannelMeta(w));let S={id:String(c.message_id),channel:"telegram",accountId:e,sender:{id:String(c.from.id),name:[c.from.first_name,c.from.last_name].filter(Boolean).join(" "),username:c.from.username,isBot:c.from.is_bot===!0},group:b?{id:w,name:c.chat.title||""}:void 0,text:l,media:p,replyTo:c.reply_to_message?String(c.reply_to_message.message_id):void 0,replyToText:c.reply_to_message?c.reply_to_message.text||c.reply_to_message.caption||`[message from ${c.reply_to_message.from?.first_name||"unknown"}]`:void 0,timestamp:new Date(c.date*1e3),raw:a,channelMeta:T};this.chatAccountMap.set(String(c.chat.id),e);try{this.appendShadowLog(String(c.chat.id),{externalId:String(c.message_id),role:"user",name:S.sender.name,content:l,timestamp:S.timestamp.toISOString(),accountId:e})}catch(v){this.log(`shadow-log write failed: ${v.message}`)}this.handler(S).catch(v=>{this.log(`Error handling message: ${v.message}`)})}if(a.my_chat_member){let c=a.my_chat_member,l=String(c.chat.id),p=c.chat.title,u=c.new_chat_member.status,f=c.new_chat_member.user.username||e;this.groupStore.setBotStatus(l,p,e,t.agentBinding,f,u),this.log(`Group membership: @${f} is now "${u}" in "${p||l}"`)}}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)V.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(ut(s))try{i=JSON.parse(ht(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),Ln(Gn(s),{recursive:!0}),Nn(s,JSON.stringify(i,null,2)))}shadowLogPath(e,t){let n=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Bn(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 c=a.toISOString().slice(0,10),l=this.shadowLogPath(e,c);if(ut(l)){try{let u=(JSON.parse(ht(l,"utf-8")).messages??[]).slice();for(let f=u.length-1;f>=0;f--){let m=u[f];if(!(t.sinceISO&&m.timestamp<t.sinceISO)&&(n.push({role:m.role,name:m.name,content:m.content,timestamp:m.timestamp,externalId:m.externalId,accountId:m.accountId}),s+=m.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 Fn,writeFileSync as ai}from"fs";import{resolve as Hn,join as ci}from"path";import{randomUUID as di}from"crypto";import{readFileSync as ei,writeFileSync as ti,mkdirSync as ni,existsSync as Un}from"fs";import{resolve as si,dirname as ii}from"path";var ke=class{contacts=new Map;chats=new Map;groups=new Map;cachePath;constructor(e){this.cachePath=si(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:ri(s),updatedAt:t},r={...i,pushName:mt(n.notify,n.pushName,i.pushName),savedName:mt(n.name,n.verifiedName,i.savedName),status:mt(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:oi(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=ii(this.cachePath);Un(t)||ni(t,{recursive:!0}),ti(this.cachePath,JSON.stringify(e,null,2),"utf8")}load(){if(Un(this.cachePath))try{let e=JSON.parse(ei(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 ri(d){let e=d.split("@")[0]??"";return!e||d.endsWith("@lid")?"":e.replace(/[^0-9]/g,"")}function mt(...d){for(let e of d)if(typeof e=="string"&&e.length>0)return e}function oi(d){if(typeof d=="number"&&Number.isFinite(d))return d;if(d&&typeof d=="object"&&"low"in d&&"high"in d){let e=d.low;return d.high*4294967296+(e>>>0)}}var $e=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=Hn(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 ke(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}Fn(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:l}=await s.fetchLatestBaileysVersion();a=l,this.log(`WhatsApp Web version: ${l.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...l)=>this.log("WA error:",...l),child:()=>c};this.sock=e({auth:{creds:r.creds,keys:s.makeCacheableSignalKeyStore?s.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,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",l=>{this.log(`WA history sync: ${l.messages?.length||0} messages, ${l.isLatest?"latest":"partial"}`);try{this.cache.applyHistorySet(l)}catch(p){this.log(`cache history-set error: ${p.message}`)}}),this.sock.ev.on("contacts.update",l=>{try{this.cache.applyContactsUpdate(l)}catch(p){this.log(`cache contacts.update error: ${p.message}`)}}),this.sock.ev.on("contacts.upsert",l=>{try{this.cache.applyContactsUpdate(l)}catch(p){this.log(`cache contacts.upsert error: ${p.message}`)}}),this.sock.ev.on("chats.upsert",l=>{try{this.cache.applyChatsUpsert(l)}catch(p){this.log(`cache chats.upsert error: ${p.message}`)}}),this.sock.ev.on("chats.update",l=>{try{this.cache.applyChatsUpsert(l)}catch(p){this.log(`cache chats.update error: ${p.message}`)}}),this.sock.ev.on("groups.update",l=>{try{this.cache.applyGroupsUpdate(l)}catch(p){this.log(`cache groups.update error: ${p.message}`)}}),this.sock.ev.on("connection.update",async l=>{let{connection:p,lastDisconnect:u,qr:f}=l;if(i===this.generation){if(f){this.log("Scan QR code with WhatsApp to connect:");try{this.onQR?.(f)}catch{}try{let{default:m}=await import("qrcode-terminal");m.generate(f,{small:!0})}catch{this.log(`QR: ${f}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(p)try{this.onStatus?.(p,u?.error?.message)}catch{}if(p==="open")try{this.onQR?.(null)}catch{}if(p==="close"){let m=u?.error?.output?.statusCode,g=u?.error?.output?.payload?.message||"";if(this.log(`WhatsApp connection closed (status: ${m}, reason: ${g})`),m===n?.loggedOut||m===401)this.log("Logged out. Delete session dir and restart to re-scan QR.");else if(m===440||m===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 h=Math.min(1e4*Math.pow(2,this.reconnectAttempts-1),12e4);this.log(`Reconnecting in ${h/1e3}s (attempt ${this.reconnectAttempts}/5)...`),setTimeout(()=>this.start(),h)}else m===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):m!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}p==="open"&&this.log("WhatsApp connected")}}),this.sock.ev.on("messages.upsert",async l=>{if(this.reconnectAttempts>0&&(this.log(`WhatsApp connection stable, resetting reconnect counter (was ${this.reconnectAttempts})`),this.reconnectAttempts=0),this.log(`WA messages.upsert: ${l.messages?.length||0} messages, type: ${l.type}`),!!this.handler)for(let p of l.messages||[]){let u=(p.key.remoteJid||"").replace(/@.*/,"").slice(-6),f=!!(p.message?.conversation||p.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${u} fromMe=${p.key.fromMe} hasText=${f} type=${Object.keys(p.message||{}).join(",")}`),p.key.remoteJid==="status@broadcast")continue;if(p.key.id&&this.sentMessageIds.has(p.key.id)){this.sentMessageIds.delete(p.key.id);continue}if(p.key.fromMe){let P=this.sock?.user,U=p.key.remoteJid||"",N=P?.id?.replace(/:.*/,"")||"",Q=P?.lid?.replace(/:.*/,"")||"",F=U.replace(/:.*/,"").replace(/@.*/,"");if(!(F===N||F===Q))continue}let m=p.message?.conversation||p.message?.extendedTextMessage?.text||p.message?.imageMessage?.caption||p.message?.videoMessage?.caption||"",g=p.message||{},h=!!g.imageMessage,y=!!g.audioMessage,b=!!g.videoMessage,w=!!g.documentMessage,T=!!g.stickerMessage,S=h||y||b||w||T;if(S&&!m&&(h?m="[Image attached \u2014 please describe what you see]":y?m="[Voice message attached \u2014 please transcribe and respond]":b?m="[Video attached]":w?m=`[Document: ${g.documentMessage?.fileName||"file"}]`:T&&(m="[Sticker]")),!m)continue;let v=p.key.remoteJid||"",$=v.endsWith("@g.us"),k=v.replace(/@.*$/,""),C=($?p.key.participant||"":v).replace(/@.*$/,"");if(this.allowFrom?.length&&!p.key.fromMe&&!this.allowFrom.some(U=>{let N=U.replace(/\+/g,"");return C.includes(N)||k.includes(N)}))continue;let x=p.key.fromMe?"me":p.pushName||C,A;if($&&this.sock)try{A=(await this.sock.groupMetadata(v)).subject}catch{}let R=this.resolveAgent(C,A,$?v:void 0);if(!R){this.log(`No route for ${$?`group ${A||v}`:C}, skipping`);continue}let O;if(S&&this.sock)try{let U=await(await import("@whiskeysockets/baileys")).downloadMediaMessage(p,"buffer",{},{reuploadRequest:this.sock.updateMediaMessage,logger:this.sock.logger});if(U){let N=g.imageMessage?.mimetype||g.audioMessage?.mimetype||"audio/ogg",Q=N.split("/")[1]?.split(";")[0]||"bin",F=Hn(this.sessionDir,"../media/inbound");Fn(F,{recursive:!0});let Z=g.documentMessage?.fileName||`${di()}.${Q}`,Ve=ci(F,Z);ai(Ve,U),O={path:Ve,type:N,fileName:Z},this.log(`WA media saved: ${N} -> ${Ve}`)}}catch(P){this.log(`WA media download failed: ${P.message}`)}let Y={id:p.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:p.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||C)+"@s.whatsapp.net":C,name:x,username:C},group:$?{id:v,name:A||v}:void 0,text:m,media:O,replyTo:p.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((p.messageTimestamp||0)*1e3),raw:p,resolvedAgent:R};this.handler(Y).catch(P=>{this.log(`Error handling message: ${P.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(Wn)}listChats(){return this.cache.listChats().map(li)}async getContactProfile(e){let t=this.cache.getContact(e);return t?Wn(t):null}async getGroupMetadata(e){let t=this.cache.getGroup(e);if(t&&t.subject)return ve(t);if(!this.isConnected())return t?ve(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?ve(s):null}catch(n){return this.log(`getGroupMetadata(${e}) failed: ${n.message}`),t?ve(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(gi).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 Jn(s)}let n=Date.now()-this.lastReadAt;return n<this.throttleMinMs&&await Jn(this.throttleMinMs-n),this.lastReadAt=Date.now(),this.readsInWindow.push(this.lastReadAt),e()}};function Wn(d){return{jid:d.jid,phone:d.phone,name:d.savedName||d.pushName||d.phone||d.jid,pushName:d.pushName,savedName:d.savedName,status:d.status,updatedAt:d.updatedAt}}function li(d){return{jid:d.jid,name:d.name||d.jid.replace(/@.*$/,""),isGroup:d.isGroup,lastMessageAt:d.lastMessageAt,unreadCount:d.unreadCount}}function ve(d){return{jid:d.jid,subject:d.subject||"",description:d.description,owner:d.owner,members:d.members.map(e=>({jid:e.jid,admin:e.admin})),memberCount:d.members.length}}function gi(d){if(!d||!d.key)return null;let e=d.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 d.messageTimestamp=="number"?d.messageTimestamp:d.messageTimestamp?.low??void 0;return{id:d.key.id,fromJid:d.key.fromMe?d.key.remoteJid||"":d.key.participant||d.key.remoteJid||"",fromMe:!!d.key.fromMe,timestamp:s,text:t,media:n}}function Jn(d){return new Promise(e=>setTimeout(e,Math.max(0,d)))}import{createServer as ur}from"http";import{writeFileSync as ys,existsSync as ue,unlinkSync as pr,mkdirSync as bs,readFileSync as Xe,watch as mr}from"fs";import{resolve as B,dirname as fr}from"path";var Se=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(c=>{this.log(`Error handling message: ${c.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 Ie=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 c=a.channel_type==="im",l=this.botUserId&&a.text.includes(`<@${this.botUserId}>`);if(!c&&!l)return;let p=a.text;if(this.botUserId&&(p=p.replace(new RegExp(`<@${this.botUserId}>`,"g"),"").trim()),!p)return;let u=a.user||"slack-user";try{let m=await this.web.users.info({user:a.user});u=m?.user?.profile?.display_name||m?.user?.real_name||u}catch{}let f={id:a.client_msg_id||a.ts,channel:"slack",accountId:"default",sender:{id:a.user,name:u,username:u},group:c?void 0:{id:a.channel,name:a.channel},text:p,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(f)}catch(m){this.log(`Error handling message: ${m.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 fi}from"http";function hi(d,e,t,n=Date.now){return{ts:n(),source:"gitlab",sourceEventId:`${d.entityKind}:${d.iid}:${d.action}:${e.agentId}:${e.trigger}`,project:d.project,subject:`${d.entityKind}:${d.iid}:agent:${e.agentId}:trigger:${e.trigger}`,intent:`${d.entityKind}.${d.action}`,rawJson:t}}function ui(d,e){return{decidedBy:`gitlab:${d}:target-${e.trigger}`,decide:()=>({agentId:e.agentId,outcome:"dispatched",reason:null})}}function Te(d,e,t,n,s,i=Date.now){let r=hi(e,t,n,i),o=ui(e.entityKind,t),a=H(d,r,o,i);return W(d,"gitlab",a,s,i),a}function pi(d,e,t=Date.now){return{ts:t(),source:"gitlab",sourceEventId:`note:${d.noteId}`,project:d.project,subject:`${d.noteableType}:${d.noteableIid}:note:${d.noteId}`,intent:`note.${d.noteableType}`,rawJson:e}}function mi(d){return{decidedBy:"gitlab:note:mention",decide:()=>({agentId:d,outcome:d?"dispatched":"halted",reason:d?null:"no @mention resolved to an agent"})}}function ft(d,e,t,n,s=Date.now){let i=pi(e,t,s),r=mi(n.agentId),o=H(d,i,r,s);return W(d,"gitlab",o,n,s),o}function zn(d,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},c=H(d,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 W(d,"gitlab",c,i,r),c}var xe=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=fi(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(p=>p.agentId===e.agentId),c=this.getAgentToken(e.agentId);if(!c&&a?.node&&this.sendNoteForwarder)try{let p=oe(e.text,e.agentId||"unknown"),u=await this.sendNoteForwarder(a.node,i,s,n,e.agentId||"",p);return u&&this.sentNoteIds.add(u),u}catch(p){return this.log(`GitLab send forward to "${a.node}" failed: ${p.message} \u2014 skipping (would post as group bot)`),""}let l=c||this.config.token;K.webhook("gitlab","send",`agentId="${e.agentId}" token=${c?"per-agent":"GLOBAL("+this.botUsername+")"}`);try{let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":l},body:JSON.stringify({body:oe(e.text,e.agentId||"unknown")})});if(!p.ok){let m=await p.text();return this.log(`GitLab API error: ${p.status} ${m}`),""}let u=await p.json(),f=String(u.id||"");return f&&this.sentNoteIds.add(f),f}catch(p){return this.log(`GitLab send error: ${p.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=J(n);if(o){let $=n.match(/@(\w[\w.-]*)/g)?.map(I=>I.slice(1).replace(/[.]+$/,""))||[];if(!$.some(I=>{let C=this.usernameToAgent.get(I.toLowerCase());return C&&C!==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 ${$.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($=>$.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 c="",l="",p="";e.issue?(c="issue",l=String(e.issue.iid),p=e.issue.title):e.merge_request&&(c="merge_request",l=String(e.merge_request.iid),p=e.merge_request.title),K.webhook("gitlab","handleNote",`noteId=${r} mentions=[${a.join(",")}] user=${i.username}`);let u=this.resolveAgentFromMention(n);if(K.webhook("gitlab","resolve",`agentId=${u??"NONE"}`),!u){if(this.log(`[handleNote] @mentions in note ${r} are not agents (${a.join(", ")}), skipping`),D("gitlab")!=="off")try{ft(j(),{noteId:r,project:s,noteableType:c,noteableIid:l,mentions:a.map($=>$.toLowerCase())},JSON.stringify(e),{agentId:null,outcome:"halted",reason:`unresolved-mentions: ${a.join(",")}`})}catch($){this.log(`[ledger] gitlab note ${r} (no-resolve) record failed: ${$?.message??$}`)}t.writeHead(200),t.end("ok");return}let f=u,m=this.config.agentMappings?.find($=>$.agentId===f),g=m?.token,h=m?.node;K.webhook("gitlab","token",`agent="${f}" mapping=${m?"found":"MISSING"} hasToken=${!!g} node=${h??"local"}`),this.reactToNote(s,c,l,e.object_attributes.id,g,h,f).catch(()=>{});let y=`${s}:${c}:${l}`,b=await this.getChannelMeta(y),w=rt(n),T=await this.downloadNoteImages(w,s,g||this.config.token),S;if(D("gitlab")!=="off")try{let $=ft(j(),{noteId:r,project:s,noteableType:c,noteableIid:l,mentions:a.map(k=>k.toLowerCase())},JSON.stringify(e),{agentId:f,outcome:"dispatched",reason:`mention:${a[0]}`});$.outcome==="dispatched"&&(S={eventId:$.eventId,decidedBy:$.decidedBy})}catch($){this.log(`[ledger] gitlab note ${r} record failed: ${$?.message??$}`)}let v={id:String(e.object_attributes.id),channel:"gitlab",accountId:"default",sender:{id:y,name:i.name,username:i.username},text:`[GitLab ${s} ${c} #${l}: ${p}]
|
|
79
|
+
${i.name} commented:
|
|
80
|
+
${w}`,timestamp:new Date,raw:e,resolvedAgent:f,preferNode:m?.node,channelMeta:b?{...b,issue:{type:c,iid:l,title:p}}:void 0,media:T,intentRef:S};this.handler(v).catch($=>{this.log(`Error handling note: ${$.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 f=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});f.blocked&&(a=!0);let m=f.modified?.dispatch;Array.isArray(m)&&m.length>0&&(o=m.filter(g=>g&&typeof g.agentId=="string"))}catch(f){this.log(`on:gitlab-issue hook error: ${f.message}`)}if(o&&o.length>0){let f=D("gitlab")!=="off",m=f?{entityKind:"issue",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url}:null,g=f?JSON.stringify(e):"";for(let h of o){let y=this.config.agentMappings?.find($=>$.agentId===h.agentId),b=`${s}:issue:${n.iid}`,w=await this.getChannelMeta(b),T=`issue-hook-${n.iid}-${h.agentId}${h.assignee?`-${h.assignee}`:""}-${n.action}`,S;if(m)try{let $=Te(j(),m,{agentId:h.agentId,trigger:"hook-dispatch"},g,{agentId:h.agentId,outcome:"dispatched",reason:h.preferNode?`hook (node:${h.preferNode})`:"hook"});$.outcome==="dispatched"&&(S={eventId:$.eventId,decidedBy:$.decidedBy})}catch($){this.log(`[ledger] gitlab issue #${n.iid} hook-dispatch ${h.agentId} record failed: ${$?.message??$}`)}let v={id:T,channel:"gitlab",accountId:"default",sender:{id:b,name:e.user.name,username:e.user.username},text:h.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:h.agentId,preferNode:h.preferNode||y?.node,channelMeta:w?{...w,issue:{type:"issue",iid:String(n.iid),title:n.title}}:void 0,intentRef:S};this.log(`Issue #${n.iid} hook dispatch -> agent "${h.agentId}"${h.preferNode||y?.node?` (remote: ${h.preferNode||y?.node})`:""}`),this.handler(v).catch($=>this.log(`Error handling hook dispatch: ${$.message}`))}t.writeHead(200),t.end("ok");return}if(a){if(this.log(`Issue #${n.iid}: on:gitlab-issue hook suppressed default dispatch`),D("gitlab")!=="off")try{zn(j(),{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(f){this.log(`[ledger] gitlab issue #${n.iid} hook-blocked record failed: ${f?.message??f}`)}t.writeHead(200),t.end("ok");return}if(r){t.writeHead(200),t.end("ok");return}let c=this.computeIssueTargets(e,i);if(c.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 l=D("gitlab")!=="off",p=l?{entityKind:"issue",project:s,iid:n.iid,action:n.action,title:n.title,description:n.description,url:n.url}:null,u=l?JSON.stringify(e):"";for(let f of c){let m=`${s}:issue:${n.iid}:${f.agentId}:${n.action}:${f.trigger}`,g=this.isDispatchedRecently(m),h;if(p)try{let y=Te(j(),p,f,u,g?{agentId:null,outcome:"deduped",reason:"isDispatchedRecently"}:{agentId:f.agentId,outcome:"dispatched"});y.outcome==="dispatched"&&(h={eventId:y.eventId,decidedBy:y.decidedBy})}catch(y){this.log(`[ledger] gitlab issue #${n.iid} target ${f.agentId} record failed: ${y?.message??y}`)}if(g)this.log(`Issue #${n.iid}: skip duplicate dispatch ${m}`);else{this.markDispatched(m);let y=this.config.agentMappings?.find(v=>v.agentId===f.agentId),b=`${s}:issue:${n.iid}`,w=await this.getChannelMeta(b),T=f.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}`,S={id:`issue-${n.iid}-${n.action}-${f.agentId}-${f.trigger}`,channel:"gitlab",accountId:"default",sender:{id:b,name:e.user.name,username:e.user.username},text:T,timestamp:new Date,raw:e,resolvedAgent:f.agentId,preferNode:y?.node,channelMeta:w?{...w,issue:{type:"issue",iid:String(n.iid),title:n.title}}:void 0,intentRef:h};this.log(`Issue #${n.iid} -> agent "${f.agentId}" (trigger: ${f.trigger})`),this.handler(S).catch(v=>this.log(`Error handling issue: ${v.message}`))}}t.writeHead(200),t.end("ok")}computeIssueTargets(e,t){let n=[],s=new Set,i=(l,p)=>{!l||s.has(l)||(s.add(l),n.push({agentId:l,trigger:p}))},o=(e.object_attributes.description||"").match(/@(\w[\w.-]*)/g)?.map(l=>l.slice(1).replace(/[.]+$/,"").toLowerCase())||[];for(let l of o)i(this.usernameToAgent.get(l),"mention");let a=new Set((e.changes?.assignees?.previous??[]).map(l=>l.username.toLowerCase())),c=(e.changes?.assignees?.current??[]).map(l=>l.username.toLowerCase());for(let l of c)a.has(l)||i(this.usernameToAgent.get(l),"assignee-added");if(n.length===0){let l=(e.assignees??[]).map(p=>p.username.toLowerCase());for(let p of l)i(this.usernameToAgent.get(p),"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=D("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,c=o?JSON.stringify(e):"";for(let l of r){let p=`${s}:merge_request:${n.iid}:${l.agentId}:${n.action}:${l.trigger}`,u=this.isDispatchedRecently(p),f;if(a)try{let m=Te(j(),a,l,c,u?{agentId:null,outcome:"deduped",reason:"isDispatchedRecently"}:{agentId:l.agentId,outcome:"dispatched"});m.outcome==="dispatched"&&(f={eventId:m.eventId,decidedBy:m.decidedBy})}catch(m){this.log(`[ledger] gitlab MR !${n.iid} target ${l.agentId} record failed: ${m?.message??m}`)}if(!u){this.markDispatched(p);let m=this.config.agentMappings?.find(T=>T.agentId===l.agentId),g=`${s}:merge_request:${n.iid}`,h=await this.getChannelMeta(g),b=l.trigger==="assignee-added"||l.trigger==="reviewer-added"?`[GitLab ${s} MR !${n.iid} ${l.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 ${l.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}-${l.agentId}-${l.trigger}`,channel:"gitlab",accountId:"default",sender:{id:g,name:e.user.name,username:e.user.username},text:b,timestamp:new Date,raw:e,resolvedAgent:l.agentId,preferNode:m?.node,channelMeta:h?{...h,issue:{type:"merge_request",iid:String(n.iid),title:n.title}}:void 0,intentRef:f};this.log(`MR !${n.iid} -> agent "${l.agentId}" (trigger: ${l.trigger})`),this.handler(w).catch(T=>this.log(`Error handling MR: ${T.message}`))}}t.writeHead(200),t.end("ok")}computeMRTargets(e,t){let n=[],s=new Set,i=(l,p)=>{!l||s.has(l)||(s.add(l),n.push({agentId:l,trigger:p}))},o=(e.object_attributes.description||"").match(/@(\w[\w.-]*)/g)?.map(l=>l.slice(1).replace(/[.]+$/,"").toLowerCase())||[];for(let l of o)i(this.usernameToAgent.get(l),"mention");let a=new Set((e.changes?.assignees?.previous??[]).map(l=>l.username.toLowerCase()));for(let l of e.changes?.assignees?.current??[]){let p=l.username.toLowerCase();a.has(p)||i(this.usernameToAgent.get(p),"assignee-added")}let c=new Set((e.changes?.reviewers?.previous??[]).map(l=>l.username.toLowerCase()));for(let l of e.changes?.reviewers?.current??[]){let p=l.username.toLowerCase();c.has(p)||i(this.usernameToAgent.get(p),"reviewer-added")}if(n.length===0){for(let l of e.assignees??[])i(this.usernameToAgent.get(l.username.toLowerCase()),"assignee-current");for(let l of e.reviewers??[])i(this.usernameToAgent.get(l.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(c=>c.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 c=this.config.token;if(!c)return[];let l;try{let m=await fetch(a,{headers:{"PRIVATE-TOKEN":c}});if(!m.ok)return[];l=await m.json()}catch{return[]}let p=[],u=0,f=t.sinceISO?new Date(t.sinceISO).getTime():0;for(let m of l){if(m.system||f&&new Date(m.created_at).getTime()<f)continue;let g=J(m.body),h=rt(m.body);if(p.push({role:g?"agent":"user",name:m.author?.name||m.author?.username||(g??"user"),content:h,timestamp:m.created_at,externalId:String(m.id)}),u+=h.length,p.length>=t.maxMessages||u>=t.maxChars)break}return p}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),c;switch(t){case"issue":c=`${this.config.host}/api/v4/projects/${a}/issues/${n}/notes/${s}/award_emoji`;break;case"merge_request":c=`${this.config.host}/api/v4/projects/${a}/merge_requests/${n}/notes/${s}/award_emoji`;break;default:return}try{let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":i},body:JSON.stringify({name:"eyes"})});l.ok||this.log(`Reaction failed on note ${s}: ${l.status}`)}catch(l){this.log(`Failed to react to note ${s}: ${l.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)),c=Math.floor(a/3600),l=Math.ceil(a%3600/60),p=c>0?`${c}h${l>0?` ${l}m`:""}`:`${l}m`,u=encodeURIComponent(o),f=r==="merge_request"?"merge_requests":"issues",m=`${this.config.host}/api/v4/projects/${u}/${f}/${i}/add_spent_time`,g=this.config.agentMappings?.find(b=>b.agentId===n),h=this.getAgentToken(n);if(!h&&g?.node&&this.logTimeForwarder){try{await this.logTimeForwarder(g.node,o,r,i,n||"",t),this.log(`Time logged (via peer "${g.node}"): ${p} on ${o} ${f}/${i} (${n})`)}catch(b){this.log(`Time log forward to "${g.node}" failed: ${b.message} \u2014 skipping (would log as group bot)`)}return}let y=h||this.config.token;try{let b=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":y},body:JSON.stringify({duration:p})});if(b.ok)this.log(`Time logged: ${p} 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(m=>m.agentId===o),c=this.getAgentToken(o);if(!c&&a?.node&&this.createIssueForwarder)try{let m=await this.createIssueForwarder(a.node,t,n,s,i,r,o||"");return m&&this.log(`Issue created (via peer "${a.node}") #${m.iid} on ${t}`),m}catch(m){return this.log(`Issue-create forward to "${a.node}" failed: ${m.message}`),null}let l=c||this.config.token;if(!l)return this.log(`Issue-create failed: no token available for agent "${o||"global"}"`),null;let p=encodeURIComponent(t),u=`${this.config.host}/api/v4/projects/${p}/issues`,f=new URLSearchParams;f.set("title",n),s&&f.set("description",s),i.length>0&&f.set("labels",i.join(","));for(let m of r)try{let g=await fetch(`${this.config.host}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":l}});if(g.ok){let h=await g.json();h[0]?.id&&f.append("assignee_ids[]",String(h[0].id))}}catch(g){this.log(`Issue-create: failed to resolve assignee "${m}": ${g.message}`)}try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","PRIVATE-TOKEN":l},body:f.toString()});if(!m.ok){let h=await m.text();return this.log(`Issue-create failed (${m.status}): ${h.slice(0,200)}`),null}let g=await m.json();return this.log(`Issue created #${g.iid} on ${t} (${o||"global"})`),{iid:g.iid,url:g.web_url}}catch(m){return this.log(`Issue-create error: ${m.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(m=>m.agentId===o),c=this.getAgentToken(o);if(!c&&a?.node&&this.setLabelsForwarder)try{let m=await this.setLabelsForwarder(a.node,t,n,s,i,r,o||"");return m&&this.log(`Labels updated (via peer "${a.node}") on ${t} ${n}/${s}`),m}catch(m){return this.log(`setLabels forward to "${a.node}" failed: ${m.message}`),null}let l=c||this.config.token;if(!l)return this.log(`setLabels failed: no token for "${o||"global"}"`),null;let p=n==="merge_request"?"merge_requests":"issues",u=`${this.config.host}/api/v4/projects/${encodeURIComponent(t)}/${p}/${s}`,f=new URLSearchParams;i.length&&f.set("add_labels",i.join(",")),r.length&&f.set("remove_labels",r.join(","));try{let m=await fetch(u,{method:"PUT",headers:{"Content-Type":"application/x-www-form-urlencoded","PRIVATE-TOKEN":l},body:f.toString()});if(!m.ok){let h=await m.text();return this.log(`setLabels failed (${m.status}): ${h.slice(0,200)}`),null}return(await m.json()).labels??[]}catch(m){return this.log(`setLabels error: ${m.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 c=Buffer.from(await a.arrayBuffer()),l=a.headers.get("content-type")||"image/png",p=l.split("/")[1]?.split(";")[0]||"png",{mkdirSync:u,writeFileSync:f}=await import("fs"),{resolve:m}=await import("path"),{randomUUID:g}=await import("crypto"),h=m(process.cwd(),".agentx/media/gitlab");u(h,{recursive:!0});let y=`${g().slice(0,8)}.${p}`,b=m(h,y);return f(b,c),this.log(`Downloaded GitLab image: ${b} (${c.length} bytes)`),{path:b,type:l,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 yi,createSign as bi}from"crypto";import{readFileSync as Kn}from"fs";var Ce=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=Kn(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(m=>m.agentId===e.agentId),o=this.getAgentToken(e.agentId),a=e.agentId||"unknown",l=!!this.appPrivateKey?"":`> \u{1F916} **${a}** (via AgentX)
|
|
100
|
+
|
|
101
|
+
`,p=oe(`${l}${e.text}`,a),u=o||await this.getTokenForRepo(i);if(!u&&r?.node&&this.sendCommentForwarder)try{let m=await this.sendCommentForwarder(r.node,i,n,a,p);if(m)return this.sentCommentIds.add(m),m;this.log(`GitHub send forward to "${r.node}" returned empty \u2014 no local token available either`)}catch(m){this.log(`GitHub send forward to "${r.node}" failed: ${m.message}`)}if(!u)return this.log(`No GitHub token available for posting comment (agent: ${e.agentId})`),"";let f=`https://api.github.com/repos/${i}/issues/${n}/comments`;try{let m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`,Accept:"application/vnd.github+json","User-Agent":"AgentX"},body:JSON.stringify({body:p})});if(!m.ok){let y=await m.text();return this.log(`GitHub API error: ${m.status} ${y.slice(0,200)}`),""}let g=await m.json(),h=String(g.id||"");return h&&this.sentCommentIds.add(h),h}catch(m){return this.log(`GitHub send error: ${m.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 c of this.config.routes)(c.repo===o||c.repo==="*")&&a.push({id:c.agent,name:c.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=J(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,c=`${n}:${o?"pull":"issue"}:${e.issue.number}`,l=this.resolveAgent(n),p=l?this.config.agentMappings?.find(m=>m.agentId===l):void 0,u=await this.getChannelMeta(c),f={id:r,channel:"github",accountId:"default",sender:{id:c,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:l,preferNode:p?.node,channelMeta:u};this.reactToComment(n,t.id).catch(()=>{}),this.handler(f).catch(m=>this.log(`Error handling issue_comment: ${m.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(l=>l.agentId===r):void 0,a=await this.getChannelMeta(i),c={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(c).catch(l=>this.log(`Error handling PR: ${l.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)||J(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(c=>c.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(c=>this.log(`Error handling issue: ${c.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(c=>c.agentId===i):void 0,o=s.slice(0,5).map(c=>` - ${c.message.split(`
|
|
113
|
+
`)[0]} (${c.author?.name||c.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(c=>this.log(`Error handling push: ${c.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 Kn(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="+yi("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=bi("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 z(d){return d.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(z)),this.log=n,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,t){return`${e}|${z(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(),c=o.filter(l=>l.expiresAt>a);for(let{signal:l}of c)this.deliverTo(s,l);this.pending.delete(r),c.length&&this.log(`flushed ${c.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=z(e.to);if(t===z(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&&z(n.recipient)===t)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(z(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=z(e.to);for(let s of this.subs)s.callId===e.callId&&z(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 qn=`<!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 ne=null;async function wi(){if(ne)return ne;let d;try{d=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=d.default??d,t=e.RTCPeerConnection,n=e.nonstandard?.RTCAudioSink;if(!t||!n)throw new Error("@roamhq/wrtc loaded but missing expected exports (RTCPeerConnection / nonstandard.RTCAudioSink)");return ne={RTCPeerConnection:t,RTCAudioSink:n},ne}var Xn=d=>d.toLowerCase().replace(/[^a-z0-9]/g,""),Pe=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 wi();if(this.pc=new o({iceServers:i}),this.pc.ontrack=c=>{if(this.closed)return;let l=c.track;if(l.kind!=="audio"){r(`[bot:${n}] non-audio track received (kind=${l.kind}) \u2014 ignored in v1`);return}r(`[bot:${n}] audio track received from ${s}`),this.tapAudio(l)},this.pc.onicecandidate=c=>{!c.candidate||this.closed||this.send({kind:"ice",callId:t,from:n,to:s,candidate:{candidate:c.candidate.candidate,sdpMid:c.candidate.sdpMid,sdpMLineIndex:c.candidate.sdpMLineIndex,usernameFragment:c.candidate.usernameFragment}})},this.pc.onconnectionstatechange=()=>{let c=this.pc?.connectionState;r(`[bot:${n}] pc state: ${c}`),(c==="failed"||c==="disconnected"||c==="closed")&&this.close(`pc state ${c}`)},this.unsubscribe=e.subscribeInternal(t,n,c=>this.handleSignal(c)),await this.send({kind:"ring",callId:t,from:n,to:s}),Xn(n)<Xn(s)){let c=await this.pc.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!1});await this.pc.setLocalDescription(c),await this.send({kind:"offer",callId:t,from:n,to:s,sdp:c.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(!ne)throw new Error("WebRtcBot.tapAudio called before loadWrtc \u2014 bug");let{RTCAudioSink:t}=ne,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=ki(e.samples,e.channelCount),s=vi(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=$i(t.samples,t.totalSamples),i=Si(s,t.sourceRate),r=Ii(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 ki(d,e){if(e===1)return d;let t=new Int16Array(d.length/e);for(let n=0,s=0;n<d.length;n+=e,s++){let i=0;for(let r=0;r<e;r++)i+=d[n+r];t[s]=i/e}return t}function vi(d){if(d.length===0)return 0;let e=0;for(let t=0;t<d.length;t++){let n=d[t]/32768;e+=n*n}return Math.sqrt(e/d.length)}function $i(d,e){let t=new Int16Array(e),n=0;for(let s of d)t.set(s,n),n+=s.length;return t}function Si(d,e){if(e===16e3)return d;let t=e/16e3,n=Math.floor(d.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,d.length-1),c=r-o;s[i]=(1-c)*d[o]+c*d[a]}return s}function Ii(d,e){let t=d.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<d.length;i++)s.writeInt16LE(d[i],i*2);return Buffer.concat([n,s])}import{spawn as Vn}from"child_process";import{writeFile as Ti,mkdtemp as xi,rm as Ci}from"fs/promises";import{tmpdir as Ai}from"os";import{join as yt}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=Vn(this.mlxCmd(),["--help"],{stdio:"ignore"});t.on("error",()=>e(!1)),t.on("exit",n=>e(n===0))})}async transcribeMlx(e){let t=await xi(yt(Ai(),"agentx-whisper-")),n=yt(t,"chunk.wav");try{await Ti(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 Pi(this.mlxCmd(),s);if(i.trim())return i;let{readFile:r}=await import("fs/promises");try{return await r(yt(t,"chunk.txt"),"utf-8")}catch{return""}}finally{await Ci(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 Pi(d,e){return new Promise((t,n)=>{let s=Vn(d,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(`${d} exited ${o}: ${r.slice(0,200)}`))})})}var Yn=50,je=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,c)=>{let l=await this.whisper.transcribe(a);if(l){this.recordTranscriptChunk(e.callId);try{await this.opts.onTranscript({invite:e,text:l,durationMs:c})}catch(p){this.opts.log(`[bot-manager] onTranscript hook threw: ${p.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 Pe(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>Yn&&(this.completed.length=Yn)}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 le=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new le(`${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(le.levelOrder[e]<le.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)}},de=le;pe(de,"levelOrder",{debug:0,info:1,warn:2,error:3});import{randomUUID as Qn}from"crypto";var Ee=class{listeners=new Map;subscribe(e,t){let n=Qn();return this.listeners.set(n,{filter:e,fn:t}),()=>{this.listeners.delete(n)}}publish(e){let t={id:typeof e.id=="string"?e.id:Qn(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e};for(let{filter:n,fn:s}of this.listeners.values())if(Mi(n,t))try{s(t)}catch{}}get size(){return this.listeners.size}};function Mi(d,e){return!(d.kinds&&d.kinds.length>0&&!d.kinds.includes(e.kind)||d.workflowId&&(e.kind==="run"&&e.workflowId!==d.workflowId||e.kind==="task"&&e.workflowId!==d.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==d.workflowId)||d.runId&&(e.kind==="run"&&e.runId!==d.runId||e.kind==="task"&&e.runId!==d.runId)||d.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(d.actor)||e.submittedBy===d.actor))||d.channel&&(e.kind!=="channel"||e.channel!==d.channel))}function Zn(d){if(!d)return;let e=["run","task","signal","mesh","channel","status"],n=d.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as es,timingSafeEqual as Ri}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),c=r||this.detectSource(e.headers),l=this.validateSignature(e.headers,o,c,i);if(l){this.log(`Webhook [${c}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let p=this.buildSummary(c,a,e.headers);this.log(`Webhook [${c}] -> ${i}: ${p.slice(0,100)}`);let u=this.extractEventType(c,a,e.headers),f=this.webhookEntries.find(h=>h.enabled&&h.agentId===i&&h.source===c),m=u&&f?.triggers?.[u]||f?.defaultWorkflow||null;if(m&&this.workflowDispatcher)try{let h=await this.workflowDispatcher.dispatchWorkflow({workflowId:m,entityRef:{kind:"webhook",id:`${c}:${i}:${u??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:c,eventType:u,payload:a},trigger:{source:c}});this.log(`Webhook [${c}/${u??"\u2014"}] -> workflow=${m} (claimed=${h.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:c,eventType:u,workflow:m,claimed:h.claimed});return}catch(h){this.log(`Workflow dispatch failed [${c}/${u}/${m}]: ${h.message}`)}let g=this.webhookEntries.find(h=>h.enabled&&h.node&&h.agentId===i&&h.source===c);if(g?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:c,node:g.node,status:"accepted"}),this.mesh.sendTask(g.node,p,i,{context:{channel:`webhook:${c}`,sender:`webhook:${c}`}}).then(h=>this.log(`Mesh-forwarded webhook [${c}] -> ${g.node}/${i}: ${h?.slice(0,100)||"ok"}`),h=>this.log(`Mesh forward failed [${c}] -> ${g.node}/${i}: ${h.message}`));return}try{let h=await this.registry.execute({message:p,agentId:i,context:{channel:`webhook:${c}`,sender:`webhook:${c}`}});this.sendJson(t,h.error?500:200,{ok:!h.error,agent:i,source:c,response:h.content?.slice(0,500),error:h.error,duration:h.duration})}catch(h){this.sendJson(t,500,{error:h.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 l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
|
|
409
|
+
`)[0]||"no message"} (${l.author?.name||""})`)}let c=t.object_attributes;if(c?.title&&(s.push(`Title: ${c.title}`),s.push(`State: ${c.state||""}`),s.push(`Action: ${c.action||""}`),c.source_branch&&s.push(`Branch: ${c.source_branch} -> ${c.target_branch}`),c.url&&s.push(`URL: ${c.url}`)),c?.iid&&!c?.source_branch&&(s.push(`Issue #${c.iid}: ${c.title||""}`),c.description&&s.push(`Description: ${c.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.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 p of t.commits.slice(0,3))s.push(` - ${p.message?.split(`
|
|
410
|
+
`)[0]||""} (${p.author?.name||""})`);let c=t.pull_request;c&&(s.push(`PR #${c.number}: ${c.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${c.head?.ref} -> ${c.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.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(c=>c.enabled&&c.agentId===s&&c.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=c=>{let l=e[c.toLowerCase()];return Array.isArray(l)?l[0]:l};if(n==="github"){let c=o("x-hub-signature-256");if(!c)return"missing X-Hub-Signature-256";let l="sha256="+es("sha256",r).update(t).digest("hex");return De(l,c)}if(n==="gitlab"){let c=o("x-gitlab-token");return c?De(r,c):"missing X-Gitlab-Token"}if(n==="stripe"){let c=o("stripe-signature");if(!c)return"missing Stripe-Signature";let l=Object.fromEntries(c.split(",").map(u=>u.split("=")));if(!l.t||!l.v1)return"malformed Stripe-Signature";let p=es("sha256",r).update(`${l.t}.${t}`).digest("hex");return De(p,l.v1)}let a=o("x-webhook-secret");return a?De(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 De(d,e){if(d.length!==e.length)return"signature mismatch";let t=Buffer.from(d),n=Buffer.from(e);return Ri(t,n)?null:"signature mismatch"}function _i(d){return{insertTaskHistory:d.prepare(`
|
|
412
|
+
INSERT OR REPLACE INTO task_history (
|
|
413
|
+
id, agent_id, channel, chat_id, status, message_preview, error,
|
|
414
|
+
duration_ms, input_tokens, output_tokens,
|
|
415
|
+
cache_read_tokens, cache_create_tokens,
|
|
416
|
+
started_at, finished_at
|
|
417
|
+
) VALUES (
|
|
418
|
+
@id, @agent_id, @channel, @chat_id, @status, @message_preview, @error,
|
|
419
|
+
@duration_ms, @input_tokens, @output_tokens,
|
|
420
|
+
@cache_read_tokens, @cache_create_tokens,
|
|
421
|
+
@started_at, @finished_at
|
|
422
|
+
)
|
|
423
|
+
`),upsertUsageDaily:d.prepare(`
|
|
424
|
+
INSERT INTO usage_daily (
|
|
425
|
+
agent_id, model, day,
|
|
426
|
+
input_tokens, output_tokens, cache_read_tokens, cache_create_tokens,
|
|
427
|
+
tier2_input_tokens, tier2_output_tokens,
|
|
428
|
+
tier2_cache_read_tokens, tier2_cache_create_tokens,
|
|
429
|
+
tasks
|
|
430
|
+
) VALUES (
|
|
431
|
+
@agent_id, @model, @day,
|
|
432
|
+
@input_tokens, @output_tokens, @cache_read_tokens, @cache_create_tokens,
|
|
433
|
+
@tier2_input_tokens, @tier2_output_tokens,
|
|
434
|
+
@tier2_cache_read_tokens, @tier2_cache_create_tokens,
|
|
435
|
+
1
|
|
436
|
+
)
|
|
437
|
+
ON CONFLICT(agent_id, model, day) DO UPDATE SET
|
|
438
|
+
input_tokens = input_tokens + excluded.input_tokens,
|
|
439
|
+
output_tokens = output_tokens + excluded.output_tokens,
|
|
440
|
+
cache_read_tokens = cache_read_tokens + excluded.cache_read_tokens,
|
|
441
|
+
cache_create_tokens = cache_create_tokens + excluded.cache_create_tokens,
|
|
442
|
+
tier2_input_tokens = tier2_input_tokens + excluded.tier2_input_tokens,
|
|
443
|
+
tier2_output_tokens = tier2_output_tokens + excluded.tier2_output_tokens,
|
|
444
|
+
tier2_cache_read_tokens = tier2_cache_read_tokens + excluded.tier2_cache_read_tokens,
|
|
445
|
+
tier2_cache_create_tokens = tier2_cache_create_tokens + excluded.tier2_cache_create_tokens,
|
|
446
|
+
tasks = tasks + 1
|
|
447
|
+
`),insertRotation:d.prepare(`
|
|
448
|
+
INSERT INTO rotations (agent_id, channel, chat_id, reason, last_turn_input_tokens, rotated_at)
|
|
449
|
+
VALUES (@agent_id, @channel, @chat_id, @reason, @last_turn_input_tokens, @rotated_at)
|
|
450
|
+
`),insertRouteTrace:d.prepare(`
|
|
451
|
+
INSERT INTO route_traces (channel, chat_id, msg_id, account_id, kind, deciding_stage, agent_id, reason, at)
|
|
452
|
+
VALUES (@channel, @chat_id, @msg_id, @account_id, @kind, @deciding_stage, @agent_id, @reason, @at)
|
|
453
|
+
`)}}function ts(d,e="claude-opus-4-7"){let t=q(),n=_i(d),s=new Map,i=new Map,r=u=>{let f=`${u.agentId}:${u.channel}:${u.chatId}`;s.set(f,{agentId:u.agentId,channel:u.channel,chatId:u.chatId,startedAt:u.at,messagePreview:u.messagePreview});let m=null;typeof u.chatId=="string"&&u.chatId.startsWith("workflow:")&&(m=u.chatId.slice(9)||null);try{let g=Qt(d,{agentId:u.agentId,channel:u.channel,chatId:u.chatId,messagePreview:u.messagePreview,workflowRunId:m},u.taskId);i.set(f,g)}catch{}},o=u=>{let f=`${u.agentId}:${u.channel}:${u.chatId}`,m=s.get(f);s.delete(f);let g=u.taskId??i.get(f);i.delete(f);let h=`${u.agentId}:${u.channel}:${u.chatId}:${u.at}`,y=u.error?"error":"ok";if(g)try{Zt(d,g,{status:u.error?"error":"ok",inputTokens:u.inputTokens??null,outputTokens:u.outputTokens??null,cacheReadTokens:u.cacheReadTokens??null,cacheCreateTokens:u.cacheCreateTokens??null,error:u.error??null})}catch{}try{n.insertTaskHistory.run({id:h,agent_id:u.agentId,channel:u.channel,chat_id:u.chatId,status:y,message_preview:m?.messagePreview??null,error:u.error??null,duration_ms:u.durationMs,input_tokens:u.inputTokens??null,output_tokens:u.outputTokens??null,cache_read_tokens:u.cacheReadTokens??null,cache_create_tokens:u.cacheCreateTokens??null,started_at:m?.startedAt??u.at,finished_at:u.at})}catch{}let b=u.inputTokens||u.outputTokens||u.cacheReadTokens||u.cacheCreateTokens||u.tier2InputTokens||u.tier2OutputTokens||u.tier2CacheReadTokens||u.tier2CacheCreateTokens;if(!u.error&&b){let w=u.at.slice(0,10);try{n.upsertUsageDaily.run({agent_id:u.agentId,model:e,day:w,input_tokens:u.inputTokens??0,output_tokens:u.outputTokens??0,cache_read_tokens:u.cacheReadTokens??0,cache_create_tokens:u.cacheCreateTokens??0,tier2_input_tokens:u.tier2InputTokens??0,tier2_output_tokens:u.tier2OutputTokens??0,tier2_cache_read_tokens:u.tier2CacheReadTokens??0,tier2_cache_create_tokens:u.tier2CacheCreateTokens??0})}catch{}}},a=u=>{try{nt(d,u.taskId,{name:u.name,action:u.action??null,status:u.status??null,inputSummary:u.inputSummary??null,outputSummary:u.outputSummary??null,error:u.error??null,ms:u.ms??null})}catch{}},c=u=>{try{n.insertRotation.run({agent_id:u.agentId,channel:u.channel,chat_id:u.chatId,reason:u.reason,last_turn_input_tokens:u.lastTurnInputTokens??null,rotated_at:u.at})}catch{}let f=`${u.agentId}:${u.channel}:${u.chatId}`,m=u.taskId??i.get(f);if(m)try{nt(d,m,{name:"session_rotation",action:u.reason,inputSummary:u.lastTurnInputTokens!=null?`last_turn_input_tokens=${u.lastTurnInputTokens}`:null})}catch{}},l=u=>{try{n.insertRouteTrace.run({channel:u.channel,chat_id:u.chatId,msg_id:u.msgId,account_id:u.accountId??null,kind:"match",deciding_stage:u.decidingStage,agent_id:u.agentId,reason:null,at:u.at})}catch{}},p=u=>{try{n.insertRouteTrace.run({channel:u.channel,chat_id:u.chatId,msg_id:u.msgId,account_id:u.accountId??null,kind:"drop",deciding_stage:u.decidingStage,agent_id:null,reason:u.reason,at:u.at})}catch{}};return t.on("task:started",r),t.on("task:completed",o),t.on("task:step",a),t.on("session:rotated",c),t.on("message:matched",l),t.on("message:dropped",p),()=>{t.off("task:started",r),t.off("task:completed",o),t.off("task:step",a),t.off("session:rotated",c),t.off("message:matched",l),t.off("message:dropped",p)}}function ji(d){return{tasks:d.tasks,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cacheReadTokens:d.cache_read_tokens,cacheCreateTokens:d.cache_create_tokens,tier2InputTokens:d.tier2_input_tokens,tier2OutputTokens:d.tier2_output_tokens,tier2CacheReadTokens:d.tier2_cache_read_tokens,tier2CacheCreateTokens:d.tier2_cache_create_tokens,totalDuration:0,errors:0,model:d.model}}function Ei(d,e){if(!d)return null;let t=d.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=ji(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 ns(d,e){let t=e??new Date().toISOString().slice(0,10);return Ei(d,t)??{date:t,agents:{}}}function ss(d=process.env){let e=(d.AGENTX_USAGE_READ??"").toLowerCase().trim();return e==="sqlite"||e==="json"||e==="sqlite-then-json"?e:"sqlite-then-json"}import{spawn as Di}from"child_process";import{existsSync as Oi,readFileSync as Ni}from"fs";import{resolve as Li}from"path";function wt(d){let e=Li(d,"CLAUDE.md");if(!Oi(e))return null;try{let t=Ni(e,"utf8");return sn(t)}catch{return null}}var is=20*60*1e3,Bi=5e3,Ne=class{constructor(e={}){this.opts=e}spawn(e,t){return new bt(e,t,this.opts)}},bt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let s=n.binary??"claude",i=this.buildArgs(t),r=n.log??(()=>{});this.child=Di(s,i,{cwd:t.workspace,env:{...process.env},stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:wt(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",o=>this.onStdout(o)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",o=>r(`[claude pid=${this.snap.pid}] stderr: ${o.trim()}`)),this.child.on("exit",o=>{this.exited=!0,this.exitCode=o,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${o}`};let a=this.waiters.splice(0);for(let c of a)c(null)}),this.child.on("error",o=>{r(`[claude pid=${this.snap.pid}] spawn error: ${o.message}`),this.killReason=`spawn-error: ${o.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(a=>{t=a}),s=this.turnQueue;if(this.turnQueue=s.then(()=>n),await s,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);this.snap={...this.snap,pendingTaskId:e.taskId};let i=Date.now(),r=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(r+`
|
|
454
|
+
`);let o=i+is;try{for(;;){let a=o-Date.now();if(a<=0)throw new Error(`turn deadline exceeded (${is}ms)`);let c=await this.nextEvent(a);if(c===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:c.type,raw:c},c.type==="result"){this.onResultEvent(c);return}}}finally{this.snap={...this.snap,pendingTaskId:null},t()}}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let s of t)s(null);let n=await new Promise(s=>{let i=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}s(!0)},Bi);this.child.once("exit",()=>{clearTimeout(i),s(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
455
|
+
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let s;try{s=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(s):this.pendingEvents.push(s)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,s=setTimeout(()=>{if(n)return;n=!0;let r=this.waiters.indexOf(i);r>=0&&this.waiters.splice(r,1),t(null)},e),i=r=>{n||(n=!0,clearTimeout(s),t(r))};this.waiters.push(i)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};import{z as Le}from"zod";var kt=Le.object({name:Le.string().min(1,"manifest.name is required"),version:Le.string().min(1,"manifest.version is required"),agentxRange:Le.string().optional()});function vt(d){let e=[],t=[],n=q(),s=`[plugin:${d.packageName}]`;return{ctx:{log:(...r)=>d.log(s,...r),on(r,o){let a=l=>{try{o(l)}catch(p){d.log(s,`subscriber for "${String(r)}" threw:`,p?.stack??p)}};n.on(r,a);let c=()=>n.off(r,a);return t.push(c),c},addChannel(r){if(!r||typeof r.name!="string"||!r.name){d.log(s,"addChannel: adapter is missing a string name; skipped");return}if(d.isChannelNameTaken?.(r.name)){d.log(s,`addChannel: name "${r.name}" already in use; skipped`);return}if(e.some(o=>o.name===r.name)){d.log(s,`addChannel: name "${r.name}" already added by this plugin; skipped`);return}e.push(r)},agents:d.agents,config:d.config},channels:e,disposeSubscriptions:()=>{for(let r of t)try{r()}catch{}t.length=0}}}var Gi=15e3;async function $t(d){let e=d.config.plugins??[];if(e.length===0)return[];let t=d.importer??(i=>import(i)),n=d.setupTimeoutMs??Gi,s=[];for(let i of e){let r;try{r=await t(i)}catch(u){d.log(`[plugins] import failed for "${i}": ${u?.message??u}`);continue}let o=Ui(r);if(!Fi(o)){d.log(`[plugins] "${i}" did not export a default AgentXPlugin (no manifest/setup pair found)`);continue}let a=o,c=kt.safeParse(a.manifest);if(!c.success){let u=c.error.issues.map(f=>f.message).join("; ");d.log(`[plugins] "${i}" manifest invalid: ${u}`);continue}if(c.data.agentxRange&&d.daemonVersion&&!Hi(c.data.agentxRange,d.daemonVersion)){d.log(`[plugins] "${i}" requires agentx ${c.data.agentxRange}, daemon is ${d.daemonVersion}; skipped`);continue}let l=vt({packageName:i,agents:d.agents,config:d.config,log:d.log,isChannelNameTaken:d.isChannelNameTaken}),p=!1;try{await Wi(Promise.resolve(a.setup(l.ctx)),n,`setup() exceeded ${n}ms`),p=!0}catch(u){d.log(`[plugins] "${i}" setup() failed: ${u?.message??u}`),l.disposeSubscriptions();continue}p&&(d.log(`[plugins] loaded ${c.data.name} v${c.data.version}`),s.push({manifest:c.data,packageName:i,channels:l.channels,dispose:async()=>{try{typeof a.teardown=="function"&&await a.teardown()}catch(u){d.log(`[plugins] "${i}" teardown() threw: ${u?.message??u}`)}finally{l.disposeSubscriptions()}}}))}return s}function Ui(d){if(d==null||typeof d!="object")return d;let e=d;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 Fi(d){return!!d&&typeof d=="object"&&"manifest"in d&&"setup"in d&&typeof d.setup=="function"}function Hi(d,e){let t=d.replace(/^[\^~=v]+/,"").split("."),n=e.replace(/^v/,"").split(".");return t[0]===n[0]&&(t[1]??"")===(n[1]??"")}function Wi(d,e,t){return new Promise((n,s)=>{let i=setTimeout(()=>s(new Error(t)),e);d.then(r=>{clearTimeout(i),n(r)},r=>{clearTimeout(i),s(r)})})}function Ji(d,e,t=Date.now){return{ts:t(),source:"mesh",sourceEventId:null,project:d.context?.project??null,subject:d.context?.chatId?`chat:${d.context.chatId}`:`mesh:agent:${d.agentId}`,intent:d.context?.channel?`mesh.${d.context.channel}`:"mesh.task",rawJson:e}}function zi(d){return{decidedBy:"mesh-receiver",decide:()=>({agentId:d.agentId,outcome:d.outcome==="deduped"?"halted":d.outcome,reason:d.outcome==="deduped"?`legacy-dedup: ${d.reason??""}`.trim():d.reason??null})}}function rs(d,e,t,n,s=Date.now){let i=Ji(e,t,s),r=zi(n),o=H(d,i,r,s);return W(d,"mesh",o,n,s),o}function os(d,e){return d?d.intents.length===0||!e?!0:d.intents.includes(e):!1}function Ki(d,e,t,n=6*60*60*1e3){if(!e||!t)return 0;let s=Date.now()-n;return d.db.prepare(`
|
|
456
|
+
SELECT DISTINCT d.agent_id
|
|
457
|
+
FROM intent_decisions d
|
|
458
|
+
JOIN intent_events e ON e.id = d.event_id
|
|
459
|
+
WHERE e.project = ? AND e.subject = ?
|
|
460
|
+
AND d.outcome = 'dispatched'
|
|
461
|
+
AND d.agent_id IS NOT NULL
|
|
462
|
+
AND d.decided_at >= ?
|
|
463
|
+
`).all(e,t,s).length}function as(d,e,t,n,s){if(!e)return!1;let i=e.maxDelegationDepth;if(i<=0)return!1;let r=Ki(d,n,s);return(d.db.prepare(`
|
|
464
|
+
SELECT 1
|
|
465
|
+
FROM intent_decisions d
|
|
466
|
+
JOIN intent_events e ON e.id = d.event_id
|
|
467
|
+
WHERE e.project = ? AND e.subject = ?
|
|
468
|
+
AND d.agent_id = ?
|
|
469
|
+
AND d.outcome = 'dispatched'
|
|
470
|
+
LIMIT 1
|
|
471
|
+
`).get(n,s,t)?r:r+1)<=i}var ge=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(([u])=>u!==e);t.push(`Available agents on this node (${o.length} \u2014 not all may be in the current group):`);for(let[u,f]of o){let m=this.getPrimaryHandle(u),g=this.extractCapability(f),h=m?` (${m})`:"";t.push(`\u2022 ${f.name}${h} \u2014 ${g}`)}let a=this.meshPeers.filter(u=>u.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 u=[...a].sort((f,m)=>f.peer.localeCompare(m.peer));for(let f of u){let m=[...f.skills].sort((g,h)=>g.id.localeCompare(h.id));for(let g of m){let h=(g.description||"").slice(0,80),y=g.name&&g.name!==g.id?` (${g.name})`:"";t.push(`\u2022 ${g.id}${y} [${f.peer}] \u2014 ${h}`)}}}t.push(""),t.push(this.renderChannels()),t.push(""),t.push("[Rules]");let c=[s,e].filter(Boolean).join(" / ");t.push(`- Only respond when YOU (${c}) 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[,l]=this.config.node.bind.split(":"),p=l||"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:${p}/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:${p}/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(`
|
|
472
|
+
`)}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 qi,readFileSync as Xi}from"fs";import{resolve as Vi}from"path";var Yi=".agentx/contacts.json",Be=class{contacts=[];filePath;log;constructor(e=process.cwd(),t=()=>{}){this.filePath=Vi(e,Yi),this.log=t,this.reload()}reload(){if(!qi(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 c of o){let l=c.toLowerCase();if(n.includes(l)||l.includes(n)){let p=Math.min(l.length,n.length);p>a&&(a=p)}}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 Qi,readFileSync as Zi,unlinkSync as er,writeFileSync as tr}from"fs";import{resolve as nr}from"path";var cs="_agentxManaged";function ds(d,e){let t=nr(d,".mcp.json"),n=Qi(t),s=n?sr(t):null,i=s!==null&&s[cs]===!0;if(n&&!i)return"skipped-operator-owned";let r=Object.keys(e).length>0;if(!r&&!n)return"noop";if(!r&&i)return er(t),"removed";let o={[cs]:!0,mcpServers:e};return tr(t,JSON.stringify(o,null,2)+`
|
|
473
|
+
`),n?"updated":"installed"}function sr(d){try{return JSON.parse(Zi(d,"utf-8"))}catch{return null}}var ls="remember.md",gs=`---
|
|
474
|
+
name: remember
|
|
475
|
+
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.
|
|
476
|
+
---
|
|
477
|
+
|
|
478
|
+
# Remember
|
|
479
|
+
|
|
480
|
+
You have a persistent memory layer that is auto-loaded into your system prompt on every task. It is SEPARATE from the shared wiki:
|
|
481
|
+
|
|
482
|
+
- **Wiki** is cross-agent, authoritative, documented. Facts that multiple agents agree on.
|
|
483
|
+
- **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.
|
|
484
|
+
|
|
485
|
+
Four memory kinds:
|
|
486
|
+
|
|
487
|
+
| Kind | Save something of type\u2026 |
|
|
488
|
+
|---|---|
|
|
489
|
+
| \`user\` | role, seniority, tone preference, what they are fluent in vs new to |
|
|
490
|
+
| \`feedback\` | corrections ("don't do X, we got burned last Q") + confirmations ("yes the bundled PR was right") |
|
|
491
|
+
| \`project\` | current initiative, known constraints, deadline context not in the code |
|
|
492
|
+
| \`reference\` | external systems and when to use them (Linear, Grafana, a specific dashboard URL) |
|
|
493
|
+
|
|
494
|
+
## When to save
|
|
495
|
+
|
|
496
|
+
**Good triggers** \u2014 save a memory whenever:
|
|
497
|
+
|
|
498
|
+
- The user corrects an approach ("no not that", "stop doing X"). Save as \`feedback\`.
|
|
499
|
+
- The user confirms a non-obvious approach worked ("yes exactly, keep doing that"). Save as \`feedback\`.
|
|
500
|
+
- You learn a durable fact about the user or their role you didn't know before. Save as \`user\`.
|
|
501
|
+
- You learn a project-level fact that is not in the code and not in the wiki. Save as \`project\`.
|
|
502
|
+
- The user points at an external system ("check Linear INGEST for ticket context"). Save as \`reference\`.
|
|
503
|
+
|
|
504
|
+
**Skip** \u2014 do NOT save:
|
|
505
|
+
|
|
506
|
+
- Conversation-specific state, current task TODOs, temporary context. Use the current session for those.
|
|
507
|
+
- Things already in the wiki, or that feel cross-agent authoritative. Propose a wiki article instead.
|
|
508
|
+
- Negative judgements about the user. Memories get re-read every session; stay professional.
|
|
509
|
+
|
|
510
|
+
## How to save
|
|
511
|
+
|
|
512
|
+
The daemon exposes \`POST /api/memory\`. Call it from a Bash tool invocation.
|
|
513
|
+
|
|
514
|
+
\`\`\`bash
|
|
515
|
+
curl -sS -X POST http://localhost:18800/api/memory \\
|
|
516
|
+
-H 'Content-Type: application/json' \\
|
|
517
|
+
-d '{
|
|
518
|
+
"agentId": "<your-agent-id>",
|
|
519
|
+
"type": "feedback",
|
|
520
|
+
"name": "no-mock-db",
|
|
521
|
+
"description": "Tests must hit a real database \u2014 mocks masked a prod migration bug in Q1.",
|
|
522
|
+
"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."
|
|
523
|
+
}'
|
|
524
|
+
\`\`\`
|
|
525
|
+
|
|
526
|
+
Your agent id is the name of the workspace directory you're in (e.g. \`atlas\`, \`mtgl-v2\`). When in doubt, run \`basename "$(pwd)"\`.
|
|
527
|
+
|
|
528
|
+
### Update an existing memory
|
|
529
|
+
|
|
530
|
+
Same endpoint, same \`name\`. The daemon keeps \`createdAt\` stable and bumps \`updatedAt\`. If you want to *append* rather than replace, pass \`"append": true\`:
|
|
531
|
+
|
|
532
|
+
\`\`\`bash
|
|
533
|
+
curl -sS -X POST http://localhost:18800/api/memory \\
|
|
534
|
+
-H 'Content-Type: application/json' \\
|
|
535
|
+
-d '{ "agentId":"atlas","type":"feedback","name":"no-mock-db",
|
|
536
|
+
"description":"\u2026", "body":"Also: 2026-04-15 hit the same class of bug on the grant-application webhook. Same rule.","append":true }'
|
|
537
|
+
\`\`\`
|
|
538
|
+
|
|
539
|
+
### Read what you already remember
|
|
540
|
+
|
|
541
|
+
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.
|
|
542
|
+
|
|
543
|
+
For the full JSON:
|
|
544
|
+
|
|
545
|
+
\`\`\`bash
|
|
546
|
+
curl -sS 'http://localhost:18800/api/memory?agent=atlas'
|
|
547
|
+
\`\`\`
|
|
548
|
+
|
|
549
|
+
### Remove
|
|
550
|
+
|
|
551
|
+
\`\`\`bash
|
|
552
|
+
curl -sS -X DELETE 'http://localhost:18800/api/memory/no-mock-db?agent=atlas'
|
|
553
|
+
\`\`\`
|
|
554
|
+
|
|
555
|
+
## Structuring the body
|
|
556
|
+
|
|
557
|
+
For **feedback** memories specifically, structure the body so future-you can judge edge cases instead of blindly obeying the rule:
|
|
558
|
+
|
|
559
|
+
\`\`\`
|
|
560
|
+
<the rule itself, one line>
|
|
561
|
+
|
|
562
|
+
Why: <the reason \u2014 often a past incident, a strong preference>
|
|
563
|
+
How to apply: <when/where this guidance kicks in>
|
|
564
|
+
\`\`\`
|
|
565
|
+
|
|
566
|
+
That's the same shape Claude Code's own memory system uses. Keeps the memory useful even when context shifts.
|
|
567
|
+
|
|
568
|
+
## Deduplication
|
|
569
|
+
|
|
570
|
+
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.
|
|
571
|
+
`;var Ge=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}
|
|
572
|
+
|
|
573
|
+
${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 he=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 K.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 Ue=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 hs={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};function St(d,e){let n=new Intl.DateTimeFormat("en-US",{timeZone:e,weekday:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(d),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:hs[s]??0}}function se(d){let[e,t]=d.split(":").map(Number);return e*60+t}function It(d,e){return d.days.some(t=>hs[t]===e)}function ir(d,e,t){let{hour:n,minute:s,dow:i}=St(e,t);if(!It(d,i))return!1;let r=n*60+s,o=se(d.start),a=se(d.end);if(r<o||r>=a)return!1;if(d.lunch){let c=se(d.lunch.start),l=se(d.lunch.end);if(r>=c&&r<l)return!1}return!0}var Fe=class{constructor(e,t){this.org=e;this.config=t}isOnClock(e,t=new Date){let n=this.org.get(e);return n?ir(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}=St(t,this.config.timezone);if(!It(n.schedule,r))return!1;let o=se(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}=St(t,this.config.timezone);if(!It(n.schedule,r))return!1;let o=se(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 He=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}
|
|
574
|
+
|
|
575
|
+
${n}`;if(!i.length){await this.postToMain(r,e);return}await this.postToMain(`${r}
|
|
576
|
+
|
|
577
|
+
cc: ${i.map(o=>`@${o}`).join(" ")}`,e)}};import{writeFileSync as rr,existsSync as us,mkdirSync as or,readFileSync as ar}from"fs";import{resolve as Tt}from"path";function xt(){return new Date().toISOString().slice(0,10)}var We=class{constructor(e,t,n){this.org=e;this.schedule=t;this.log=n;this.dir=Tt(process.cwd(),".agentx/kpi"),us(this.dir)||or(this.dir,{recursive:!0}),this.stats=this.loadOrInit()}stats;dir;onClockTick=new Map;loadOrInit(){let e=Tt(this.dir,`${xt()}.json`);if(us(e))try{return JSON.parse(ar(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:xt(),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!==xt()&&(this.flush(),this.stats=this.loadOrInit());try{rr(Tt(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(`
|
|
578
|
+
`)}};function _(d,e,t){d.statusCode=e,d.setHeader("Content-Type","application/json"),d.end(JSON.stringify(t))}async function Je(d){return new Promise((e,t)=>{let n=[];d.on("data",s=>n.push(s)),d.on("end",()=>{let s=Buffer.concat(n).toString("utf-8");if(!s)return e({});try{e(JSON.parse(s))}catch(i){t(i)}}),d.on("error",t)})}async function ps(d,e,t,n){if(d==="GET /business/status"){let s=new Date,i=n.schedule.clockedInAgents(s);return _(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(d.startsWith("GET /business/work")){let i=new URL(e.url||"/","http://x").searchParams.get("agent");if(!i)return _(t,400,{error:"?agent= required"}),!0;try{let r=await n.workSource.listOpen(i);_(t,200,{items:r})}catch(r){_(t,500,{error:r.message})}return!0}if(d==="POST /business/claim"){let s=await Je(e),{agent:i,itemId:r}=s;if(!i||!r)return _(t,400,{error:"agent and itemId required"}),!0;try{await n.workSource.claim(i,r),_(t,200,{ok:!0})}catch(o){_(t,500,{error:o.message})}return!0}if(d==="POST /business/report"){let s=await Je(e);if(!s.itemId||!s.status)return _(t,400,{error:"itemId and status required"}),!0;if(!["in-progress","done","blocked"].includes(s.status))return _(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}),_(t,200,{ok:!0})}catch(i){_(t,500,{error:i.message})}return!0}if(d==="POST /business/escalate"){let s=await Je(e);return!s.agent||!s.subject?(_(t,400,{error:"agent and subject required"}),!0):(await n.reporter.escalate(s.agent,s.subject,s.detail||""),n.kpi.recordBlocker(s.agent),_(t,200,{ok:!0}),!0)}if(d==="POST /business/post"){let s=await Je(e);return s.text?(await n.reporter.postToMain(s.text,s.agent),_(t,200,{ok:!0}),!0):(_(t,400,{error:"text required"}),!0)}return!1}function Ct(d){return`## Business Layer Tools
|
|
579
|
+
|
|
580
|
+
During business hours you'll receive lifecycle prompts ([STANDUP], [WORK], [WRAP]).
|
|
581
|
+
Use these HTTP endpoints on the local daemon to act on them.
|
|
582
|
+
|
|
583
|
+
- **List your work:**
|
|
584
|
+
\`curl -s ${d}/business/work?agent=<your-id>\`
|
|
585
|
+
- **Claim an item** (optional \u2014 some sources no-op):
|
|
586
|
+
\`curl -s -X POST ${d}/business/claim -d '{"agent":"<your-id>","itemId":"<id>"}'\`
|
|
587
|
+
- **Report progress or completion:**
|
|
588
|
+
\`curl -s -X POST ${d}/business/report \\
|
|
589
|
+
-d '{"itemId":"<id>","status":"done","timeSeconds":1800,"note":"shipped"}'\`
|
|
590
|
+
status: \`in-progress\` | \`done\` | \`blocked\`
|
|
591
|
+
- **Escalate a blocker** up the org chart:
|
|
592
|
+
\`curl -s -X POST ${d}/business/escalate \\
|
|
593
|
+
-d '{"agent":"<your-id>","subject":"short","detail":"why it's stuck"}'\`
|
|
594
|
+
- **Post to the main channel** (daily plans, reports):
|
|
595
|
+
\`curl -s -X POST ${d}/business/post \\
|
|
596
|
+
-d '{"agent":"<your-id>","text":"your update"}'\`
|
|
597
|
+
|
|
598
|
+
Your org chart, role, and schedule are fixed in agentx.json under \`business.orgChart\`.
|
|
599
|
+
`}import{existsSync as At,mkdirSync as cr,readFileSync as ms,writeFileSync as dr,readdirSync as lr}from"fs";import{resolve as Pt,dirname as gr}from"path";var ze=class{constructor(e,t=process.cwd()){this.plansDir=e;this.cwd=t}absDir(){return Pt(this.cwd,this.plansDir)}slug(e,t){if(e==="day")return t.toISOString().slice(0,10);if(e==="month")return t.toISOString().slice(0,7);let n=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),s=n.getUTCDay()||7;n.setUTCDate(n.getUTCDate()+4-s);let i=new Date(Date.UTC(n.getUTCFullYear(),0,1)),r=Math.ceil(((+n-+i)/864e5+1)/7);return`${n.getUTCFullYear()}-W${String(r).padStart(2,"0")}`}absPath(e,t){return Pt(this.absDir(),`${this.slug(e,t)}.md`)}resolve(e=new Date){for(let t of["day","week","month"]){let n=this.absPath(t,e);if(At(n)){let s=ms(n,"utf-8");if(s.trim())return{tier:t,date:this.slug(t,e),path:n,content:s}}}return null}read(e,t=new Date){let n=this.absPath(e,t);if(!At(n))return null;let s=ms(n,"utf-8");return{tier:e,date:this.slug(e,t),path:n,content:s}}write(e,t,n=new Date){let s=this.absPath(e,n);return cr(gr(s),{recursive:!0}),dr(s,t.endsWith(`
|
|
600
|
+
`)?t:t+`
|
|
601
|
+
`),{tier:e,date:this.slug(e,n),path:s,content:t}}list(e=30){let t=this.absDir();if(!At(t))return[];let n=[];for(let s of lr(t)){if(!s.endsWith(".md"))continue;let i=s.slice(0,-3),r,o;if(/^\d{4}-\d{2}-\d{2}$/.test(i))r="day",o=i;else if(/^\d{4}-W\d{2}$/.test(i))r="week",o=i.replace("-W","-");else if(/^\d{4}-\d{2}$/.test(i))r="month",o=i;else continue;n.push({tier:r,date:i,path:Pt(t,s),sortKey:o})}return n.sort((s,i)=>i.sortKey.localeCompare(s.sortKey)),n.slice(0,e).map(({tier:s,date:i,path:r})=>({tier:s,date:i,path:r}))}};function fs(d){let e=[];for(let t of d.split(`
|
|
602
|
+
`)){let s=t.trim().match(/^(?:[-*]|\d+\.)\s+(.+)$/);s&&e.push(s[1].trim())}return e}var hr=6e4,Ke=class{constructor(e,t,n,s,i,r,o,a,c){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=c;for(let l of t.all())this.day.set(l.agentId,{});this.planStore=new ze(this.config.standup.plansDir)}timer;day=new Map;currentDate=new Date().toISOString().slice(0,10);runningTask=new Set;standupsFiredToday=0;noPlanNoticePostedFor;planStore;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}`))},hr)}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.standupsFiredToday=0}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?`
|
|
603
|
+
Responsibilities:
|
|
604
|
+
${t.role.responsibilities.map(r=>`- ${r}`).join(`
|
|
605
|
+
`)}`:"",i=t.role.sopPath?`
|
|
606
|
+
SOP: @${t.role.sopPath}`:"";return`You are ${e}, role: ${t.role.title} ${n}.${s}${i}
|
|
607
|
+
|
|
608
|
+
${Ct(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){let t=this.config.standup;if(!t.enabled){this.log(`[business] STANDUP skipped (standup.enabled=false) \u2192 ${e}`);return}if(this.standupsFiredToday>=t.maxAgentsPerDay){this.log(`[business] STANDUP ceiling hit (${t.maxAgentsPerDay}/day) \u2014 skipping ${e}`);return}let n=this.planStore.resolve();if(!n){await this.postNoPlanNoticeOnce(),this.log(`[business] STANDUP skipped (no plan for ${this.currentDate}) \u2192 ${e}`);return}if(t.dryRun){await this.postPlanPreviewOnce(n),this.log(`[business] STANDUP dry-run (plan ${n.tier}/${n.date}) \u2014 no dispatch`);return}this.log(`[business] STANDUP \u2192 ${e} (plan ${n.tier}/${n.date})`),this.standupsFiredToday++;let s=this.roleContext(e),i=fs(n.content),r=i.length?`Today's priorities (from the ${n.tier} plan, ${n.date}):
|
|
609
|
+
${i.map((c,l)=>` ${l+1}. ${c}`).join(`
|
|
610
|
+
`)}`:`Today's plan (${n.tier}, ${n.date}):
|
|
611
|
+
${n.content.trim()}`,o=`${s}
|
|
612
|
+
|
|
613
|
+
[STANDUP] It's the start of your work day.
|
|
614
|
+
|
|
615
|
+
${r}
|
|
616
|
+
|
|
617
|
+
1. Call GET /business/work?agent=${e} to see your open work items, and reconcile them with the priorities above. The plan wins on tie-breaks.
|
|
618
|
+
2. Pick your top 3 for today, in priority order, citing which plan item each one serves.
|
|
619
|
+
3. Post your plan to the main channel via POST /business/post \u2014 keep it to 4-6 short lines.
|
|
620
|
+
4. Flag any blockers via POST /business/escalate.`;if(await this.runLifecycle(e,o)){let c=this.day.get(e)||{};c.hadWorkToday=!0,this.day.set(e,c)}}async postNoPlanNoticeOnce(){if(this.noPlanNoticePostedFor===this.currentDate)return;this.noPlanNoticePostedFor=this.currentDate;let e=`No plan for ${this.currentDate} \u2014 skipping standup. Set one with \`agentx plan set today \u2026\` or via the admin \u2192 Plans tab.`;try{await this.reporter.postToMain(e)}catch(t){this.log(`[business] no-plan notice post failed: ${t?.message||t}`)}}async postPlanPreviewOnce(e){if(this.noPlanNoticePostedFor===this.currentDate)return;this.noPlanNoticePostedFor=this.currentDate;let t=`[dry-run] Plan for ${this.currentDate} (resolved from ${e.tier}/${e.date}):`;try{await this.reporter.postToMain(`${t}
|
|
621
|
+
${e.content.trim()}`)}catch(n){this.log(`[business] plan-preview post failed: ${n?.message||n}`)}}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)}
|
|
622
|
+
|
|
623
|
+
[WORK] Continue your highest-priority open task.
|
|
624
|
+
- Call GET /business/work?agent=${e} to see what's assigned to you.
|
|
625
|
+
- If you complete one, POST /business/report with status:done and the time you spent.
|
|
626
|
+
- If blocked, POST /business/escalate with a concise blocker description.
|
|
627
|
+
- 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)}
|
|
628
|
+
|
|
629
|
+
[WRAP] End of work day. Post a concise daily report to the main channel via POST /business/post:
|
|
630
|
+
- Tasks closed today
|
|
631
|
+
- Time logged (total)
|
|
632
|
+
- Carry-overs to tomorrow
|
|
633
|
+
- Any outstanding blockers
|
|
634
|
+
Keep it under 8 lines.`;await this.runLifecycle(e,s)}};var qe=class{org;schedule;workSource;reporter;kpi;dayCycle;constructor(e,t,n,s,i){this.org=new Ue(e),this.schedule=new Fe(this.org,e),this.workSource=gn(e,t,i),this.reporter=new He(s,this.org,e,i),this.kpi=new We(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 Ke(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 ps(e,t,n,s)}summary(){let e=this.schedule.clockedInAgents().length;return`Business layer: ${this.org.all().length} employees, ${e} on-clock now`}};var ws=class{config;registry;router;cron;mesh;hooks;landscape;heartbeat;business;httpServer;webhooks;github;webrtc;botManager;workflowDispatcher;workflowStore;workflowRuns;db=null;loadedPlugins=[];agentMemory=new Bt;contacts;processRegistry=null;events=new Ee;log;sseClients=new Set;configPath;configWatcher;reloadTimer;constructor(e){let n=new de("agentx").asConsoleLog();this.log=(...o)=>{n(...o);let a=o.map(c=>typeof c=="string"?c:JSON.stringify(c)).join(" ");this.broadcastSSE("log",a)},this.log("Loading configuration..."),this.configPath=e,this.config=Ze(e),this.contacts=new Be(process.cwd(),this.log);let s=Wt(this.config);for(let o of s)this.log(` \u26A0 ${o}`);let[,i]=this.config.node.bind.split(":");rn(this.config.agents,i||"19900",this.log),this.hooks=new Dt,Ye(process.cwd(),this.hooks),this.landscape=new ge(this.config),this.registry=new Ut(this.config,this.log),Gt(this.registry),this.registry.setLandscape(this.landscape),this.heartbeat=new Ge(this.registry,this.log);for(let[o,a]of Object.entries(this.config.agents))a.heartbeat?.enabled&&this.heartbeat.register(o,a.heartbeat);if(this.router=new ae(this.registry,this.config,this.hooks,this.log),Object.keys(this.config.services).length>0){let o=new he(this.config.services,this.log);this.router.setServiceMatcher(o)}this.cron=new tt(this.config,this.registry,this.hooks,this.log),this.cron.setNotifyCallback(async(o,a,c,l)=>{let p=`Cron "${o}" failed (${l}x)
|
|
635
|
+
Agent: ${a}
|
|
636
|
+
Error: ${c.slice(0,300)}`;this.log(`[CRON ALERT] ${p}`),this.broadcastSSE("cron-failure",JSON.stringify({jobId:o,agent:a,error:c,consecutiveErrors:l}));let u=this.config.crons[o];if(u?.notify)try{await this.router.sendOutbound({channel:u.notify.channel,chatId:u.notify.chatId,text:`\u{1F534} **Cron "${o}" failed** (${l}x)
|
|
637
|
+
${c.slice(0,300)}`,agentId:a,accountId:u.notify.accountId})}catch(f){this.log(`[CRON ALERT] notify send failed: ${f.message}`)}}),this.config.mesh.enabled&&(this.mesh=new fe(this.config,this.log),this.router.setMesh(this.mesh),Kt(this.mesh),this.mesh.onPeerChange(o=>{this.events.publish({kind:"mesh",peer:o.peer,healthy:o.healthy,skills:o.skills,delta:o.delta})}),this.registry.setMeshFallback({findPeerWithSkill:o=>this.mesh.findPeerWithSkill(o),sendTask:(o,a,c)=>this.mesh.sendTask(o,a,c),directory:()=>this.mesh.directory()})),this.webhooks=new Oe(this.registry,{},this.log,this.mesh,this.config.webhooks);try{let o=Vt();if(this.db=o,o){let a=tn(o);a>0&&this.log(` Traces: canceled ${a} orphaned in-flight row(s) from prior run`),ts(o),this.log(` SQLite: ${o.name}`)}else this.log(" SQLite: not opened (native binding unavailable or path unwritable)")}catch(o){this.log(` SQLite: skipped (${o.message})`)}let r=Object.values(this.config.agents).filter(o=>o.persistentProcess);if(r.length>0)try{let o=new Ne({log:c=>this.log(` ${c}`)}),a=new Ot({factory:o,log:c=>this.log(` ${c}`),currentWorkspaceHash:(c,l)=>wt(l)});a.start(),Qe(a),this.processRegistry=a,this.log(` ProcessRegistry: enabled for ${r.length} agent(s)`)}catch(o){this.log(` ProcessRegistry: skipped (${o.message})`)}if(this.config.business?.enabled)try{if(this.business=new qe(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 o=this.business.org,a=this.config.agents;Xt({pmFor:c=>o.pmFor(c),canHandle:(c,l,p)=>o.canHandle(c,l,p)?os(a[c],p):!1,withinDelegationBudget:(c,l,p)=>as(j(),a[c],c,l,p)}),this.log(" Ledger governance: PM gate + capability + delegation-depth ENABLED")}}catch(o){this.log(`[business] initialization failed: ${o.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=>D(o)!=="off")){let o=j().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 $t({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=Yt(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{}try{qt();let r=et().length;this.log(` Built-in actions: ${r} registered`)}catch(r){this.log(` Built-in actions: registration failed (${r.message})`)}this.log(""),this.log(" Ready."),this.log("");let n=B(process.cwd(),".agentx/daemon.pid");bs(fr(n),{recursive:!0}),ys(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(`
|
|
638
|
+
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.processRegistry&&(this.log(" Stopping persistent claude processes..."),await this.processRegistry.stop(),Qe(null))}catch(t){this.log(` ProcessRegistry stop 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");ue(t)&&pr(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(ue(e))try{this.configWatcher=mr(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=Ze(this.configPath)}catch(m){return this.log(`[reload] config invalid, keeping previous: ${m.message}`),{applied:[],restartRequired:[],error:m.message}}let t=[],n=[];if(JSON.stringify(this.config.crons)!==JSON.stringify(e.crons))try{await this.cron.stop(),this.cron=new tt(e,this.registry,this.hooks,this.log),this.cron.setNotifyCallback(async(m,g,h,y)=>{this.log(`[CRON ALERT] Cron "${m}" failed (${y}x) \u2014 ${h.slice(0,200)}`),this.broadcastSSE("cron-failure",JSON.stringify({jobId:m,agent:g,error:h,consecutiveErrors:y}));let b=e.crons[m];if(b?.notify)try{await this.router.sendOutbound({channel:b.notify.channel,chatId:b.notify.chatId,text:`Cron "${m}" failed (${y}x)
|
|
639
|
+
${h.slice(0,300)}`,agentId:g,accountId:b.notify.accountId})}catch(w){this.log(`[CRON ALERT] notify send failed: ${w.message}`)}}),await this.cron.start(),t.push("crons")}catch(m){this.log(`[reload] cron reload failed: ${m.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 m=this.router.getChannel("telegram");if(m)try{let g=await m.reloadAccounts(i.accounts,i.policy);this.router.updateConfig(e);let h=[];g.added.length&&h.push(`+${g.added.join(",")}`),g.removed.length&&h.push(`-${g.removed.join(",")}`),g.tokenChanged.length&&h.push(`~${g.tokenChanged.join(",")}`),t.push(h.length?`telegram(${h.join(" ")})`:"telegram"),o=!0}catch(g){this.log(`[reload] telegram hot-reload failed: ${g.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(m){this.log(`[reload] providers hot-reload failed: ${m.message}`)}let a=this.config.mesh,c=e.mesh,l=JSON.stringify(a)!==JSON.stringify(c),p=!l;if(l&&c.enabled&&a.enabled&&this.mesh&&!(JSON.stringify(a.healthCheck)!==JSON.stringify(c.healthCheck)))try{let g=await this.mesh.reloadPeers(e),h=[];g.added.length&&h.push(`+${g.added.join(",")}`),g.removed.length&&h.push(`-${g.removed.join(",")}`),g.updated.length&&h.push(`~${g.updated.join(",")}`),t.push(h.length?`mesh(${h.join(" ")})`:"mesh"),p=!0}catch(g){this.log(`[reload] mesh hot-reload failed: ${g.message}`)}if(JSON.stringify(this.config.services)!==JSON.stringify(e.services))try{let m=this.router.getServiceMatcher();if(m){let{count:g}=m.reload(e.services);t.push(`services(${g})`)}else if(Object.keys(e.services).length>0){let g=new he(e.services,this.log);this.router.setServiceMatcher(g),t.push(`services(${Object.keys(e.services).length})`)}}catch(m){this.log(`[reload] services hot-reload failed: ${m.message}`)}try{let m=this.hooks.size?.()??0;this.hooks.clear(),Ye(process.cwd(),this.hooks);let g=this.hooks.size?.()??0;m!==g&&t.push(`hooks(${g})`)}catch(m){this.log(`[reload] hooks reload failed: ${m.message}`)}if(JSON.stringify(this.config.business)!==JSON.stringify(e.business)||JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){try{this.landscape=new ge(e),this.registry.setLandscape(this.landscape),t.push("landscape")}catch(m){this.log(`[reload] landscape rebuild failed: ${m.message}`)}if(this.mesh&&this.mesh.peerCount()>0)try{let m=await this.mesh.refreshAll(),g=m.filter(h=>h.healthy).length;t.push(`mesh.refresh(${g}/${m.length})`)}catch(m){this.log(`[reload] mesh refresh failed: ${m.message}`)}}if(JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){let m=Object.keys(this.config.agents).sort().join(","),g=Object.keys(e.agents).sort().join(",");m===g&&(this.registry.setConfig(e),t.push("agents.meta"));let h=wr(this.config.agents,e.agents);h.length>0&&n.push(`agents(${h.join(",")})`)}p||n.push("mesh"),JSON.stringify(this.config.node)!==JSON.stringify(e.node)&&n.push("node");let u={...this.config.channels,telegram:void 0},f={...e.channels,telegram:void 0};JSON.stringify(u)!==JSON.stringify(f)?n.push("channels"):r&&!o&&n.push("channels.telegram");{let m=this.contacts.size(),g=this.contacts.reload();g.error?this.log(`[reload] contacts.json invalid: ${g.error}`):g.count!==m&&t.push(`contacts(${g.count})`)}if(JSON.stringify(this.config.webhooks)!==JSON.stringify(e.webhooks))try{this.webhooks.setWebhookEntries(e.webhooks),t.push(`webhooks(${e.webhooks.length})`)}catch(m){this.log(`[reload] webhooks hot-reload failed: ${m.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 V(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 $e({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 Se({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 Ie({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 xe({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(l=>l.peer===t&&l.healthy);if(!a){this.log(`[gitlab] react forward: peer "${t}" not found or unhealthy`);return}let c=`${a.peerUrl}/gitlab/react`;try{let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,noteId:r,agentId:o})}),p=await l.text().catch(()=>"");this.log(`[gitlab] react forward -> ${c} : ${l.status} ${p.slice(0,200)}`)}catch(l){this.log(`[gitlab] react forward FAILED -> ${c} : ${l.message}`)}}),e.setSendNoteForwarder(async(t,n,s,i,r,o)=>{let a=this.mesh.directory().find(l=>l.peer===t&&l.healthy);if(!a)return this.log(`[gitlab] send-note forward: peer "${t}" not found or unhealthy`),"";let c=`${a.peerUrl}/gitlab/send-note`;try{let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:r,text:o})}),p=await l.json().catch(()=>({}));return this.log(`[gitlab] send-note forward -> ${c} : ${l.status} noteId=${p.noteId||"?"}`),p.noteId||""}catch(l){return this.log(`[gitlab] send-note forward FAILED -> ${c} : ${l.message}`),""}}),e.setLogTimeForwarder(async(t,n,s,i,r,o)=>{let a=this.mesh.directory().find(l=>l.peer===t&&l.healthy);if(!a){this.log(`[gitlab] log-time forward: peer "${t}" not found or unhealthy`);return}let c=`${a.peerUrl}/gitlab/log-time`;try{let l=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:r,durationMs:o})}),p=await l.text().catch(()=>"");this.log(`[gitlab] log-time forward -> ${c} : ${l.status} ${p.slice(0,160)}`)}catch(l){this.log(`[gitlab] log-time forward FAILED -> ${c} : ${l.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 Ce({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(c=>c.peer===t&&c.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 c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({repo:n,issueNumber:s,agentId:i,text:r})}),l=await c.json().catch(()=>({}));return this.log(`[github] send-comment forward -> ${a} : ${c.status} commentId=${l.commentId||"?"}`),l.commentId||""}catch(c){return this.log(`[github] send-comment forward FAILED -> ${a} : ${c.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 je({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}
|
|
640
|
+
${i}`,parseMode:"plain",...o.accountId?{accountId:o.accountId}:{}})}catch(c){this.log(`[bot-manager] transcript send via ${o.channel}:${o.chatId} failed: ${c.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 on({baseDir:B(process.cwd(),e.dir)}),n=new an({baseDir:B(process.cwd(),e.dir),nodeId:this.config.node.id}),s={};for(let k of this.router.getChannelNames()){let I=this.router.getChannel(k);I&&(s[k]=I)}let i={execute:async k=>{let I=Date.now();try{let C=k.workflowRunId?`workflow:${k.workflowRunId}`:"workflow:adhoc",x=await this.registry.execute({agentId:k.agentId,message:k.message,workflowRunId:k.workflowRunId,timeoutMinutes:k.timeoutMinutes,context:{channel:"workflow",chatId:C,sender:"workflow"}});return{content:x.content??"",error:x.error,taskId:`wf-${k.workflowRunId??"na"}-${I.toString(36)}`,durationMs:Date.now()-I}}catch(C){return{content:"",error:C.message}}}},r=this.mesh?{forwardTransition:async(k,I)=>{let C=this.mesh.directory().find(A=>A.peer===k&&A.healthy);if(!C){this.log(`[workflows] forward to "${k}" skipped \u2014 peer not found or unhealthy`);return}let x=`${C.peerUrl}/workflow/event`;try{let A=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:I})});A.ok||this.log(`[workflows] forward ${x} -> ${A.status}`)}catch(A){this.log(`[workflows] forward ${x} failed: ${A.message}`)}},broadcastTrigger:async k=>{let I=this.mesh.directory().filter(x=>x.healthy);if(I.length===0)return;let C=this.config.node.id;this.log(`[workflows/mesh] broadcasting trigger source="${k.trigger.source}" chat="${k.trigger.chat??"*"}" -> ${I.length} peer(s): ${I.map(x=>x.peer).join(", ")}`),await Promise.allSettled(I.map(async x=>{let A=`${x.peerUrl}/workflow/event`;try{let R=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:"trigger",fromPeer:C,payload:k}),signal:AbortSignal.timeout(5e3)});R.ok||this.log(`[workflows/mesh] broadcastTrigger ${x.peer} -> ${R.status}`)}catch(R){this.log(`[workflows/mesh] broadcastTrigger ${x.peer} failed: ${R.message}`)}}))},forwardChannelSend:async k=>{let I=this.mesh.directory().filter(O=>O.healthy&&O.channels?.includes(k.channel));if(I.length===0)throw new Error(`no healthy mesh peer hosts channel "${k.channel}"`);let C=I[0],x=`${C.peerUrl}/channel/send`,A=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k),signal:AbortSignal.timeout(15e3)});if(!A.ok){let O=await A.text().catch(()=>"");throw new Error(`peer ${C.peer} /channel/send -> ${A.status} ${O.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"),c=new o,l=new a(e.dir?{baseDir:B(process.cwd(),e.dir)}:void 0),p=process.env.AGENTX_INBOX_BASE_URL||"",u=[],f=s.telegram;if(f?.sendMessage){let{createTelegramTaskRenderer:k}=await import("./telegram-PIYDRM46.js");u.push(k({actors:c,tasks:l,adapter:{sendMessage:f.sendMessage.bind(f),sendWithInlineButtons:f.sendWithInlineButtons?.bind(f)},inboxBaseUrl:p,log:I=>this.log(I)}))}let m=s.whatsapp;if(m?.send){let{createWhatsappTaskRenderer:k}=await import("./whatsapp-PFRDMUMT.js");u.push(k({actors:c,tasks:l,adapter:{send:m.send.bind(m)},inboxBaseUrl:p,log:I=>this.log(I)}))}let g=s.slack;if(g?.send){let{createSlackTaskRenderer:k}=await import("./slack-6P7ZJ32Y.js");u.push(k({actors:c,tasks:l,adapter:{send:g.send.bind(g)},inboxBaseUrl:p,log:I=>this.log(I)}))}let h=u.length?async k=>{for(let I of u)try{await I(k)}catch{}}:void 0,{TimerService:y}=await import("./timers-5LPZN55J.js"),b=new y({baseDir:e.dir?B(process.cwd(),e.dir):void 0,log:k=>this.log(k)}),w=new cn({store:t,runs:n,nodeId:this.config.node.id,channels:s,agents:i,forwarder:r,actors:c,tasks:l,timers:b,events:this.events,renderUserTask:h,log:k=>this.log(k)});b.start();let T=dn(w);for(let[k,I]of Object.entries(T))I&&this.hooks.registerHandler(k,`workflows:${k}`,I,50);this.workflowDispatcher=w,this.workflowStore=t,this.workflowRuns=n,this.webhooks.setWorkflowDispatcher(w);let{cronTimers:S,hookSubscribers:v}=ln({store:t,dispatcher:w,hooks:this.hooks,log:k=>this.log(k)}),$=t.list().length;this.log(` Workflows: enabled (${$} definition${$===1?"":"s"} loaded from ${e.dir}, editor=${e.editor}, cron=${S}, hook=${v})`);try{let{detectConflicts:k}=await import("./conflict-detector-D7VIYPDI.js"),I=k(t.list(),this.config);if(I.length>0){this.log(` Workflows: ${I.length} dispatch conflict(s) detected`);for(let C of I)this.log(` [${C.severity}] ${C.workflowId}: ${C.summary}`),this.log(` \u2192 ${C.suggestion}`)}}catch(k){this.log(` Workflows: conflict-detector failed: ${k.message}`)}}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=ur(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}
|
|
641
|
+
data: ${JSON.stringify({time:new Date().toISOString(),message:t})}
|
|
642
|
+
|
|
643
|
+
`;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:Zn(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(c=>c.active>0);t.write(`event: status
|
|
644
|
+
data: ${JSON.stringify({node:this.config.node.name,agents:r.length,active:o.map(c=>({id:c.id,name:c.name,tasks:c.active})),mesh:this.mesh?.directory().map(c=>({peer:c.peer,healthy:c.healthy}))||[]})}
|
|
645
|
+
|
|
646
|
+
`),this.sseClients.add(t);let a=this.events.subscribe(i,c=>{try{t.write(`event: ${c.kind}
|
|
647
|
+
data: ${JSON.stringify(c)}
|
|
648
|
+
|
|
649
|
+
`)}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=(c,l)=>{if(!i)try{t.write(`event: ${c}
|
|
650
|
+
data: ${JSON.stringify(l)}
|
|
651
|
+
|
|
652
|
+
`)}catch{i=!0}},o=this.registry.subscribeToTaskOutput(s,c=>r("chunk",{text:c}));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
|
|
653
|
+
|
|
654
|
+
`)}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
|
|
655
|
+
data: ${JSON.stringify({callId:s,as:i})}
|
|
656
|
+
|
|
657
|
+
`);let r=this.webrtc.subscribe(s,i,t),o=setInterval(()=>{try{t.write(`: ping
|
|
658
|
+
|
|
659
|
+
`)}catch{}},15e3);e.on("close",()=>{clearInterval(o),r()})}serveCallPage(e){e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(qn)}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))),y=n.searchParams.get("workflowId")||void 0;this.json(t,200,{runs:this.workflowRuns.list({workflowId:y,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 G(e)}catch(k){this.json(t,400,{error:"invalid JSON body",message:k.message});return}let h=Array.isArray(g?.messages)?g.messages:[];if(!h.length){this.json(t,400,{error:"messages array required"});return}let y=h.filter(k=>k&&(k.role==="user"||k.role==="assistant")&&typeof k.content=="string").map(k=>({role:k.role,content:k.content}));if(!y.length){this.json(t,400,{error:"messages must contain at least one {role: 'user'|'assistant', content}"});return}let b=typeof g?.agentId=="string"&&g.agentId?g.agentId:process.env.AGENTX_WORKFLOW_AUTHOR_AGENT||this.registry.list()[0]?.id;if(!b){this.json(t,503,{error:"no authoring agent available \u2014 register an agent or set AGENTX_WORKFLOW_AUTHOR_AGENT"});return}let{buildWorkflowAuthorPrompt:w,extractWorkflowJson:T}=await import("./editor-chat-RVLCKKB7.js"),S=Object.keys(this.workflowDispatcher.channels).sort(),v=this.registry.list().map(k=>({id:k.id,description:k.name})),$=w({messages:y,store:this.workflowStore,actors:this.workflowDispatcher.actors,availableAgents:v,availableChannels:S,currentWorkflow:g?.currentWorkflow});try{let k=await this.registry.execute({agentId:b,message:$,context:{channel:"workflow-editor",chatId:"editor",sender:"editor"}});if(k.error){this.json(t,502,{error:k.error,agentId:b});return}let I=k.content??"",C=T(I);this.json(t,200,{reply:I,workflow:C,agentId:b})}catch(k){this.json(t,500,{error:"agent execute failed",message:k.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 G(e)}catch(b){this.json(t,400,{error:"invalid JSON body",message:b.message});return}let y=this.workflowDispatcher.emitSignal({name:g,scope:h?.scope,workflowId:h?.workflowId,payload:h?.payload});this.json(t,200,{ok:!0,emission:y});return}if(e.method==="GET"&&s==="/inbox"){let{renderInboxPage:g}=await import("./inbox-BIN2S5XN.js"),h=n.searchParams,y=g({actor:h.get("actor")||void 0});t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(y);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],y=n.searchParams.get("actor")||"anonymous",b=await this.workflowDispatcher.submitTask(g,{action:h,values:{}},y);t.writeHead(b.ok?200:400,{"Content-Type":"text/html; charset=utf-8"}),b.ok?t.end(`<!doctype html><meta charset=utf-8><title>Submitted</title>
|
|
660
|
+
<body style="font-family:system-ui;max-width:520px;margin:48px auto;padding:0 16px;text-align:center">
|
|
661
|
+
<h1 style="color:#27ae60">\u2713 Submitted</h1>
|
|
662
|
+
<p>Your <strong>${h==="primary"?"approval":"rejection"}</strong> has been recorded. You can close this tab.</p>
|
|
663
|
+
<p style="color:#888;font-size:13px">Run <code>${b.runId}</code></p>
|
|
664
|
+
</body>`):t.end(`<!doctype html><meta charset=utf-8><title>Submit failed</title>
|
|
665
|
+
<body style="font-family:system-ui;max-width:520px;margin:48px auto;padding:0 16px;text-align:center">
|
|
666
|
+
<h1 style="color:#c0392b">\u2717 ${b.error}</h1>
|
|
667
|
+
${Array.isArray(b.fieldErrors)&&b.fieldErrors.length?`<p>This task has required fields. Please open the <a href="/inbox?actor=${encodeURIComponent(y)}">inbox</a> instead.</p>`:""}
|
|
668
|
+
</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(y=>{let b="";e.on("data",w=>b+=w.toString()),e.on("end",()=>y(b)),e.on("error",()=>y(""))}),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(y=>this.log(`[github] webhook handler error: ${y.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 c=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks$/);if(c){let g=Math.max(1,Math.min(500,parseInt(n.searchParams.get("limit")||"50",10)||50));this.json(t,200,this.registry.listTaskHistory(c[1],g));return}let l=e.method==="GET"&&s.match(/^\/agents\/([^/]+)\/tasks\/([^/]+)$/);if(l){let g=this.registry.getTaskRecord(l[1],l[2]);if(!g){this.json(t,404,{error:"not found"});return}this.json(t,200,g);return}let p=e.method==="GET"&&s.match(/^\/agents\/([^/]+)$/);if(p){let g=p[1],h=this.config.agents[g];if(!h){this.json(t,404,{error:"agent not found"});return}let y=Nt(h);this.json(t,200,{id:g,name:h.name,tier:h.tier,model:h.model??null,workspace:h.workspace,mentions:h.mentions??[],maxConcurrent:h.maxConcurrent,maxExecutionMinutes:h.maxExecutionMinutes,permission:y,persistentProcess:!!h.persistentProcess,toolUseRequired:h.toolUseRequired??[]});return}if(e.method==="GET"&&s==="/traces"){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let g=y=>{let b=n.searchParams.get(y);if(b===null||b==="")return;let w=parseInt(b,10);return Number.isFinite(w)?w:void 0},h=nn(this.db,{agentId:n.searchParams.get("agentId")||void 0,channel:n.searchParams.get("channel")||void 0,chatId:n.searchParams.get("chatId")||void 0,workflowRunId:n.searchParams.get("workflowRunId")||void 0,status:n.searchParams.get("status")||void 0,since:g("since"),until:g("until"),limit:g("limit")});this.json(t,200,{traces:h});return}let f=e.method==="GET"&&s.match(/^\/traces\/([^/]+)$/);if(f){if(!this.db){this.json(t,503,{error:"sqlite not opened"});return}let g=en(this.db,f[1]);if(!g){this.json(t,404,{error:"not found"});return}this.json(t,200,g);return}if(e.method==="GET"&&s==="/api/processes"){if(!this.processRegistry){this.json(t,503,{error:"process registry not enabled"});return}this.json(t,200,{processes:this.processRegistry.list()});return}if(e.method==="GET"&&s==="/api/actions/builtin"){this.json(t,200,{actions:et()});return}let m=e.method==="POST"&&s.match(/^\/api\/actions\/builtin\/([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*)$/);if(m){let g=m[1];if(!Jt(g)){this.json(t,404,{error:`unknown built-in: ${g}`});return}try{let h=await G(e),y=await zt(g,h);this.json(t,200,{output:y})}catch(h){h?.name==="ZodError"?this.json(t,400,{error:h.message}):this.json(t,500,{error:h?.message||String(h)})}return}if(e.method==="POST"&&s==="/api/processes/kill"){if(!this.processRegistry){this.json(t,503,{error:"process registry not enabled"});return}try{let g=await G(e),{agentId:h,channel:y,chatId:b,reason:w}=g;if(!h||!y||!b){this.json(t,400,{error:"agentId, channel, chatId required"});return}await this.processRegistry.kill({agentId:h,channel:y,chatId:b},w||"operator"),this.json(t,200,{killed:{agentId:h,channel:y,chatId:b}})}catch(g){this.json(t,500,{error:g?.message||String(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 y=await import("qrcode"),w=await(y.default||y).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(w)}catch(y){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("qrcode package not installed or failed: "+(y?.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),y=this.config.channels.whatsapp.ingest;if(!y.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 b=typeof h.agent=="string"&&h.agent||this.config.channels.whatsapp.defaultAgent||this.config.node.defaultAgent;if(!b){this.json(t,400,{error:"No agent to own the entries. Pass {agent: '...'} or set channels.whatsapp.defaultAgent."});break}let w=!!h.dryRun,{runSweep:T}=await import("./ingest-whatsapp-LZE62INA.js"),S=this.registry.getWikiHub().getAgentWiki(b),v=y;if(typeof h.onlyJid=="string"){let k=h.onlyJid,I=k.endsWith("@g.us"),C=h.forceMode==="metadata-only"||h.forceMode==="messages"?h.forceMode:void 0;v={...y,enabled:!0,mode:C??y.mode,allowContacts:I||h.onlyKind==="group"?[]:[k],allowGroups:I||h.onlyKind==="group"?[k]:[],denyContacts:[],denyGroups:[]}}let $=await T({source:g,store:S,config:v,agentId:b,dryRun:w});this.json(t,200,$);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:y,noteableIid:b,noteId:w,agentId:T}=g,v=(this.config.channels.gitlab?.agentMappings||[]).find(x=>x.agentId===T),$=v?.token||this.config.channels.gitlab?.token,k=this.config.channels.gitlab?.host;if(this.log(`[gitlab/react] agent="${T}" project="${h}" mappingFound=${!!v} mappingToken=${!!v?.token} globalToken=${!!this.config.channels.gitlab?.token}(len=${(this.config.channels.gitlab?.token||"").length}) host=${k||"MISSING"}`),!$||!k){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:T,mappingFound:!!v,hasMappingToken:!!v?.token,hasGlobalToken:!!this.config.channels.gitlab?.token,hasHost:!!k}});break}let I=encodeURIComponent(h),C=y==="issue"?`${k}/api/v4/projects/${I}/issues/${b}/notes/${w}/award_emoji`:`${k}/api/v4/projects/${I}/merge_requests/${b}/notes/${w}/award_emoji`;try{let x=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":$},body:JSON.stringify({name:"eyes"})}),A=await x.text().catch(()=>"");this.log(`[gitlab/react] -> POST ${C} : ${x.status} ${A.slice(0,120)}`),this.json(t,200,{ok:x.ok,status:x.status,gitlabResponse:A.slice(0,200)})}catch(x){this.log(`[gitlab/react] FETCH ERROR: ${x.message}`),this.json(t,500,{error:x.message})}break}case"POST /gitlab/send-note":{let g=await M(e),{project:h,noteableType:y,noteableIid:b,agentId:w,text:T}=g,$=(this.config.channels.gitlab?.agentMappings||[]).find(x=>x.agentId===w)?.token||this.config.channels.gitlab?.token,k=this.config.channels.gitlab?.host;if(!$||!k){this.json(t,404,{error:"no gitlab token for agent",debug:{agentId:w,hasToken:!!$,hasHost:!!k}});break}let I=encodeURIComponent(h),C=y==="issue"?`${k}/api/v4/projects/${I}/issues/${b}/notes`:`${k}/api/v4/projects/${I}/merge_requests/${b}/notes`;try{let x=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":$},body:JSON.stringify({body:T})}),A=await x.text().catch(()=>""),R="";try{R=String(JSON.parse(A).id||"")}catch{}this.log(`[gitlab/send-note] agent="${w}" -> POST ${C} : ${x.status} noteId=${R||"?"}`),this.json(t,200,{ok:x.ok,status:x.status,noteId:R})}catch(x){this.log(`[gitlab/send-note] FETCH ERROR: ${x.message}`),this.json(t,500,{error:x.message})}break}case"POST /gitlab/log-time":{let g=await M(e),{project:h,noteableType:y,noteableIid:b,agentId:w,durationMs:T}=g,$=(this.config.channels.gitlab?.agentMappings||[]).find(P=>P.agentId===w)?.token||this.config.channels.gitlab?.token,k=this.config.channels.gitlab?.host;if(!$||!k){this.json(t,404,{error:"no gitlab token for agent"});break}let I=Math.max(60,Math.round(Number(T)/1e3)),C=Math.floor(I/3600),x=Math.ceil(I%3600/60),A=C>0?`${C}h${x>0?` ${x}m`:""}`:`${x}m`,R=encodeURIComponent(h),Y=`${k}/api/v4/projects/${R}/${y==="merge_request"?"merge_requests":"issues"}/${b}/add_spent_time`;try{let P=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":$},body:JSON.stringify({duration:A})});this.log(`[gitlab/log-time] agent="${w}" duration=${A} -> POST ${Y} : ${P.status}`),this.json(t,200,{ok:P.ok,status:P.status,duration:A})}catch(P){this.log(`[gitlab/log-time] FETCH ERROR: ${P.message}`),this.json(t,500,{error:P.message})}break}case"POST /github/send-comment":{let g=await M(e),{repo:h,issueNumber:y,agentId:b,text:w}=g,T=this.config.channels.github,v=(T?.agentMappings||[]).find(I=>I.agentId===b),$;if(v?.tokenFile)try{$=Xe(v.tokenFile,"utf-8").trim().split(`
|
|
669
|
+
`)[0].trim()}catch{}if($=$||v?.token,!$&&T?.tokenFile)try{$=Xe(T.tokenFile,"utf-8").trim().split(`
|
|
670
|
+
`)[0].trim()}catch{}if($=$||T?.token,!$){this.json(t,404,{error:"no github token for agent",debug:{agentId:b,hasMapping:!!v}});break}let k=`https://api.github.com/repos/${h}/issues/${y}/comments`;try{let I=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`,"User-Agent":"AgentX"},body:JSON.stringify({body:w})}),C=await I.text().catch(()=>""),x="";try{x=String(JSON.parse(C).id||"")}catch{}this.log(`[github/send-comment] agent="${b}" -> POST ${k} : ${I.status} commentId=${x||"?"}`),this.json(t,200,{ok:I.ok,status:I.status,commentId:x})}catch(I){this.log(`[github/send-comment] FETCH ERROR: ${I.message}`),this.json(t,500,{error:I.message})}break}case"POST /github/react":{let g=await M(e),{repo:h,commentId:y,agentId:b}=g,w=this.config.channels.github,S=(w?.agentMappings||[]).find(k=>k.agentId===b),v;if(S?.tokenFile)try{v=Xe(S.tokenFile,"utf-8").trim().split(`
|
|
671
|
+
`)[0].trim()}catch{}if(v=v||S?.token,!v&&w?.tokenFile)try{v=Xe(w.tokenFile,"utf-8").trim().split(`
|
|
672
|
+
`)[0].trim()}catch{}if(v=v||w?.token,!v){this.json(t,404,{error:"no github token for agent"});break}let $=`https://api.github.com/repos/${h}/issues/comments/${y}/reactions`;try{let k=await fetch($,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`,"User-Agent":"AgentX"},body:JSON.stringify({content:"eyes"})});this.log(`[github/react] agent="${b}" -> POST ${$} : ${k.status}`),this.json(t,200,{ok:k.ok,status:k.status})}catch(k){this.log(`[github/react] FETCH ERROR: ${k.message}`),this.json(t,500,{error:k.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(y=>String(y)):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),y=String(g.text);if(this.registry.getAgent(h)){try{let S=g.senderAgentId?String(g.senderAgentId):void 0,v=await this.registry.execute({agentId:h,message:y,context:{channel:"a2a",sender:S?`agent:${S}`:"agent",chatId:S||"a2a"}});this.json(t,v.error?500:200,{ok:!v.error,content:v.content,error:v.error})}catch(S){this.json(t,500,{error:S.message})}break}if(!this.mesh){this.json(t,400,{error:`Unknown agent "${h}" \u2014 mesh disabled, no remote lookup possible`});break}let w=this.mesh.directory(),T=w.find(S=>S.healthy&&S.skills.some(v=>v.id===h));if(!T){let S=[...Object.keys(this.config.agents),...w.flatMap(v=>v.skills.map($=>$.id))];this.json(t,404,{error:`Unknown agent "${h}"`,known:S});break}try{let S=g.senderAgentId?String(g.senderAgentId):void 0,v=await this.mesh.sendTask(T.peer,y,h,{senderAgentId:S});this.json(t,200,{ok:!0,messageId:v,peer:T.peer})}catch(S){this.json(t,500,{error:S.message,peer:T.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),y=String(g.text),b=g.channel?String(g.channel):void 0,w=g.confirmed===!0,T=this.contacts.resolve(h);if(T.kind==="miss"){this.json(t,404,{error:`No contact matches "${h}"`,hint:"Add the contact to .agentx/contacts.json and POST /reload."});break}if(T.kind==="ambiguous"){this.json(t,409,{error:"ambiguous",candidates:T.candidates.map(k=>({id:k.id,name:k.name,channels:Object.keys(k.channels)}))});break}if(T.kind==="fuzzy"&&!w){this.json(t,409,{error:"fuzzy-match-needs-confirmation",candidate:{id:T.contact.id,name:T.contact.name,channels:Object.keys(T.contact.channels)},confidence:T.confidence,hint:"Re-call with confirmed:true once the user has confirmed this is the intended recipient."});break}let S=!!this.registry.getAgent(h),v=this.mesh?.directory()?.some(k=>k.skills.some(I=>I.id.toLowerCase()===h.toLowerCase()));if(S||v){this.json(t,409,{error:"ambiguous",hint:`"${h}" resolves to BOTH a contact (id=${T.contact.id}) and an agent. Use /send/agent for the agent, or pass contactId="${T.contact.id}" to /send/contact for the contact.`});break}let $=this.contacts.pickChannel(T.contact,b);if(!$){this.json(t,400,{error:`Contact "${T.contact.id}" has no channels configured`});break}if(b&&$.channel!==b){this.json(t,400,{error:`Contact "${T.contact.id}" has no "${b}" channel`,available:Object.keys(T.contact.channels)});break}try{let k=await this.router.sendOutbound({channel:$.channel,chatId:$.address,text:y,agentId:g.agentId,accountId:g.accountId});this.json(t,200,{ok:!0,messageId:k||null,contactId:T.contact.id,channel:$.channel})}catch(k){this.json(t,400,{error:k.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 y=typeof g.senderAgentId=="string"?g.senderAgentId:void 0;!g.context&&!y&&this.log(`[a2a] /task accepted without senderAgentId for agent="${h}" from ${e.socket?.remoteAddress||"unknown"} \u2014 caller should upgrade. Required in next release.`);let w=g.contextStrategy==="layered"||g.contextStrategy==="planner"?g.contextStrategy:void 0,T;if(D("mesh")!=="off")try{let v=rs(j(),{agentId:h,senderAgentId:y,context:g.context},JSON.stringify({agentId:h,senderAgentId:y,context:g.context,message:typeof g.message=="string"?g.message.slice(0,200):""}),{agentId:h,outcome:"dispatched",reason:y?`from ${y}`:null});v.outcome==="dispatched"&&(T={eventId:v.eventId,decidedBy:v.decidedBy})}catch(v){this.log(`[ledger] mesh /task agent="${h}" record failed: ${v?.message??v}`)}let S=await this.registry.execute({agentId:h,message:g.message,context:g.context,contextStrategy:w,intentRef:T,freshSession:g.freshSession===!0?!0:void 0},()=>{});this.json(t,S.error?500:200,S);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 S=await M(e);h=S.message||S.q||h}let y=this.config.node.defaultAgent;if(!y){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 b=`[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.]
|
|
673
|
+
|
|
674
|
+
${h}`,w=await this.registry.execute({agentId:y,message:b,context:{channel:"voice",sender:"Siri"}}),T=br(w.content);this.json(t,w.error?500:200,{text:T,full:w.content,error:w.error,duration:w.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 y=await this.webrtc.handleOutgoing(h);this.json(t,y.ok?200:400,y);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 y=this.webrtc.handleIncoming(h);this.json(t,y.ok?200:400,y);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,y=g.target,b=g.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!h||!y||!b){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let w=await this.botManager.invite({callId:h,target:y,agentId:b});this.json(t,w.ok?200:500,w);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]||{},y=typeof h.description=="string"&&h.description.trim()||yr(h.systemPrompt)||`Agent "${g.name}" (${g.tier})`,b=Array.isArray(h.mentions)?h.mentions.slice(0,4):[];return{id:g.id,name:g.name,description:y,tags:[g.tier,...b]}}),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,y=n.searchParams.get("after")||void 0,b=h?g.getAgentEntries(h):g.getSharedStore().listEntries({after:y});this.json(t,200,{nodeId:this.config.node.id,count:b.length,entries:b.map(w=>({id:w.id,date:w.date,agentId:w.agentId,source:w.source,sourceContext:w.sourceContext,content:w.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 b=g.getAgentWiki(h).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:h,articles:b.articles});break}case"GET /wiki/article":{let g=this.registry.getWikiHub(),h=n.searchParams.get("agent"),y=n.searchParams.get("path");if(!h||!y){this.json(t,400,{error:"?agent= and ?path= required"});break}let w=g.getAgentWiki(h).readArticle(y);if(!w){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:h,path:w.path,title:w.meta.title,tags:w.meta.tags,owner:w.meta.owner,created:w.meta.created,lastUpdated:w.meta.lastUpdated,sources:w.meta.sources,content:w.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",y=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),b=g.listByStatus(h,y);this.json(t,200,{nodeId:this.config.node.id,status:h,count:b.length,classifications:b});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?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","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||[],c=[...a].reverse().find(f=>f.role==="user");if(!c?.content){this.json(t,400,{error:{message:"No user message found",type:"invalid_request_error"}});return}let l=a.slice(0,-1).map(f=>`${f.role==="user"?"User":"Assistant"}: ${f.content.slice(0,200)}`),p=l.length>0?`[Conversation]
|
|
675
|
+
${l.slice(-10).join(`
|
|
676
|
+
`)}
|
|
677
|
+
|
|
678
|
+
`:"";if(s.stream===!0){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let f=`chatcmpl-${Date.now().toString(36)}`,m=await this.registry.execute({agentId:o,message:p+c.content,context:{channel:"api",sender:"openai-compat"}}),g=m.error||m.content||"",h={id:f,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,delta:{role:"assistant",content:g},finish_reason:"stop"}]};t.write(`data: ${JSON.stringify(h)}
|
|
679
|
+
|
|
680
|
+
`),t.write(`data: [DONE]
|
|
681
|
+
|
|
682
|
+
`),t.end()}else{let f=await this.registry.execute({agentId:o,message:p+c.content,context:{channel:"api",sender:"openai-compat"}}),m=f.error||f.content||"",g=Math.ceil(m.length/4);this.json(t,200,{id:`chatcmpl-${Date.now().toString(36)}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:o,choices:[{index:0,message:{role:"assistant",content:m},finish_reason:"stop"}],usage:{prompt_tokens:Math.ceil(c.content.length/4),completion_tokens:g,total_tokens:Math.ceil(c.content.length/4)+g}})}}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveTodayUsage(){let e=ss();if(e==="json")return this.registry.getTodayUsage();let t=ns(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||!ue(t)))try{let n=B(t,".claude","skills");bs(n,{recursive:!0});let s=B(n,ls);ue(s)||(ys(s,gs),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||!ue(n))continue;let s=t.mcp??{};try{switch(ds(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 c=i.get(a,decodeURIComponent(r[1]));return c?(this.json(t,200,{memory:c}),!0):(this.json(t,404,{error:"no such memory"}),!0)}if(e.method==="POST"&&n==="/api/memory"){let a;try{a=await G(e)}catch(g){return this.json(t,400,{error:"invalid JSON body",message:g.message}),!0}let c=typeof a?.agentId=="string"?a.agentId:"",l=typeof a?.type=="string"?a.type:"",p=typeof a?.name=="string"?a.name:"",u=typeof a?.description=="string"?a.description:"",f=typeof a?.body=="string"?a.body:"",m=a?.append===!0;if(!c||!l||!p||!u||!f)return this.json(t,400,{error:"required fields: agentId, type, name, description, body"}),!0;try{let g=f;if(m){let b=i.get(c,p);b&&(g=`${b.body.trimEnd()}
|
|
683
|
+
|
|
684
|
+
${f.trim()}`)}let h=i.save({agentId:c,type:l,name:p,description:u,body:g}),y=this.workspaceFor(c);if(y)try{i.syncToWorkspace(c,y)}catch{}this.json(t,200,{ok:!0,memory:h,syncedToWorkspace:!!y})}catch(g){this.json(t,400,{error:g?.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 l=this.workspaceFor(a);if(l)try{i.syncToWorkspace(a,l)}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 l=new URL(e.url||"/","http://_").searchParams.get("actor")||void 0,p=l?s.tasks.listForActor(l):s.tasks.listOpen();return this.json(t,200,{tasks:p}),!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 c;try{c=await G(e)}catch(m){return this.json(t,400,{error:"invalid JSON body",message:m.message}),!0}let l=c&&typeof c=="object"&&"submission"in c?c.submission:c,p=i.safeParse(l);if(!p.success)return this.json(t,400,{error:"invalid submission",issues:p.error.issues.map(m=>({path:m.path.join("."),message:m.message}))}),!0;let u=typeof c?.submittedBy=="string"?c.submittedBy:"anonymous",f=await s.submitTask(a,p.data,u);return f.ok?(this.json(t,200,{ok:!0,runId:f.runId}),!0):(this.json(t,400,{error:f.error,fieldErrors:f.fieldErrors}),!0)}if(e.method==="GET"){let c=s.tasks.get(a);return c?(this.json(t,200,{task:c}),!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 G(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 u=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${u}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:r,event:i,fromRemote:{peer:u}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(m=>m.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(m=>m.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(u=>u.type.startsWith("trigger."))?.config??{},p={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels};await this.workflowDispatcher.dispatch({trigger:p,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 G(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=(c,l)=>{let p=0;for(let u of c)!u.id||s.has(u.id)||(s.add(u.id),i.push({...u,source:l}),p++);p>0&&r.push(`${l}:${p}`)},a=this.router.getChannel(t);if(a?.listKnownChats)try{o(a.listKnownChats(),"local")}catch{}else if(a?.listChats)try{o(a.listChats().map(c=>({id:c.jid,name:c.name,kind:c.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let c=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(c.map(async l=>{try{let p=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{signal:AbortSignal.timeout(5e3)});if(!p.ok)return;let u=await p.json();Array.isArray(u.chats)&&o(u.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${l.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(m=>m.type.startsWith("trigger."));if(!i){this.json(t,400,{error:`workflow "${n}" has no trigger node`});return}let r;try{r=await G(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 c=i.config??{},l=o?String(c.source??"manual"):"manual",p=String(a.entityId||a.chatId||`manual-${Date.now().toString(36)}`),u={backend:o&&c.source?"channel":"manual",id:p},f=`manual:${n}:${p}:${Date.now()}`;try{let g=(await this.workflowDispatcher.dispatch({trigger:o?{source:l,project:c.filter?.project,repo:c.filter?.repo,chat:c.filter?.chat,labels:c.filter?.labels}:{source:"manual"},entityRef:u,event:{id:f,payload:a}})).runs[0]?.id;this.json(t,g?200:202,{ok:!0,runId:g,entityRef:u,source:l,force:o})}catch(m){this.log(`[workflows] manual run "${n}" failed: ${m.message}`),this.json(t,500,{error:m.message})}}};function yr(d){if(typeof d!="string")return"";let e=d.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 G(d){return new Promise((e,t)=>{let n="";d.setEncoding("utf8"),d.on("data",s=>{n+=s}),d.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),d.on("error",t)})}function br(d){let e=d;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 wr(d,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(d),...Object.keys(e)]);for(let i of s){let r=d[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(d){return new Promise((e,t)=>{let n="";d.on("data",s=>n+=s.toString()),d.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),d.on("error",t)})}function Id(d){typeof d=="string"&&(me.error(d),process.exit(1)),d instanceof Error&&(me.error(d.message),process.exit(1)),me.error("Something went wrong. Please try again."),process.exit(1)}import Mt from"path";import ks from"fs-extra";function Ad(){let d=[];try{let e=import.meta.dirname;e&&(d.push(Mt.resolve(e,"..","package.json")),d.push(Mt.resolve(e,"package.json")))}catch{}d.push(Mt.resolve(process.cwd(),"package.json"));for(let e of d)try{if(ks.existsSync(e)){let t=ks.readJSONSync(e);if(t&&t.name)return t}}catch{}return{name:"agentix-cli",version:"0.0.0"}}export{xr as a,te as b,fe as c,ae as d,V as e,$e as f,kt as g,ze as h,fs as i,ws as j,Id as k,Ad as l};
|
|
685
|
+
//# sourceMappingURL=chunk-EQPUB7CZ.js.map
|