@toolpack-sdk/agents 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/capabilities/index.cjs +16 -14
- package/dist/capabilities/index.js +15 -13
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.d.cts +1 -1
- package/dist/channels/index.d.ts +1 -1
- package/dist/channels/index.js +2 -2
- package/dist/{index-CA38tE7C.d.cts → index-BRuKydRC.d.cts} +11 -1
- package/dist/{index-BCBukKC4.d.ts → index-BjieDC5c.d.ts} +11 -1
- package/dist/index.cjs +38 -36
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +39 -37
- package/package.json +3 -3
package/dist/channels/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var D=Object.create;var C=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var U=(a,e)=>{for(var n in e)C(a,n,{get:e[n],enumerable:!0})},A=(a,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R(e))!N.call(a,i)&&i!==n&&C(a,i,{get:()=>e[i],enumerable:!(t=E(e,i))||t.enumerable});return a};var p=(a,e,n)=>(n=a!=null?D(O(a)):{},A(e||!a||!a.__esModule?C(n,"default",{value:a,enumerable:!0}):n,a)),B=a=>A(C({},"__esModule",{value:!0}),a);var j={};U(j,{BaseChannel:()=>l,DiscordChannel:()=>I,EmailChannel:()=>T,McpChannel:()=>x,SMSChannel:()=>P,ScheduledChannel:()=>b,SlackChannel:()=>v,TelegramChannel:()=>S,WebhookChannel:()=>k});module.exports=B(j);var l=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};var y=require("crypto");var v=class extends l{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,c=`v0=${(0,y.createHmac)("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(c.length!==i.length)return!1;try{return(0,y.timingSafeEqual)(Buffer.from(c),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,d=n.user,c=d?{kind:"user",id:d}:void 0,m=/<@([A-Z0-9]+)>/g,u=[],f;for(;(f=m.exec(i))!==null;)u.push(f[1]);let g=n.channel;return{message:i,conversationId:o?r:g||s||"",data:n,participant:c,context:{user:d,channel:g,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:u.length>0?u:void 0,channelId:g,channelName:typeof this.config.channel=="string"?this.config.channel:g}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let d={kind:"user",id:n};return this.participantCache.set(n,d),d}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let d=e.channel;if(!d||!this.allowedChannels.includes(d))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var k=class extends l{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((d,c)=>{this.pendingResponses.set(r,{resolve:d,reject:c}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(d=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(d))}).catch(d=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:d.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var _=require("cron-parser"),b=class extends l{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{_.CronExpressionParser.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return _.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};var S=class extends l{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown"})});if(!t.ok)throw new Error(`Failed to send Telegram message: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.message||n.edited_message||{},i=t.text||"",s=t.chat||{},r=t.from||{},o=r.id!=null?String(r.id):void 0,d=r.first_name||r.username||o,c=o?{kind:"user",id:o,displayName:d??o}:void 0,m=t.entities??[],u=[];for(let w of m)if(w.type==="text_mention"&&w.user){let $=w.user;$.id!=null&&u.push(String($.id))}let f=s.type,g=s.id!=null?String(s.id):"";return{message:i,conversationId:g,data:n,participant:c,context:{chatId:s.id,userId:r.id,username:r.username,firstName:r.first_name,lastName:r.last_name,messageId:t.message_id,channelType:f,channelId:g,channelName:s.title,mentions:u.length>0?u:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var z=new Set([1,3]),M=/<@!?(\d+)>/g,F="https://discord.com/api/v10",I=class extends l{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&z.has(s),o=n.author?.id,d=n.author?.globalName??n.author?.username,c=[];if(n.content){M.lastIndex=0;let m;for(;(m=M.exec(n.content))!==null;)c.push(m[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:d??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:c.length>0?c:void 0,isMentioned:this.botUserId?c.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${F}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var T=class extends l{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
|
|
1
|
+
"use strict";var B=Object.create;var y=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var H=(d,e)=>{for(var n in e)y(d,n,{get:e[n],enumerable:!0})},R=(d,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!W.call(d,i)&&i!==n&&y(d,i,{get:()=>e[i],enumerable:!(t=F(e,i))||t.enumerable});return d};var p=(d,e,n)=>(n=d!=null?B(j(d)):{},R(e||!d||!d.__esModule?y(n,"default",{value:d,enumerable:!0}):n,d)),J=d=>R(y({},"__esModule",{value:!0}),d);var G={};H(G,{BaseChannel:()=>l,DiscordChannel:()=>_,EmailChannel:()=>x,McpChannel:()=>M,SMSChannel:()=>$,ScheduledChannel:()=>T,SlackChannel:()=>b,TelegramChannel:()=>P,WebhookChannel:()=>I});module.exports=J(G);var l=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};var S=require("crypto");var b=class extends l{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,c=`v0=${(0,S.createHmac)("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(c.length!==i.length)return!1;try{return(0,S.timingSafeEqual)(Buffer.from(c),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,a=n.user,c=a?{kind:"user",id:a}:void 0,m=/<@([A-Z0-9]+)>/g,k=[],f;for(;(f=m.exec(i))!==null;)k.push(f[1]);let w=n.channel;return{message:i,conversationId:o?r:w||s||"",data:n,participant:c,context:{user:a,channel:w,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:k.length>0?k:void 0,channelId:w,channelName:typeof this.config.channel=="string"?this.config.channel:w}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let a={kind:"user",id:n};return this.participantCache.set(n,a),a}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let a=e.channel;if(!a||!this.allowedChannels.includes(a))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var I=class extends l{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((a,c)=>{this.pendingResponses.set(r,{resolve:a,reject:c}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(a=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(a))}).catch(a=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:a.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var D=require("cron-parser"),T=class extends l{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{D.CronExpressionParser.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return D.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};var P=class extends l{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=e.metadata?.replyMarkup,i=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown",...t?{reply_markup:t}:{}})});if(!i.ok)throw new Error(`Failed to send Telegram message: ${i.statusText}`);let s=await i.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,n){let t=await fetch(`https://api.telegram.org/bot${this.config.token}/answerCallbackQuery`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callback_query_id:e,...n?{text:n}:{}})});if(!t.ok)throw new Error(`Failed to answer Telegram callback query: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.callback_query;if(t){let C=t.message||{},u=C.chat||{},g=t.from||{},v=g.id!=null?String(g.id):void 0,O=g.first_name||g.username||v,U=v?{kind:"user",id:v,displayName:O??v}:void 0,E=u.id!=null?String(u.id):"";return{message:t.data??"",conversationId:E,data:n,participant:U,context:{isCallback:!0,callbackQueryId:t.id,callbackData:t.data,chatId:u.id,userId:g.id,username:g.username,firstName:g.first_name,lastName:g.last_name,messageId:C.message_id,channelType:u.type,channelId:E,channelName:u.title}}}let i=n.message||n.edited_message||{},s=i.text||"",r=i.chat||{},o=i.from||{},a=o.id!=null?String(o.id):void 0,c=o.first_name||o.username||a,m=a?{kind:"user",id:a,displayName:c??a}:void 0,k=i.entities??[],f=[];for(let C of k)if(C.type==="text_mention"&&C.user){let u=C.user;u.id!=null&&f.push(String(u.id))}let w=r.type,A=r.id!=null?String(r.id):"";return{message:s,conversationId:A,data:n,participant:m,context:{chatId:r.id,userId:o.id,username:o.username,firstName:o.first_name,lastName:o.last_name,messageId:i.message_id,channelType:w,channelId:A,channelName:r.title,mentions:f.length>0?f:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var q=new Set([1,3]),N=/<@!?(\d+)>/g,L="https://discord.com/api/v10",_=class extends l{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&q.has(s),o=n.author?.id,a=n.author?.globalName??n.author?.username,c=[];if(n.content){N.lastIndex=0;let m;for(;(m=N.exec(n.content))!==null;)c.push(m[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:a??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:c.length>0?c:void 0,isMentioned:this.botUserId?c.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${L}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var x=class extends l{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
|
|
2
2
|
|
|
3
|
-
`).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var
|
|
3
|
+
`).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var $=class extends l{config;twilioClient;server;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name}get isTriggerChannel(){return!this.config.webhookPath}listen(){typeof process<"u"&&import("twilio").then(e=>{this.twilioClient=e.default(this.config.accountSid,this.config.authToken),console.log("[SMSChannel] Twilio client initialized"),this.config.webhookPath&&this.startWebhookServer()}).catch(e=>{console.error("[SMSChannel] Failed to initialize Twilio client:",e),console.error("[SMSChannel] Make sure to install twilio: npm install twilio")})}async send(e){if(!this.twilioClient)throw new Error("Twilio client not initialized. Did you call listen()?");let n=e.metadata?.from||this.config.to;if(!n)throw new Error('No recipient phone number specified. Set "to" in config or provide in output.metadata.from');try{await this.twilioClient.messages.create({body:e.output,from:this.config.from,to:n})}catch(t){throw console.error("[SMSChannel] Failed to send SMS:",t),new Error(`Failed to send SMS: ${t instanceof Error?t.message:String(t)}`)}}normalize(e){let n=e,t=n.From,i=n.Body,s=n.MessageSid;return{message:i,conversationId:t,data:n,context:{from:t,to:n.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleWebhookRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SMSChannel] Webhook server listening on port ${this.config.port} at ${this.config.webhookPath}`)})}).catch(e=>{console.error("[SMSChannel] Failed to start webhook server:",e)})}handleWebhookRequest(e,n){if(e.method!=="POST"||e.url!==this.config.webhookPath){n.writeHead(404),n.end("Not found");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=new URLSearchParams(t),s={};i.forEach((o,a)=>{s[a]=o});let r=this.normalize(s);this.handleMessage(r),n.writeHead(200,{"Content-Type":"text/xml"}),n.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(i){console.error("[SMSChannel] Error handling webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var M=class extends l{isTriggerChannel=!1;_timeout;_pendingResolve;constructor(e={}){super(),this._timeout=e.timeout??12e4}listen(){}async send(e){this._pendingResolve?.(e),this._pendingResolve=void 0}normalize(e){let n=e;return{message:typeof n.message=="string"?n.message:JSON.stringify(n),data:n,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let n=this.normalize(e);return new Promise((t,i)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,i(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=r=>{clearTimeout(s),t(r.output)},this.handleMessage(n).catch(r=>{clearTimeout(s),this._pendingResolve=void 0,i(r instanceof Error?r:new Error(String(r)))})})}asAgentDefinition(e,n){return{name:e.name,description:e.description,...n!==void 0&&{inputSchema:n},invoke:t=>this.trigger(t)}}};0&&(module.exports={BaseChannel,DiscordChannel,EmailChannel,McpChannel,SMSChannel,ScheduledChannel,SlackChannel,TelegramChannel,WebhookChannel});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-
|
|
1
|
+
export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-BRuKydRC.cjs';
|
|
2
2
|
import '../types-C3EZvpe0.cjs';
|
|
3
3
|
import 'toolpack-sdk';
|
|
4
4
|
import 'events';
|
package/dist/channels/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-
|
|
1
|
+
export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-BjieDC5c.js';
|
|
2
2
|
import '../types-C3EZvpe0.js';
|
|
3
3
|
import 'toolpack-sdk';
|
|
4
4
|
import 'events';
|
package/dist/channels/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var d=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};import{createHmac as $,timingSafeEqual as A}from"crypto";var C=class extends d{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,l=`v0=${$("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(l.length!==i.length)return!1;try{return A(Buffer.from(l),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,a=n.user,l=a?{kind:"user",id:a}:void 0,m=/<@([A-Z0-9]+)>/g,g=[],f;for(;(f=m.exec(i))!==null;)g.push(f[1]);let p=n.channel;return{message:i,conversationId:o?r:p||s||"",data:n,participant:l,context:{user:a,channel:p,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:g.length>0?g:void 0,channelId:p,channelName:typeof this.config.channel=="string"?this.config.channel:p}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let a={kind:"user",id:n};return this.participantCache.set(n,a),a}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let a=e.channel;if(!a||!this.allowedChannels.includes(a))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var v=class extends d{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((a,l)=>{this.pendingResponses.set(r,{resolve:a,reject:l}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),l(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(a=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(a))}).catch(a=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:a.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};import{CronExpressionParser as x}from"cron-parser";var y=class extends d{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{x.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return x.parse(e,{currentDate:new Date}).next().toDate()}};var k=class extends d{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown"})});if(!t.ok)throw new Error(`Failed to send Telegram message: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.message||n.edited_message||{},i=t.text||"",s=t.chat||{},r=t.from||{},o=r.id!=null?String(r.id):void 0,a=r.first_name||r.username||o,l=o?{kind:"user",id:o,displayName:a??o}:void 0,m=t.entities??[],g=[];for(let w of m)if(w.type==="text_mention"&&w.user){let P=w.user;P.id!=null&&g.push(String(P.id))}let f=s.type,p=s.id!=null?String(s.id):"";return{message:i,conversationId:p,data:n,participant:l,context:{chatId:s.id,userId:r.id,username:r.username,firstName:r.first_name,lastName:r.last_name,messageId:t.message_id,channelType:f,channelId:p,channelName:s.title,mentions:g.length>0?g:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var M=new Set([1,3]),_=/<@!?(\d+)>/g,D="https://discord.com/api/v10",b=class extends d{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&M.has(s),o=n.author?.id,a=n.author?.globalName??n.author?.username,l=[];if(n.content){_.lastIndex=0;let m;for(;(m=_.exec(n.content))!==null;)l.push(m[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:a??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:l.length>0?l:void 0,isMentioned:this.botUserId?l.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${D}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var S=class extends d{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
|
|
1
|
+
var d=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};import{createHmac as N,timingSafeEqual as O}from"crypto";var b=class extends d{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,l=`v0=${N("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(l.length!==i.length)return!1;try{return O(Buffer.from(l),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,a=n.user,l=a?{kind:"user",id:a}:void 0,m=/<@([A-Z0-9]+)>/g,k=[],f;for(;(f=m.exec(i))!==null;)k.push(f[1]);let w=n.channel;return{message:i,conversationId:o?r:w||s||"",data:n,participant:l,context:{user:a,channel:w,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:k.length>0?k:void 0,channelId:w,channelName:typeof this.config.channel=="string"?this.config.channel:w}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let a={kind:"user",id:n};return this.participantCache.set(n,a),a}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let a=e.channel;if(!a||!this.allowedChannels.includes(a))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var S=class extends d{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((a,l)=>{this.pendingResponses.set(r,{resolve:a,reject:l}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),l(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(a=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(a))}).catch(a=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:a.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};import{CronExpressionParser as A}from"cron-parser";var I=class extends d{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{A.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return A.parse(e,{currentDate:new Date}).next().toDate()}};var T=class extends d{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=e.metadata?.replyMarkup,i=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown",...t?{reply_markup:t}:{}})});if(!i.ok)throw new Error(`Failed to send Telegram message: ${i.statusText}`);let s=await i.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,n){let t=await fetch(`https://api.telegram.org/bot${this.config.token}/answerCallbackQuery`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callback_query_id:e,...n?{text:n}:{}})});if(!t.ok)throw new Error(`Failed to answer Telegram callback query: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.callback_query;if(t){let C=t.message||{},g=C.chat||{},p=t.from||{},v=p.id!=null?String(p.id):void 0,E=p.first_name||p.username||v,R=v?{kind:"user",id:v,displayName:E??v}:void 0,M=g.id!=null?String(g.id):"";return{message:t.data??"",conversationId:M,data:n,participant:R,context:{isCallback:!0,callbackQueryId:t.id,callbackData:t.data,chatId:g.id,userId:p.id,username:p.username,firstName:p.first_name,lastName:p.last_name,messageId:C.message_id,channelType:g.type,channelId:M,channelName:g.title}}}let i=n.message||n.edited_message||{},s=i.text||"",r=i.chat||{},o=i.from||{},a=o.id!=null?String(o.id):void 0,l=o.first_name||o.username||a,m=a?{kind:"user",id:a,displayName:l??a}:void 0,k=i.entities??[],f=[];for(let C of k)if(C.type==="text_mention"&&C.user){let g=C.user;g.id!=null&&f.push(String(g.id))}let w=r.type,y=r.id!=null?String(r.id):"";return{message:s,conversationId:y,data:n,participant:m,context:{chatId:r.id,userId:o.id,username:o.username,firstName:o.first_name,lastName:o.last_name,messageId:i.message_id,channelType:w,channelId:y,channelName:r.title,mentions:f.length>0?f:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var U=new Set([1,3]),D=/<@!?(\d+)>/g,B="https://discord.com/api/v10",P=class extends d{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&U.has(s),o=n.author?.id,a=n.author?.globalName??n.author?.username,l=[];if(n.content){D.lastIndex=0;let m;for(;(m=D.exec(n.content))!==null;)l.push(m[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:a??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:l.length>0?l:void 0,isMentioned:this.botUserId?l.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${B}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var _=class extends d{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
|
|
2
2
|
|
|
3
|
-
`).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var
|
|
3
|
+
`).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var x=class extends d{config;twilioClient;server;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name}get isTriggerChannel(){return!this.config.webhookPath}listen(){typeof process<"u"&&import("twilio").then(e=>{this.twilioClient=e.default(this.config.accountSid,this.config.authToken),console.log("[SMSChannel] Twilio client initialized"),this.config.webhookPath&&this.startWebhookServer()}).catch(e=>{console.error("[SMSChannel] Failed to initialize Twilio client:",e),console.error("[SMSChannel] Make sure to install twilio: npm install twilio")})}async send(e){if(!this.twilioClient)throw new Error("Twilio client not initialized. Did you call listen()?");let n=e.metadata?.from||this.config.to;if(!n)throw new Error('No recipient phone number specified. Set "to" in config or provide in output.metadata.from');try{await this.twilioClient.messages.create({body:e.output,from:this.config.from,to:n})}catch(t){throw console.error("[SMSChannel] Failed to send SMS:",t),new Error(`Failed to send SMS: ${t instanceof Error?t.message:String(t)}`)}}normalize(e){let n=e,t=n.From,i=n.Body,s=n.MessageSid;return{message:i,conversationId:t,data:n,context:{from:t,to:n.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleWebhookRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SMSChannel] Webhook server listening on port ${this.config.port} at ${this.config.webhookPath}`)})}).catch(e=>{console.error("[SMSChannel] Failed to start webhook server:",e)})}handleWebhookRequest(e,n){if(e.method!=="POST"||e.url!==this.config.webhookPath){n.writeHead(404),n.end("Not found");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=new URLSearchParams(t),s={};i.forEach((o,a)=>{s[a]=o});let r=this.normalize(s);this.handleMessage(r),n.writeHead(200,{"Content-Type":"text/xml"}),n.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(i){console.error("[SMSChannel] Error handling webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var $=class extends d{isTriggerChannel=!1;_timeout;_pendingResolve;constructor(e={}){super(),this._timeout=e.timeout??12e4}listen(){}async send(e){this._pendingResolve?.(e),this._pendingResolve=void 0}normalize(e){let n=e;return{message:typeof n.message=="string"?n.message:JSON.stringify(n),data:n,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let n=this.normalize(e);return new Promise((t,i)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,i(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=r=>{clearTimeout(s),t(r.output)},this.handleMessage(n).catch(r=>{clearTimeout(s),this._pendingResolve=void 0,i(r instanceof Error?r:new Error(String(r)))})})}asAgentDefinition(e,n){return{name:e.name,description:e.description,...n!==void 0&&{inputSchema:n},invoke:t=>this.trigger(t)}}};export{d as BaseChannel,P as DiscordChannel,_ as EmailChannel,$ as McpChannel,x as SMSChannel,I as ScheduledChannel,b as SlackChannel,T as TelegramChannel,S as WebhookChannel};
|
|
@@ -629,9 +629,19 @@ declare class TelegramChannel extends BaseChannel {
|
|
|
629
629
|
private runStartupCheck;
|
|
630
630
|
/**
|
|
631
631
|
* Send a message back to Telegram.
|
|
632
|
-
* @param output The agent output to send
|
|
632
|
+
* @param output The agent output to send. Pass `metadata.replyMarkup` (a Telegram
|
|
633
|
+
* `InlineKeyboardMarkup`-shaped object, e.g. `{ inline_keyboard: [[{ text, callback_data }]] }`)
|
|
634
|
+
* to attach interactive buttons — optional, existing callers are unaffected.
|
|
633
635
|
*/
|
|
634
636
|
send(output: AgentOutput): Promise<void>;
|
|
637
|
+
/**
|
|
638
|
+
* Answer a callback query (inline keyboard button tap) so Telegram dismisses
|
|
639
|
+
* the button's loading spinner. Not called automatically by `normalize()` —
|
|
640
|
+
* the consuming agent should call this after it has handled the tap.
|
|
641
|
+
* @param callbackQueryId `callback_query.id` from the normalized update's context
|
|
642
|
+
* @param text Optional short toast text shown to the user
|
|
643
|
+
*/
|
|
644
|
+
answerCallbackQuery(callbackQueryId: string, text?: string): Promise<void>;
|
|
635
645
|
/**
|
|
636
646
|
* Normalize a Telegram update into AgentInput.
|
|
637
647
|
* @param incoming Telegram update object
|
|
@@ -629,9 +629,19 @@ declare class TelegramChannel extends BaseChannel {
|
|
|
629
629
|
private runStartupCheck;
|
|
630
630
|
/**
|
|
631
631
|
* Send a message back to Telegram.
|
|
632
|
-
* @param output The agent output to send
|
|
632
|
+
* @param output The agent output to send. Pass `metadata.replyMarkup` (a Telegram
|
|
633
|
+
* `InlineKeyboardMarkup`-shaped object, e.g. `{ inline_keyboard: [[{ text, callback_data }]] }`)
|
|
634
|
+
* to attach interactive buttons — optional, existing callers are unaffected.
|
|
633
635
|
*/
|
|
634
636
|
send(output: AgentOutput): Promise<void>;
|
|
637
|
+
/**
|
|
638
|
+
* Answer a callback query (inline keyboard button tap) so Telegram dismisses
|
|
639
|
+
* the button's loading spinner. Not called automatically by `normalize()` —
|
|
640
|
+
* the consuming agent should call this after it has handled the tap.
|
|
641
|
+
* @param callbackQueryId `callback_query.id` from the normalized update's context
|
|
642
|
+
* @param text Optional short toast text shown to the user
|
|
643
|
+
*/
|
|
644
|
+
answerCallbackQuery(callbackQueryId: string, text?: string): Promise<void>;
|
|
635
645
|
/**
|
|
636
646
|
* Normalize a Telegram update into AgentInput.
|
|
637
647
|
* @param incoming Telegram update object
|