@toolpack-sdk/agents 2.0.0-alpha.1 → 2.1.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.
@@ -1,17 +1,22 @@
1
- import{EventEmitter as Z}from"events";import{Toolpack as X,InMemoryConversationStore as ee}from"toolpack-sdk";var b=Symbol("interceptor-skip-sentinel");function L(i){return i===b}function j(){return b}var T=class extends Error{constructor(t,e){super(`Invocation depth ${t} exceeds maximum ${e}`),this.name="InvocationDepthExceededError"}};function U(i,t,e,n,r={}){let o=r.maxInvocationDepth??5;return{async execute(s){let l=(u=>({agent:t,channel:e,registry:n,invocationDepth:u,delegateAndWait:async(p,m)=>{let d=u+1;if(d>o)throw new T(d,o);if(!n)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let y=n.getAgent(p);if(!y)throw new Error(`Agent "${p}" not found for delegation`);let g={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await y.invokeAgent(g)},skip:j}))(0),c=async u=>{let p=u??s;return await t.invokeAgent(p)};for(let u=i.length-1;u>=0;u--){let p=i[u],m=c;c=async d=>await p(d??s,l,m)}return await c()}}}async function H(i,t){let e=await i.execute(t);return e===b?null:e}import{randomUUID as W}from"crypto";function J(i){let t=i.context??{},e=t.channelType;return e==="im"||e==="private"||e==="dm"?"dm":t.threadId!==void 0?"thread":"channel"}var P=Symbol.for("toolpack:capture-history");function B(i){let t=i.captureAgentReplies??!0,e=i.getScope??J,n=i.getMessageId??(s=>s.context?.messageId??s.context?.eventId??W()),r=i.getMentions??(s=>s.context?.mentions??[]),o=async(s,a,l)=>{let c=s.conversationId;if(!c)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await l();let u=s.participant;if(u){let m={id:n(s),conversationId:c,participant:u,content:s.message??"",timestamp:new Date().toISOString(),scope:e(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:r(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await i.store.append(m),i.onCaptured?.(m),a.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:u.id,conversationId:c})}catch(d){a.logger?.warn("[capture-history] Failed to store inbound message",{error:d instanceof Error?d.message:String(d)})}}let p=await l();if(t&&!L(p)&&p.output!=null){let m={kind:"agent",id:a.agent.name,displayName:a.agent.name},d={id:W(),conversationId:c,participant:m,content:p.output,timestamp:new Date().toISOString(),scope:e(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await i.store.append(d),i.onCaptured?.(d),a.logger?.debug("[capture-history] Captured agent reply",{messageId:d.id,agentId:a.agent.name,conversationId:c})}catch(y){a.logger?.warn("[capture-history] Failed to store agent reply",{error:y instanceof Error?y.message:String(y)})}}return p};return o[P]=!0,o}import{randomUUID as Y}from"crypto";function F(i){return Math.ceil(i.length/4)}function V(i){return{id:i.id,participant:i.participant,content:i.content,timestamp:i.timestamp}}function G(i,t){let{participant:e,content:n}=i;return e.kind==="system"?{role:"system",content:n}:e.kind==="agent"?e.id===t?{role:"assistant",content:n}:{role:"user",content:`${e.displayName??e.id} (agent): ${n}`}:{role:"user",content:`${e.displayName??e.id}: ${n}`}}function Q(i,t,e){return!!(i.participant.id===t||i.metadata?.mentions?.some(n=>e.has(n)))}async function q(i,t,e,n,r={},o){let{scope:s,addressedOnlyMode:a=!0,tokenBudget:l=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:u,maxTurnsToLoad:p=100,agentAliases:m}=r,d=new Set([e,...m??[]]),y=u!==void 0?new Date(Date.now()-u*60*1e3).toISOString():void 0,g=await i.get(t,{scope:s,sinceTimestamp:y,limit:p}),E=g.length;if(a){let h=new Set;for(let f=0;f<g.length;f++){let x=g[f];if(Q(x,e,d)&&h.add(x.id),f<g.length-1){let A=g[f+1];A.participant.kind==="agent"&&A.participant.id===e&&h.add(x.id)}}let v=g[g.length-1];v&&h.add(v.id),g=g.filter(f=>h.has(f.id))}let R=!1;if(g.length>c&&o){let h=Math.floor(g.length/2),v=g.slice(0,h),f=g.slice(h),x=v.filter(A=>!A.metadata?.isSummary);try{let A=await o.invokeAgent({message:"summarize",data:{turns:x.map(V),agentName:n,agentId:e,maxTokens:Math.floor(l*.25),extractDecisions:!0}}),D=JSON.parse(A.output),z={id:`summary-${Y()}`,conversationId:t,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${D.turnsSummarized} earlier turns]: ${D.summary}`,timestamp:v[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};g=[z,...f],R=!0;try{await i.append(z),await i.deleteMessages(t,v.map(K=>K.id))}catch{}}catch{g=g.slice(-c)}}else g.length>c&&(g=g.slice(-c));let S=g.map(h=>G(h,e));if(S.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:E,hasSummary:R};let O=S[S.length-1],$=[O],_=F(O.content);for(let h=S.length-2;h>=0;h--){let v=S[h],f=F(v.content);if(_+f>l)break;$.unshift(v),_+=f}return{messages:$,estimatedTokens:_,turnsLoaded:E,hasSummary:R}}var I=class extends Error{constructor(t){super(t),this.name="AgentError"}};var C=class extends Z{provider;model;workflow;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;constructor(t){super(),this.conversationHistory=new ee,"toolpack"in t?this.toolpack=t.toolpack:this._initConfig=t}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await X.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let t of this.channels)this._bindChannel(t),t.listen()}async stop(){for(let t of this.channels)"stop"in t&&typeof t.stop=="function"&&await t.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(t,e,n){let r=n?.conversationId??this._conversationId;await this.onBeforeRun({message:t,conversationId:r}),this.emit("agent:start",{message:t});try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let o=[];if(r)try{let c=await q(this.conversationHistory,r,this.name,this.name,this._resolveAssemblerOptions()),u=c.messages[c.messages.length-1],p=t.trim(),d=p!==""&&u?.role==="user"&&typeof u.content=="string"&&(u.content===p||u.content.endsWith(`: ${p}`))?c.messages.slice(0,-1):c.messages;o.push(...d)}catch{}t.trim()&&o.push({role:"user",content:t});let s=[];if(r){let c=this.conversationHistory;s.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async u=>{let p=await c.search(r,String(u.query??""),{limit:typeof u.limit=="number"?u.limit:5});return{results:p.map(m=>({role:m.participant.kind==="agent"?"assistant":"user",content:m.content,timestamp:m.timestamp})),count:p.length}}})}let a=await this.toolpack.generate({messages:o,model:this.model||"",requestTools:s.length>0?s:void 0},this.provider),l={output:a.content||"",steps:this.extractSteps(a),metadata:a.usage?{usage:a.usage}:void 0};return await this.onComplete(l),this.emit("agent:complete",l),l}catch(o){throw await this.onError(o),this.emit("agent:error",o),o}}getAgentAliases(){let t=[];for(let e of this.channels){let n=e.botUserId;n&&t.push(n)}return t}async sendTo(t,e){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(t,{output:e})}async ask(t,e){if(!this._registry)throw new I("Agent not registered - cannot use ask()");if(!this._conversationId)throw new I("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new I("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new I("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let n=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:t,context:e?.context??{},maxRetries:e?.maxRetries??2,expiresAt:e?.expiresIn?new Date(Date.now()+e.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,t),{output:t,metadata:{waitingForHuman:!0,askId:n.id}}}getPendingAsk(t){if(!this._registry)return null;let e=t??this._conversationId;return e?this._registry.getPendingAsk(e)??null:null}async resolvePendingAsk(t,e){if(!this._registry)throw new I("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(t,e)}async evaluateAnswer(t,e,n){return n?.simpleValidation?n.simpleValidation(e):(await this.run(`Evaluate if this answer sufficiently addresses the question.
1
+ var we=Object.defineProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var ve=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})};import it from"path";import{fileURLToPath as ot}from"url";var y=_(()=>{"use strict"});import{randomUUID as $}from"crypto";var L,U,q,j,z,a,B,ae=_(()=>{"use strict";y();L=.6,U=.2,q=.2,j={low:.3,medium:.6,high:1},z=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},B=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},o=n[t.priority]-n[i.priority];return o!==0?o:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let o=this.chunkToBelief(n),s=(t-o.createdAt)/864e5,p=Math.exp(-s/z)*U+j.high*q+L;return{...o,score:p}}).sort((n,o)=>o.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(o=>o[a.type]==="reflection"&&!o[a.pinned]&&!o[a.error]&&o[a.createdAt]>=i)).map(o=>this.chunkToReflection(o)).sort((o,s)=>s.createdAt-o.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:o}=t,s;if(e.trim()&&typeof this.provider.keywordQuery=="function")s=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(p=>this.chunkToGoal(p.chunk));else{let u=n;if(s=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();s=s.filter(d=>d.description.toLowerCase().includes(c))}}return o?.length&&(s=s.filter(u=>o.every(p=>u.tags.includes(p)))),s.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:o,includeExpired:s=!1}=t,u=Date.now(),p=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of p){let l=this.chunkToBelief(d.chunk);if(!s&&l.expiresAt&&l.expiresAt<u||o?.length&&!o.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,g=Math.exp(-m/z),h=l.error?.3:j[l.confidence],f=d.score*L+g*U+h*q;f<n||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:o,pinned:s}=t,u=Date.now(),p={[a.type]:"reflection"};s===!0&&(p[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:p}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(s===!1&&m.pinned||o?.length&&!o.every(w=>m.tags.includes(w)))continue;let g=(u-m.createdAt)/864e5,h=Math.exp(-g/z),f=l.score*L+h*U+j.medium*q;f<n||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let o of n){let s=this.chunkToBelief(o.chunk);if(!(s.expiresAt&&s.expiresAt<i))return{id:o.chunk.id,score:o.score,belief:s}}return null}async addGoal(e){let t=$();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),o={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(o)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=$();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let o=this.chunkToBelief(n),s={...o,content:t.content??o.content,confidence:t.confidence??o.confidence,tags:t.tags??o.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:o.expiresAt,error:t.error??o.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(s,u)])}async addReflection(e,t){let i=$();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),o={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(o,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function F(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function ce(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=F(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function de(r,e){let t=0,i=0,n=0;for(let s=0;s<r.length;s++)t+=r[s]*e[s],i+=r[s]*r[s],n+=e[s]*e[s];let o=Math.sqrt(i)*Math.sqrt(n);return o===0?0:t/o}function H(r){return Math.ceil(r.length/4)}var W=_(()=>{"use strict";y()});import{randomUUID as Ce}from"crypto";var E,le=_(()=>{"use strict";y();W();E=class{constructor(e,t,i,n,o,s){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=o;this.committedPinnedReflectionCount=s}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,o=e.expiresIn??e.ttlDefault;o&&(n=t+F(o));let s=this._findSimilarInDraft(i);if(s!==null){let c=this.ops[s],d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l];return this.ops[s]={...c,content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${s}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l],h={op:"believe",content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let s=this.totalPinnedReflectionCount;if(s>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);s>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${s+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},o=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:o,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?ce(e.dueBy):void 0,i={op:"set_goal",tempId:Ce(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let o=i;if(o.vector.length===0)continue;if(de(e,o.vector)>=this.deduplicationThreshold)return n}return null}}});function ue(r,e,t){return[xe(r,t),_e(r,e,t),Me(e,t),Se(e),Te(e,t),De(r,e),Pe(r)]}function xe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",o=t.status??"active",s=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,p=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:o,tags:s});for(let f of h)l.push(Be(f))}if(g&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(g,{limit:d,threshold:c,tags:s,includeExpired:p});for(let f of h)l.push(Ee(f))}if(g&&(n==="reflection"||n==="all")){let h=await r.queryReflections(g,{limit:d,threshold:c,tags:s,pinned:u});for(let f of h)l.push(Ne(f))}return l}}}function _e(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Me(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function Se(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function Te(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function De(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function Pe(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Be(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function Ee(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function Ne(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var pe=_(()=>{"use strict";y()});async function me(r,e){let[t,i,n,o]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),s=t.map(l=>Ge(l)),u=i.map(l=>`- ${l.content}`),{beliefLines:p,reflectionLines:c}=Oe(n,o,e.tokenBudget);if(s.length===0&&u.length===0&&p.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return s.length>0&&(d.push("## Goals"),d.push(...s),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),p.length>0&&(d.push("## Beliefs"),d.push(...p),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
+ `)}function Ge(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function Oe(r,e,t){let i=t,n=[],o=[];for(let s of r){let u=`- ${s.content} (${s.confidence} confidence)`,p=H(u);if(p>i)break;n.push(u),i-=p}for(let s of e){let p=`- [${new Date(s.createdAt).toISOString().slice(0,10)}] ${s.content}`,c=H(p);if(c>i)break;o.push(p),i-=c}return{beliefLines:n,reflectionLines:o}}var ge=_(()=>{"use strict";y();W()});var fe={};ve(fe,{AgentMind:()=>K});function Ke(r,e){let t=Math.min(e.maxGoals??Ue,He),i=Math.min(e.maxPinnedReflections??qe,We);return{tokenBudget:e.tokenBudget??$e,recencyWindowDays:e.recencyWindowDays??Le,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??je,retrievalThreshold:e.retrievalThreshold??ze,ttlDefaults:{belief:e.ttlDefaults?.belief??Fe,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var $e,Le,Ue,qe,je,ze,Fe,He,We,K,he=_(()=>{"use strict";y();ae();le();pe();ge();$e=300,Le=7,Ue=10,qe=10,je=.85,ze=.35,Fe="30d",He=10,We=10,K=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:s}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new s({namespace:u})}let n=Ke(e,t),o=new B(i,t.embedder);return await o.initialize(),new r(o,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),me(this.store,this.config)]),n=new E(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),o=ue(this.store,n,this.config);return{mindHeader:i,tools:o,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});y();y();y();import{EventEmitter as Ve}from"events";import{Toolpack as Je,InMemoryConversationStore as Ye}from"toolpack-sdk";y();y();var P=Symbol("interceptor-skip-sentinel");function Z(r){return r===P}function ee(){return P}var G=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function te(r,e,t,i,n={}){let o=n.maxInvocationDepth??5;return{async execute(s){let p=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>o)throw new G(g,o);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let h=i.getAgent(l);if(!h)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:ee}))(0),c=async d=>{let l=d??s;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??s,p,m)}return await c()}}}async function ne(r,e){let t=await r.execute(e);return t===P?null:t}y();import{randomUUID as ie}from"crypto";function Ae(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var O=Symbol.for("toolpack:capture-history");function re(r){let e=r.captureAgentReplies??!0,t=r.getScope??Ae,i=r.getMessageId??(s=>s.context?.messageId??s.context?.eventId??ie()),n=r.getMentions??(s=>s.context?.mentions??[]),o=async(s,u,p)=>{let c=s.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await p();let d=s.participant;if(d){let m={id:i(s),conversationId:c,participant:d,content:s.message??"",timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:n(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){u.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await p();if(e&&!Z(l)&&l.output!=null){let m={kind:"agent",id:u.agent.name,displayName:u.agent.name},g={id:ie(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return l};return o[O]=!0,o}y();import{randomUUID as be}from"crypto";function oe(r){return Math.ceil(r.length/4)}function ke(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Ie(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Re(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function se(r,e,t,i,n={},o){let{scope:s,addressedOnlyMode:u=!0,tokenBudget:p=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:s,sinceTimestamp:h,limit:l}),w=f.length;if(u){let b=new Set;for(let k=0;k<f.length;k++){let T=f[k];if(Re(T,t,g)&&b.add(T.id),k<f.length-1){let M=f[k+1];M.participant.kind==="agent"&&M.participant.id===t&&b.add(T.id)}}let C=f[f.length-1];C&&b.add(C.id),f=f.filter(k=>b.has(k.id))}let I=!1;if(f.length>c&&o){let b=Math.floor(f.length/2),C=f.slice(0,b),k=f.slice(b),T=C.filter(M=>!M.metadata?.isSummary);try{let M=await o.invokeAgent({message:"summarize",data:{turns:T.map(ke),agentName:i,agentId:t,maxTokens:Math.floor(p*.25),extractDecisions:!0}}),X=JSON.parse(M.output),Q={id:`summary-${be()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${X.turnsSummarized} earlier turns]: ${X.summary}`,timestamp:C[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};f=[Q,...k],I=!0;try{await r.append(Q),await r.deleteMessages(e,C.map(ye=>ye.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let R=f.map(b=>Ie(b,t));if(R.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:I};let D=R[R.length-1],Y=[D],N=oe(D.content);for(let b=R.length-2;b>=0;b--){let C=R[b],k=oe(C.content);if(N+k>p)break;Y.unshift(C),N+=k}return{messages:Y,estimatedTokens:N,turnsLoaded:w,hasSummary:I}}y();var x=class extends Error{constructor(e){super(e),this.name="AgentError"}};var S=class extends Ve{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Ye,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Je.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(he(),fe));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await se(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
3
+ `);this.delegation.mode==="forget"?c.push({name:"delegate_and_forget",displayName:"Delegate and Forget",description:`Hand off the current task to a peer agent. The agent will handle its own delivery (e.g. posting to Slack or GitHub) \u2014 you do not need to relay its response. Call this ONCE, then output an empty string.
2
4
 
3
- Question: "${t}"
4
- Answer: "${e}"
5
+ Available agents:
6
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}}).catch(D=>{console.error(`[${this.name}] delegate_and_forget to ${I} failed:`,D)}),{status:"delegated",agent:I}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
5
7
 
6
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(t,e,n,r){return await this.evaluateAnswer(t.question,e,{simpleValidation:s=>s.trim().length>3})?(await this.resolvePendingAsk(t.id,e),n(e)):t.retries>=t.maxRetries?(await this.resolvePendingAsk(t.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),r?r():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:t.id}}):(this._registry?.incrementRetries(t.id),this.ask(`I need a bit more clarity on: "${t.question}". Could you provide more details?`,{context:t.context,maxRetries:t.maxRetries}))}async delegate(t,e){if(!this._registry)throw new I("Agent not registered - cannot use delegate()");let n={message:e.message,intent:e.intent,data:e.data,context:{...e.context||{},delegatedBy:this.name},conversationId:e.conversationId||this._conversationId||`delegation-${Date.now()}`};this._registry.invoke(t,n).catch(r=>{console.error(`[${this.name}] Delegation to ${t} failed:`,r.message)})}async delegateAndWait(t,e){if(!this._registry)throw new I("Agent not registered - cannot use delegateAndWait()");let n={message:e.message,intent:e.intent,data:e.data,context:{...e.context||{},delegatedBy:this.name},conversationId:e.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(t,n)}async onBeforeRun(t){}async onStepComplete(t){}async onComplete(t){}async onError(t){}_resolveAssemblerOptions(){let t=this.channels.map(r=>r.botUserId).filter(r=>typeof r=="string"&&r.length>0),e=this.assemblerOptions?.agentAliases??[];if(t.length===0&&e.length===0)return this.assemblerOptions;let n=Array.from(new Set([...e,...t]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(e=>e[P]===!0)?this.interceptors:[B({store:this.conversationHistory}),...this.interceptors]}_bindChannel(t){t.onMessage(async e=>{if(!e.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let n=await this._acquireConversationLock(e.conversationId),r=()=>{};try{this._triggeringChannel=t.name,this._isTriggerChannel=t.isTriggerChannel,this._conversationId=e.conversationId,r=this._attachWorkflowStepUpdates(t,e);let o=U(this._getEffectiveInterceptors(),this,t,this._registry??null),s=await H(o,e);if(s===null)return;let a={output:s.output,metadata:s.metadata};await t.send({output:a.output,metadata:{...a.metadata,conversationId:e.conversationId,...e.context}})}catch(o){let s=o instanceof Error?o.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await t.send({output:`Error: ${s}`,metadata:{conversationId:e.conversationId,error:!0,...e.context}})}catch(a){console.error(`[${this.name}] Failed to send error to channel: ${a}`)}}finally{r(),n()}})}_attachWorkflowStepUpdates(t,e){if(t.isTriggerChannel)return()=>{};let n=new Set,r=new Set,o=a=>{a?.id&&n.add(String(a.id))},s=(a,l)=>{if(!l?.id||!n.has(String(l.id))||!a?.result?.output||typeof a.result.output!="string"||l?.steps?.length&&Number(l.steps.length)<=1)return;let c=`${String(l.id)}:${String(a.id??a.number??"unknown")}`;if(r.has(c))return;r.add(c);let u=a.result.output.trim();if(!u)return;let p=u.length>3500?`${u.slice(0,3500)}
7
- ... [truncated]`:u,m=`Step ${a.number}: ${a.description||"Completed"}`;t.send({output:`${m}
8
+ Available agents:
9
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}})}})}}let d=await this.toolpack.generate({messages:p,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds},this.provider),l={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(l),o&&await o(!1),this.emit("agent:complete",l),l}catch(p){throw o&&o(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(p),this.emit("agent:error",p),p}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new x("Agent not registered - cannot use ask()");if(!this._conversationId)throw new x("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new x("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new x("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new x("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
8
10
 
9
- ${p}`,metadata:{conversationId:e.conversationId,...e.context}}).catch(d=>{let y=d instanceof Error?d.message:String(d);console.warn(`[${this.name}] Failed to send workflow step update: ${y}`)})};return this.toolpack.on("workflow:plan_created",o),this.toolpack.on("workflow:step_complete",s),()=>{this.toolpack.off("workflow:plan_created",o),this.toolpack.off("workflow:step_complete",s)}}async _acquireConversationLock(t){for(;this._conversationLocks.has(t);)try{await this._conversationLocks.get(t)}catch{}let e,n=new Promise(r=>{e=r});return this._conversationLocks.set(t,n),()=>{this._conversationLocks.delete(t),e()}}extractSteps(t){let e=t;if(e.plan&&typeof e.plan=="object"){let n=e.plan;if(Array.isArray(n.steps))return n.steps.map(r=>({number:r.number||0,description:r.description||"",status:r.status||"completed",result:r.result}))}if(Array.isArray(e.steps))return e.steps}};import{CHAT_MODE as te}from"toolpack-sdk";var ne={...te,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
10
- `)},M=class extends C{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=ne;constructor(t){super(t)}async invokeAgent(t){let e=t.data;if(e?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!e?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let n=[];if(n.push(`Context: Public channel #${e.channelName}`),n.push(`Target agent: "${e.agentName}" (ID: ${e.agentId})`),n.push(`Message sender: ${e.senderName}`),e.recentContext&&e.recentContext.length>0){n.push(`
11
- Recent conversation:`);for(let a of e.recentContext)n.push(` ${a.sender}: ${a.content.substring(0,100)}`)}n.push(`
12
- Message to classify: "${e.message}"`),e.includeExamples&&(n.push(`
13
- Examples of classifications:`),n.push(` "@${e.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${e.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${e.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
14
- Classification (start with direct, indirect, passive, or ignore):`);let r=n.join(`
15
- `),o=await this.run(r),s=this.normalizeClassification(o.output);return{output:s,metadata:{rawOutput:o.output,classification:s,confidence:"high"}}}normalizeClassification(t){let e=t.toLowerCase().trim().split(/\s+/)[0],n=t.toLowerCase();return["direct","indirect","passive","ignore"].includes(e)?e:n.includes("indirect")||n.includes("mention")?"indirect":n.includes("passive")||n.includes("listen")?"passive":n.includes("ignore")||n.includes("skip")?"ignore":n.includes("direct")||n.includes("addressed")?"direct":"ignore"}};import{CHAT_MODE as se}from"toolpack-sdk";var re={...se,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
16
- `)},N=class extends C{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=re;constructor(t){super(t)}async invokeAgent(t){let e=t.data;if(!e?.turns||e.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let n=e.maxTokens??800,r=e.extractDecisions??!0,o=[`Target agent: "${e.agentName}" (ID: ${e.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${r?"yes":"no"}`,"",`Conversation turns to summarize (${e.turns.length} turns):`,""];for(let c of e.turns){let u=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${p}`:p,d=`[${u}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(d+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(d+=` [tool: ${c.metadata.toolName}]`),o.push(d)}o.push("","Generate a JSON summary object:");let s=o.join(`
17
- `),a=await this.run(s),l=this.parseSummarizerOutput(a.output,e.turns.length);return{output:JSON.stringify(l),metadata:{turnsProcessed:e.turns.length,rawOutputLength:a.output.length}}}parseSummarizerOutput(t,e){let n=t.trim(),r=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);r&&(n=r[1].trim());try{let o=JSON.parse(n);return{summary:typeof o.summary=="string"&&o.summary.length>0?o.summary:this.generateFallbackSummary(e),turnsSummarized:typeof o.turnsSummarized=="number"?o.turnsSummarized:e,hasDecisions:typeof o.hasDecisions=="boolean"?o.hasDecisions:!1,estimatedTokens:typeof o.estimatedTokens=="number"&&o.estimatedTokens>0?o.estimatedTokens:Math.ceil(t.length/4)}}catch{return{summary:this.generateFallbackSummary(e),turnsSummarized:e,hasDecisions:t.toLowerCase().includes("decision")||t.toLowerCase().includes("action"),estimatedTokens:Math.ceil(t.length/4)}}}generateFallbackSummary(t){return`(Summary of ${t} conversation turns - key details preserved in full context)`}};export{M as IntentClassifierAgent,N as SummarizerAgent};
11
+ Question: "${e}"
12
+ Answer: "${t}"
13
+
14
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:s=>s.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new x("Agent not registered - cannot use delegateAndWait()");let i={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,i)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(n=>n.botUserId).filter(n=>typeof n=="string"&&n.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let i=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:i}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[O]===!0)?this.interceptors:[re({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let i=await this._acquireConversationLock(t.conversationId);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let n=te(this._getEffectiveInterceptors(),this,e,this._registry??null),o=await ne(n,t);if(o===null)return;let s={output:o.output,metadata:o.metadata};await e.send({output:s.output,metadata:{...s.metadata,conversationId:t.conversationId,...t.context}})}catch(n){let o=n instanceof Error?n.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${o}`);try{await e.send({output:`Error: ${o}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(s){console.error(`[${this.name}] Failed to send error to channel: ${s}`)}}finally{i()}})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,i=new Promise(n=>{t=n});return this._conversationLocks.set(e,i),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let i=t.plan;if(Array.isArray(i.steps))return i.steps.map(n=>({number:n.number||0,description:n.description||"",status:n.status||"completed",result:n.result}))}if(Array.isArray(t.steps))return t.steps}};import{CHAT_MODE as Xe}from"toolpack-sdk";var Qe={...Xe,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
15
+ `)},V=class extends S{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=Qe;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let i=[];if(i.push(`Context: Public channel #${t.channelName}`),i.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),i.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){i.push(`
16
+ Recent conversation:`);for(let u of t.recentContext)i.push(` ${u.sender}: ${u.content.substring(0,100)}`)}i.push(`
17
+ Message to classify: "${t.message}"`),t.includeExamples&&(i.push(`
18
+ Examples of classifications:`),i.push(` "@${t.agentName} help me" \u2192 direct`),i.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),i.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),i.push(' "Check the logs" \u2192 ignore')),i.push(`
19
+ Classification (start with direct, indirect, passive, or ignore):`);let n=i.join(`
20
+ `),o=await this.run(n),s=this.normalizeClassification(o.output);return{output:s,metadata:{rawOutput:o.output,classification:s,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();import{CHAT_MODE as Ze}from"toolpack-sdk";var et={...Ze,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
21
+ `)},J=class extends S{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=et;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let i=t.maxTokens??800,n=t.extractDecisions??!0,o=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${i} tokens`,`Extract decisions/action items: ${n?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let c of t.turns){let d=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),l=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${l}`:l,g=`[${d}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(g+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(g+=` [tool: ${c.metadata.toolName}]`),o.push(g)}o.push("","Generate a JSON summary object:");let s=o.join(`
22
+ `),u=await this.run(s),p=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(p),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let i=e.trim(),n=i.match(/```(?:json)?\s*([\s\S]*?)\s*```/);n&&(i=n[1].trim());try{let o=JSON.parse(i);return{summary:typeof o.summary=="string"&&o.summary.length>0?o.summary:this.generateFallbackSummary(t),turnsSummarized:typeof o.turnsSummarized=="number"?o.turnsSummarized:t,hasDecisions:typeof o.hasDecisions=="boolean"?o.hasDecisions:!1,estimatedTokens:typeof o.estimatedTokens=="number"&&o.estimatedTokens>0?o.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};export{V as IntentClassifierAgent,J as SummarizerAgent};
@@ -1,3 +1,3 @@
1
- "use strict";var A=Object.create;var m=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var _=(a,n)=>{for(var e in n)m(a,e,{get:n[e],enumerable:!0})},$=(a,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of R(n))!N.call(a,o)&&o!==e&&m(a,o,{get:()=>n[o],enumerable:!(t=M(n,o))||t.enumerable});return a};var g=(a,n,e)=>(e=a!=null?A(O(a)):{},$(n||!a||!a.__esModule?m(e,"default",{value:a,enumerable:!0}):e,a)),D=a=>$(m({},"__esModule",{value:!0}),a);var B={};_(B,{BaseChannel:()=>l,DiscordChannel:()=>S,EmailChannel:()=>b,SMSChannel:()=>I,ScheduledChannel:()=>k,SlackChannel:()=>w,TelegramChannel:()=>v,WebhookChannel:()=>y});module.exports=D(B);var l=class{name;_handler;onMessage(n){this._handler=n}async handleMessage(n){this._handler&&await this._handler(n)}};var C=require("crypto");var w=class extends l{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;allowedChannels;constructor(n){super(),this.config={port:3e3,...n},this.name=n.name;let e=n.channel;this.allowedChannels=e==null?null:Array.isArray(e)?e:[e]}listen(){typeof process<"u"&&import("http").then(n=>{this.server=n.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(n=>{console.error("[SlackChannel] Failed to start HTTP server:",n)})}async runStartupCheck(){try{let e=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();e.ok?(this.botUserId=e.user_id,console.log(`[SlackChannel] Connected as @${e.user} (${e.user_id}) in workspace "${e.team}" \u2014 ${e.url}`)):console.warn(`[SlackChannel] auth.test failed: ${e.error}. Check your bot token.`)}catch(n){console.warn("[SlackChannel] Startup self-check failed (network error):",n)}}verifySignature(n,e){let t=n["x-slack-request-timestamp"],o=n["x-slack-signature"];if(!t||!o||Array.isArray(t)||Array.isArray(o))return!1;let r=parseInt(t,10),i=Math.floor(Date.now()/1e3);if(isNaN(r)||Math.abs(i-r)>300)return!1;let s=`v0:${t}:${e}`,c=`v0=${(0,C.createHmac)("sha256",this.config.signingSecret).update(s).digest("hex")}`;if(c.length!==o.length)return!1;try{return(0,C.timingSafeEqual)(Buffer.from(c),Buffer.from(o))}catch{return!1}}async send(n){let e=n.metadata?.threadTs??n.metadata?.thread_ts??n.metadata?.threadId,o=n.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!o)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 r={channel:o,text:n.output};e&&(r.thread_ts=e);let i=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new Error(`Failed to send Slack message: ${i.statusText}`);let s=await i.json();if(!s.ok)throw new Error(`Slack API error: ${s.error}`)}normalize(n){let e=n,t=e.text||"",o=e.ts,r=e.thread_ts,i=r!==void 0&&r!==o,s=e.user,d=s?{kind:"user",id:s}:void 0,c=/<@([A-Z0-9]+)>/g,f=[],u;for(;(u=c.exec(t))!==null;)f.push(u[1]);let p=e.channel;return{message:t,conversationId:i?r:p||o||"",data:e,participant:d,context:{user:s,channel:p,team:e.team,channelType:e.channel_type,threadId:i?r:void 0,mentions:f.length>0?f:void 0,channelId:p,channelName:typeof this.config.channel=="string"?this.config.channel:p}}}async resolveParticipant(n){let e=n.participant?.id??n.context?.user;if(!e)return;let t=this.participantCache.get(e);if(t)return t;try{let o=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!o.ok)return{kind:"user",id:e};let r=await o.json();if(!r.ok||!r.user){let d={kind:"user",id:e};return this.participantCache.set(e,d),d}let i=r.user.profile?.display_name||r.user.profile?.real_name||r.user.real_name||r.user.name||e,s={kind:"user",id:e,displayName:i,metadata:{slackUser:r.user}};return this.participantCache.set(e,s),s}catch{return{kind:"user",id:e}}}invalidateParticipant(n){this.participantCache.delete(n)}shouldProcessEvent(n){let e=n.type;if(e!=="message"&&e!=="app_mention")return!1;if(this.allowedChannels!==null){let i=n.channel_type;if(!(i==="im"||i==="mpim")){let d=n.channel;if(!d||!this.allowedChannels.includes(d))return!1}}let t=n.user;if(this.botUserId&&t===this.botUserId)return!1;let o=n.bot_id;if(!o)return!0;let r=this.config.blockedBotIds??[];if(r.includes(o)||t!==void 0&&r.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let i=this.config.allowedBotIds;return i.includes(o)||t!==void 0&&i.includes(t)}return!0}handleRequest(n,e){if(n.method!=="POST"){e.writeHead(405),e.end("Method not allowed");return}let t="";n.on("data",o=>{t+=o.toString()}),n.on("end",()=>{if(!this.verifySignature(n.headers,t)){e.writeHead(401),e.end("Invalid signature");return}try{let o=JSON.parse(t);if(o.type==="url_verification"){e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({challenge:o.challenge}));return}if(o.type==="event_callback"&&o.event){let r=o.event;if(this.shouldProcessEvent(r)){let i=this.normalize(r);this.handleMessage(i)}else r.type==="user_change"&&r.user&&this.invalidateParticipant(r.user.id);e.writeHead(200),e.end("OK");return}e.writeHead(200),e.end("OK")}catch(o){console.error("[SlackChannel] Error handling request:",o),e.writeHead(400),e.end("Bad request")}})}async stop(){if(this.server)return new Promise(n=>{this.server.close(n)})}};var y=class extends l{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(n){super(),this.name=n.name,this.config={port:n.port??3e3,path:n.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(n=>{this.server=n.createServer((e,t)=>{this.handleRequest(e,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(n=>{console.error("[WebhookChannel] Failed to start HTTP server:",n)})}async send(n){let e=n.metadata?.conversationId;if(e&&this.pendingResponses.has(e)){let t=this.pendingResponses.get(e);this.pendingResponses.delete(e),t.resolve({output:n.output,metadata:n.metadata})}}normalize(n){let e=n,t=e.headers||{},o=t["x-session-id"]||t["X-Session-Id"]||e.sessionId||e.conversationId||this.generateSessionId();return{message:e.message||e.text||"",intent:e.intent,conversationId:o,data:e,context:{headers:e.headers,method:e.method,sessionId:o}}}handleRequest(n,e){if(n.url!==this.config.path){e.writeHead(404),e.end("Not found");return}if(n.method!=="POST"){e.writeHead(405),e.end("Method not allowed");return}let t="";n.on("data",o=>{t+=o.toString()}),n.on("end",()=>{try{let o=JSON.parse(t),r=this.normalize(o),i=r.conversationId||this.generateSessionId(),s=new Promise((d,c)=>{this.pendingResponses.set(i,{resolve:d,reject:c}),setTimeout(()=>{this.pendingResponses.has(i)&&(this.pendingResponses.delete(i),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...r,conversationId:i,context:{...r.context,sessionId:i}}),s.then(d=>{e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(d))}).catch(d=>{e.writeHead(500,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:d.message}))})}catch(o){console.error("[WebhookChannel] Error handling request:",o),e.writeHead(400,{"Content-Type":"application/json"}),e.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(n=>{this.server.close(n)})}};var P=require("cron-parser"),k=class extends l{isTriggerChannel=!0;config;timer;constructor(n){super(),this.config=n,this.name=n.name;try{P.CronExpressionParser.parse(n.cron)}catch(e){throw new Error(`Invalid cron expression '${n.cron}': ${e.message}`)}}listen(){this.scheduleNextRun()}async send(n){let e=this.config.notify.indexOf(":");if(e===-1)throw new Error(`Invalid notify format: ${this.config.notify}. Expected format: 'webhook:https://...'`);let t=this.config.notify.substring(0,e),o=this.config.notify.substring(e+1);if(!t||!o)throw new Error(`Invalid notify format: ${this.config.notify}. Expected format: 'webhook:https://...'`);switch(t.toLowerCase()){case"webhook":await this.sendToWebhook(o,n);break;case"slack":throw new Error("ScheduledChannel no longer supports the 'slack:' notify protocol. Attach a named SlackChannel to the agent and route from inside run() via this.sendTo('<channelName>', output). See ScheduledChannelConfig.notify docs.");default:throw new Error(`Unknown notify protocol: ${t}`)}}normalize(n){let e=new Date,t=`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`;return{intent:this.config.intent,message:`Scheduled task triggered at ${e.toISOString()}`,conversationId:`scheduled:${this.name||"default"}:${t}`,data:{scheduled:!0,cron:this.config.cron,timestamp:e.toISOString()}}}async sendToWebhook(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({output:e.output,metadata:e.metadata,timestamp:new Date().toISOString()})});if(!t.ok)throw new Error(`Webhook notification failed: ${t.statusText}`)}getNextRunTime(){return P.CronExpressionParser.parse(this.config.cron,{currentDate:new Date}).next().toDate()}scheduleNextRun(){let n=this.getNextRunTime(),e=n.getTime()-Date.now();if(e<=0){this.scheduleNextRun();return}console.log(`[ScheduledChannel] Next run scheduled for ${n.toISOString()}`),this.timer=setTimeout(()=>{this.trigger(),this.scheduleNextRun()},e)}async trigger(){let n=this.normalize(null);try{await this.handleMessage(n)}catch(e){console.error("[ScheduledChannel] Error triggering scheduled task:",e)}}async stop(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var v=class extends l{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(n){super(),this.name=n.name,this.config=n}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let e=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(e.ok&&e.result){let t=e.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: ${e.description??"unknown error"}. Check your bot token.`)}catch(n){console.warn("[TelegramChannel] Startup self-check failed (network error):",n)}}async send(n){let e=n.metadata?.chatId;if(!e)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:e,text:n.output,parse_mode:"Markdown"})});if(!t.ok)throw new Error(`Failed to send Telegram message: ${t.statusText}`);let o=await t.json();if(!o.ok)throw new Error(`Telegram API error: ${o.description}`)}normalize(n){let e=n,t=e.message||e.edited_message||{},o=t.text||"",r=t.chat||{},i=t.from||{},s=i.id!=null?String(i.id):void 0,d=i.first_name||i.username||s,c=s?{kind:"user",id:s,displayName:d??s}:void 0,f=t.entities??[],u=[];for(let x of f)if(x.type==="text_mention"&&x.user){let E=x.user;E.id!=null&&u.push(String(E.id))}let p=r.type,T=r.id!=null?String(r.id):"";return{message:o,conversationId:T,data:e,participant:c,context:{chatId:r.id,userId:i.id,username:i.username,firstName:i.first_name,lastName:i.last_name,messageId:t.message_id,channelType:p,channelId:T,channelName:r.title,mentions:u.length>0?u:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(n){console.error("[TelegramChannel] Polling error:",n)}},5e3)}async pollUpdates(){let n=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,e=await fetch(n);if(!e.ok)throw new Error(`Telegram getUpdates failed: ${e.statusText}`);let t=await e.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let o of t.result){let r=o.update_id;r>=this.offset&&(this.offset=r+1);try{let i=this.normalize(o);await this.handleMessage(i)}catch(i){console.error("[TelegramChannel] Error processing update:",i)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(n=>{this.server=n.createServer((o,r)=>{this.handleWebhookRequest(o,r)});let e=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(e.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(n=>{console.error("[TelegramChannel] Failed to start webhook server:",n)}))}async setWebhook(){if(!this.config.webhookUrl)return;let n=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(!n.ok){console.error("[TelegramChannel] Failed to set webhook");return}let e=await n.json();e.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",e.description)}handleWebhookRequest(n,e){if(n.method!=="POST"){e.writeHead(405),e.end("Method not allowed");return}let t="";n.on("data",o=>{t+=o.toString()}),n.on("end",()=>{try{let o=JSON.parse(t);this.handleMessage(this.normalize(o)).catch(r=>{console.error("[TelegramChannel] Error processing webhook:",r)}),e.writeHead(200),e.end("OK")}catch(o){console.error("[TelegramChannel] Error parsing webhook:",o),e.writeHead(400),e.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(n=>{this.server.close(n)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(n){console.error("[TelegramChannel] Failed to delete webhook:",n)}}};var S=class extends l{isTriggerChannel=!1;config;client;constructor(n){super(),this.config=n,this.name=n.name}listen(){typeof process<"u"&&import("discord.js").then(n=>{let{Client:e,GatewayIntentBits:t}=n;this.client=new e({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{console.log(`[DiscordChannel] Bot logged in as ${this.client.user?.tag}`)}),this.client.on("messageCreate",o=>{this.handleDiscordMessage(o)}),this.client.login(this.config.token).catch(o=>{console.error("[DiscordChannel] Failed to login to Discord:",o)})}).catch(n=>{console.error("[DiscordChannel] Failed to initialize Discord client:",n),console.error("[DiscordChannel] Make sure to install discord.js: npm install discord.js")})}async send(n){if(!this.client)throw new Error("Discord client not initialized. Did you call listen()?");try{let e=n.metadata?.channelId||this.config.channelId,t=await this.client.channels.fetch(e);if(!t||!("send"in t))throw new Error(`Channel ${e} not found or is not a text channel`);let o={content:n.output},r=n.metadata?.threadId;if(r){let i=await this.client.channels.fetch(r);if(i&&"send"in i){await i.send(o);return}}await t.send(o)}catch(e){throw console.error("[DiscordChannel] Failed to send Discord message:",e),new Error(`Failed to send Discord message: ${e instanceof Error?e.message:String(e)}`)}}normalize(n){let e=n,t=e.channelId,o=(t??"")+(e.thread?.id?`:${e.thread.id}`:""),r=e.channel?.type,i=r===1||r===3,s=e.author?.id,d=e.author?.globalName||e.author?.username;return{message:e.content,conversationId:o,data:e,participant:s?{kind:"user",id:s,displayName:d}:void 0,context:{userId:s,username:e.author?.username,channelType:i?"dm":"channel",channelId:t,channelName:e.channel?.name,guildId:e.guildId,threadId:e.thread?.id,messageId:e.id}}}handleDiscordMessage(n){if(n.author?.bot||n.channelId!==this.config.channelId||n.guildId!==this.config.guildId)return;let e=this.normalize(n);this.handleMessage(e)}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var b=class extends l{isTriggerChannel=!0;config;transporter;constructor(n){super(),this.config=n,this.name=n.name}listen(){typeof process<"u"&&import("nodemailer").then(n=>{this.transporter=n.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(n=>{console.error("[EmailChannel] Failed to initialize nodemailer:",n),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(n){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let e=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",o={from:this.config.from,to:e.join(", "),subject:t,text:n.output,html:this.formatAsHtml(n.output)};try{let r=await this.transporter.sendMail(o);console.log(`[EmailChannel] Email sent: ${r.messageId}`)}catch(r){throw console.error("[EmailChannel] Failed to send email:",r),new Error(`Failed to send email: ${r instanceof Error?r.message:String(r)}`)}}normalize(n){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(n){return n.split(`
1
+ "use strict";var M=Object.create;var C=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var O=(a,e)=>{for(var n in e)C(a,n,{get:e[n],enumerable:!0})},_=(a,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of E(e))!N.call(a,r)&&r!==n&&C(a,r,{get:()=>e[r],enumerable:!(t=D(e,r))||t.enumerable});return a};var p=(a,e,n)=>(n=a!=null?M(R(a)):{},_(e||!a||!a.__esModule?C(n,"default",{value:a,enumerable:!0}):n,a)),U=a=>_(C({},"__esModule",{value:!0}),a);var z={};O(z,{BaseChannel:()=>d,DiscordChannel:()=>I,EmailChannel:()=>T,SMSChannel:()=>P,ScheduledChannel:()=>S,SlackChannel:()=>v,TelegramChannel:()=>b,WebhookChannel:()=>y});module.exports=U(z);var d=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};var k=require("crypto");var v=class extends d{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;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,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"],r=e["x-slack-signature"];if(!t||!r||Array.isArray(t)||Array.isArray(r))return!1;let i=parseInt(t,10),s=Math.floor(Date.now()/1e3);if(isNaN(i)||Math.abs(s-i)>300)return!1;let o=`v0:${t}:${n}`,c=`v0=${(0,k.createHmac)("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(c.length!==r.length)return!1;try{return(0,k.timingSafeEqual)(Buffer.from(c),Buffer.from(r))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,r=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!r)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 i={channel:r,text:e.output};n&&(i.thread_ts=n);let s=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!s.ok)throw new Error(`Failed to send Slack message: ${s.statusText}`);let o=await s.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,r=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),i=n.ts,s=n.thread_ts,o=s!==void 0&&s!==i,l=n.user,c=l?{kind:"user",id:l}:void 0,f=/<@([A-Z0-9]+)>/g,u=[],m;for(;(m=f.exec(r))!==null;)u.push(m[1]);let g=n.channel;return{message:r,conversationId:o?s:g||i||"",data:n,participant:c,context:{user:l,channel:g,team:n.team,channelType:n.channel_type,threadId:o?s: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 r=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!r.ok)return{kind:"user",id:n};let i=await r.json();if(!i.ok||!i.user){let l={kind:"user",id:n};return this.participantCache.set(n,l),l}let s=i.user.profile?.display_name||i.user.profile?.real_name||i.user.real_name||i.user.name||n,o={kind:"user",id:n,displayName:s,metadata:{slackUser:i.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 s=e.channel_type;if(!(s==="im"||s==="mpim")){let l=e.channel;if(!l||!this.allowedChannels.includes(l))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let r=e.bot_id;if(!r)return!0;let i=this.config.blockedBotIds??[];if(i.includes(r)||t!==void 0&&i.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let s=this.config.allowedBotIds;return s.includes(r)||t!==void 0&&s.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",r=>{t+=r.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let r=JSON.parse(t);if(r.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:r.challenge}));return}if(r.type==="event_callback"&&r.event){let i=r.event;if(this.shouldProcessEvent(i)){let s=this.normalize(i);this.handleMessage(s)}else i.type==="user_change"&&i.user&&this.invalidateParticipant(i.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(r){console.error("[SlackChannel] Error handling request:",r),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var y=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||{},r=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:r,data:n,context:{headers:n.headers,method:n.method,sessionId:r}}}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",r=>{t+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(t),i=this.normalize(r),s=i.conversationId||this.generateSessionId(),o=new Promise((l,c)=>{this.pendingResponses.set(s,{resolve:l,reject:c}),setTimeout(()=>{this.pendingResponses.has(s)&&(this.pendingResponses.delete(s),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...i,conversationId:s,context:{...i.context,sessionId:s}}),o.then(l=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(l))}).catch(l=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:l.message}))})}catch(r){console.error("[WebhookChannel] Error handling request:",r),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 x=require("cron-parser"),S=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.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,r=`${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"}:${r}`,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 r=e.resetStuck(this.name);r>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${r} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:r}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});r||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(r=>this._triggerJob(r)))),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 i=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),i);return}let r=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(r/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let i=n.getDue(Date.now(),this.name);await Promise.allSettled(i.map(s=>this._triggerJob(s))),this._scheduleNextFromStore(e)},r)}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(r){let i=r instanceof Error?r.message:String(r);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,r),n.markFailed(e.id,i)}}_nextRunFromCron(e){return x.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};var b=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 r=await t.json();if(!r.ok)throw new Error(`Telegram API error: ${r.description}`)}normalize(e){let n=e,t=n.message||n.edited_message||{},r=t.text||"",i=t.chat||{},s=t.from||{},o=s.id!=null?String(s.id):void 0,l=s.first_name||s.username||o,c=o?{kind:"user",id:o,displayName:l??o}:void 0,f=t.entities??[],u=[];for(let w of f)if(w.type==="text_mention"&&w.user){let $=w.user;$.id!=null&&u.push(String($.id))}let m=i.type,g=i.id!=null?String(i.id):"";return{message:r,conversationId:g,data:n,participant:c,context:{chatId:i.id,userId:s.id,username:s.username,firstName:s.first_name,lastName:s.last_name,messageId:t.message_id,channelType:m,channelId:g,channelName:i.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 r of t.result){let i=r.update_id;i>=this.offset&&(this.offset=i+1);try{let s=this.normalize(r);await this.handleMessage(s)}catch(s){console.error("[TelegramChannel] Error processing update:",s)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((r,i)=>{this.handleWebhookRequest(r,i)});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",r=>{t+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(t);this.handleMessage(this.normalize(r)).catch(i=>{console.error("[TelegramChannel] Error processing webhook:",i)}),n.writeHead(200),n.end("OK")}catch(r){console.error("[TelegramChannel] Error parsing webhook:",r),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 B=new Set([1,3]),A=/<@!?(\d+)>/g,F="https://discord.com/api/v10",I=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,r=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),i=n.channel?.type,s=i!==void 0&&B.has(i),o=n.author?.id,l=n.author?.globalName??n.author?.username,c=[];if(n.content){A.lastIndex=0;let f;for(;(f=A.exec(n.content))!==null;)c.push(f[1])}return{message:n.content,conversationId:r,data:n,participant:o?{kind:"user",id:o,displayName:l??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:s?"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 r=await fetch(`${F}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!r.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${r.status}`),{kind:"user",id:n};let i=await r.json(),s=i.global_name??i.username,o={kind:"user",id:i.id,displayName:s};return this.participantCache.set(n,o),o}catch(r){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,r),{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 i=await this.client.channels.fetch(n);if(i&&"send"in i)try{await i.send({content:e.output});return}catch(s){throw console.error("[DiscordChannel] Failed to send to thread:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}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 r=await this.client.channels.fetch(t);if(!r||!("send"in r))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await r.send({content:e.output})}catch(i){throw console.error("[DiscordChannel] Failed to send to channel:",i),new Error(`[DiscordChannel] Failed to send Discord message: ${i instanceof Error?i.message:String(i)}`)}}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 r=this.client.user;this.botUserId=r?.id;let i=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),s=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${r?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${s} | channels=${i}`)}),this.client.on("messageCreate",r=>{let i=r;if(!this.shouldProcessEvent(i))return;let s=this.normalize(i);this.handleMessage(s)}),this.client.on("userUpdate",(r,i)=>{let s=i;s?.id&&this.invalidateParticipant(s.id)}),this.client.login(this.config.token).catch(r=>{console.error("[DiscordChannel] Failed to login to Discord:",r)})}).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 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",r={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(r)}catch(i){throw console.error("[EmailChannel] Failed to send email:",i),new Error(`Failed to send email: ${i instanceof Error?i.message:String(i)}`)}}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(e=>`<p>${e.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var I=class extends l{config;twilioClient;server;constructor(n){super(),this.config={port:3e3,...n},this.name=n.name}get isTriggerChannel(){return!this.config.webhookPath}listen(){typeof process<"u"&&import("twilio").then(n=>{this.twilioClient=n.default(this.config.accountSid,this.config.authToken),console.log("[SMSChannel] Twilio client initialized"),this.config.webhookPath&&this.startWebhookServer()}).catch(n=>{console.error("[SMSChannel] Failed to initialize Twilio client:",n),console.error("[SMSChannel] Make sure to install twilio: npm install twilio")})}async send(n){if(!this.twilioClient)throw new Error("Twilio client not initialized. Did you call listen()?");let e=n.metadata?.from||this.config.to;if(!e)throw new Error('No recipient phone number specified. Set "to" in config or provide in output.metadata.from');try{let t=await this.twilioClient.messages.create({body:n.output,from:this.config.from,to:e});console.log(`[SMSChannel] SMS sent: ${t.sid}`)}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(n){let e=n,t=e.From,o=e.Body,r=e.MessageSid;return{message:o,conversationId:t,data:e,context:{from:t,to:e.To,messageSid:r}}}startWebhookServer(){import("http").then(n=>{this.server=n.createServer((e,t)=>{this.handleWebhookRequest(e,t)}),this.server.listen(this.config.port,()=>{console.log(`[SMSChannel] Webhook server listening on port ${this.config.port} at ${this.config.webhookPath}`)})}).catch(n=>{console.error("[SMSChannel] Failed to start webhook server:",n)})}handleWebhookRequest(n,e){if(n.method!=="POST"||n.url!==this.config.webhookPath){e.writeHead(404),e.end("Not found");return}let t="";n.on("data",o=>{t+=o.toString()}),n.on("end",()=>{try{let o=new URLSearchParams(t),r={};o.forEach((s,d)=>{r[d]=s});let i=this.normalize(r);this.handleMessage(i),e.writeHead(200,{"Content-Type":"text/xml"}),e.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(o){console.error("[SMSChannel] Error handling webhook:",o),e.writeHead(400),e.end("Bad request")}})}async stop(){if(this.server)return new Promise(n=>{this.server.close(n)})}};0&&(module.exports={BaseChannel,DiscordChannel,EmailChannel,SMSChannel,ScheduledChannel,SlackChannel,TelegramChannel,WebhookChannel});
3
+ `).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var P=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,r=n.Body,i=n.MessageSid;return{message:r,conversationId:t,data:n,context:{from:t,to:n.To,messageSid:i}}}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",r=>{t+=r.toString()}),e.on("end",()=>{try{let r=new URLSearchParams(t),i={};r.forEach((o,l)=>{i[l]=o});let s=this.normalize(i);this.handleMessage(s),n.writeHead(200,{"Content-Type":"text/xml"}),n.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(r){console.error("[SMSChannel] Error handling webhook:",r),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};0&&(module.exports={BaseChannel,DiscordChannel,EmailChannel,SMSChannel,ScheduledChannel,SlackChannel,TelegramChannel,WebhookChannel});