@toolpack-sdk/agents 3.0.0 → 3.2.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,42 +1,42 @@
1
- var qe=Object.defineProperty;var D=(r,e)=>()=>(r&&(e=r(r=0)),e);var we=(r,e)=>{for(var t in e)qe(r,t,{get:e[t],enumerable:!0})};import Rt from"path";import{fileURLToPath as St}from"url";var h=D(()=>{"use strict"});function Ae(r){return r===K}function ve(){return K}var K,Q=D(()=>{"use strict";h();K=Symbol("interceptor-skip-sentinel")});function ke(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let u=(d=>({agent:e,channel:t,registry:n,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>s)throw new Z(g,s);if(!n)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let A=n.getAgent(l);if(!A)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??o.conversationId??`delegation-${Date.now()}`};return await A.invokeAgent(f)},skip:ve}))(0),c=async d=>{let l=d??o;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??o,u,m)}return await c()}}}async function be(r,e){let t=await r.execute(e);return t===K?null:t}var Z,Ie=D(()=>{"use strict";h();Q();Z=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});import{randomUUID as xe}from"crypto";function je(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function Ce(r){let e=r.captureAgentReplies??!0,t=r.getScope??je,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??xe()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,p,u)=>{let c=o.conversationId;if(!c)return p.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await u();let d=o.participant;if(d){let m={id:n(o),conversationId:c,participant:d,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:i(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),p.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){p.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await u();if(e&&!Ae(l)&&l.output!=null){let m={kind:"agent",id:p.agent.name,displayName:p.agent.name},g={id:xe(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),p.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:p.agent.name,conversationId:c})}catch(A){p.logger?.warn("[capture-history] Failed to store agent reply",{error:A instanceof Error?A.message:String(A)})}}return l};return s[ee]=!0,s}var ee,Re=D(()=>{"use strict";h();Q();ee=Symbol.for("toolpack:capture-history")});import{randomUUID as Fe}from"crypto";function _e(r){return Math.ceil(r.length/4)}function ze(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function He(r,e){let{participant:t,content:n}=r;return t.kind==="system"?{role:"system",content:n}:t.kind==="agent"?t.id===e?{role:"assistant",content:n}:{role:"user",content:`${t.displayName??t.id} (agent): ${n}`}:{role:"user",content:`${t.displayName??t.id}: ${n}`}}function We(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function Se(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:p=!0,tokenBudget:u=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=i,g=new Set([t,...m??[]]),A=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:A,limit:l}),y=f.length;if(p){let b=new Set;for(let M=0;M<f.length;M++){let k=f[M];if(We(k,t,g)&&b.add(k.id),M<f.length-1){let _=f[M+1];_.participant.kind==="agent"&&_.participant.id===t&&b.add(k.id)}}let x=f[f.length-1];x&&b.add(x.id),f=f.filter(M=>b.has(M.id))}let w=!1;if(f.length>c&&s){let b=Math.floor(f.length/2),x=f.slice(0,b),M=f.slice(b),k=x.filter(_=>!_.metadata?.isSummary);try{let _=await s.invokeAgent({message:"summarize",data:{turns:k.map(ze),agentName:n,agentId:t,maxTokens:Math.floor(u*.25),extractDecisions:!0}}),$=JSON.parse(_.output),U={id:`summary-${Fe()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${$.turnsSummarized} earlier turns]: ${$.summary}`,timestamp:x[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[U,...M],w=!0;try{await r.append(U),await r.deleteMessages(e,x.map(B=>B.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let v=f.map(b=>He(b,t));if(v.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:y,hasSummary:w};let R=v[v.length-1],I=[R],P=_e(R.content);for(let b=v.length-2;b>=0;b--){let x=v[b],M=_e(x.content);if(P+M>u)break;I.unshift(x),P+=M}return{messages:I,estimatedTokens:P,turnsLoaded:y,hasSummary:w}}var Te=D(()=>{"use strict";h()});var N,Me=D(()=>{"use strict";h();N=class extends Error{constructor(e){super(e),this.name="AgentError"}}});import{randomUUID as te}from"crypto";var ne,ie,re,se,oe,a,V,De=D(()=>{"use strict";h();ne=.6,ie=.2,re=.2,se={low:.3,medium:.6,high:1},oe=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"},V=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,n)=>{let i={high:0,normal:1,low:2},s=i[t.priority]-i[n.priority];return s!==0?s:t.createdAt-n.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(i=>i[a.type]==="belief"&&i[a.confidence]==="high"&&!i[a.error]&&!(i[a.expiresAt]&&i[a.expiresAt]<t))).map(i=>{let s=this.chunkToBelief(i),o=(t-s.createdAt)/864e5,u=Math.exp(-o/oe)*ie+se.high*re+ne;return{...s,score:u}}).sort((i,s)=>s.score-i.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:i="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[a.type]:"goal",[a.status]:i}})).map(u=>this.chunkToGoal(u.chunk));else{let p=i;if(o=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===p)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();o=o.filter(d=>d.description.toLowerCase().includes(c))}}return s?.length&&(o=o.filter(p=>s.every(u=>p.tags.includes(u)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,p=Date.now(),u=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of u){let l=this.chunkToBelief(d.chunk);if(!o&&l.expiresAt&&l.expiresAt<p||s?.length&&!s.every(y=>l.tags.includes(y)))continue;let m=(p-l.createdAt)/864e5,g=Math.exp(-m/oe),A=l.error?.3:se[l.confidence],f=d.score*ne+g*ie+A*re;f<i||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,p=Date.now(),u={[a.type]:"reflection"};o===!0&&(u[a.pinned]=!0);let c=await this.provider.query(e,{limit:n*4,threshold:0,filter:u}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(o===!1&&m.pinned||s?.length&&!s.every(y=>m.tags.includes(y)))continue;let g=(p-m.createdAt)/864e5,A=Math.exp(-g/oe),f=l.score*ne+A*ie+se.medium*re;f<i||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),i=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of i){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=te();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n),s={...i,description:t.description??i.description,priority:t.priority??i.priority,status:t.status??i.status,outcome:t.outcome??i.outcome,progress:t.appendProgress?[...i.progress,t.appendProgress]:i.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...i,status:"completed",outcome:t??i.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=te();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(i),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},p=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,p)])}async addReflection(e,t){let n=te();return await this.provider.add([this.reflectionToChunk({...e,id:n},t)]),n}async updateReflection(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Reflection not found: ${e}`);let i=this.chunkToReflection(n),s={...i,pinned:t.pinned??i.pinned,error:t.error??i.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,n.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(n=>n.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(n=>e(n.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function ae(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),n=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[n]}function Pe(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=ae(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Be(r,e){let t=0,n=0,i=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],i+=e[o]*e[o];let s=Math.sqrt(n)*Math.sqrt(i);return s===0?0:t/s}function ce(r){return Math.ceil(r.length/4)}var de=D(()=>{"use strict";h()});import{randomUUID as Ke}from"crypto";var J,Ee=D(()=>{"use strict";h();de();J=class{constructor(e,t,n,i,s,o,p){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=p}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;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(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+ae(s));let o=this._findSimilarInDraft(n);if(o!==null){let d=this.ops[o],l=e.confidence,m=d.confidence,g={low:0,medium:1,high:2},A=g[l]>g[m]||e.allowDowngrade&&g[l]<g[m];return this.ops[o]={...d,content:e.content,confidence:A?l:m,tags:e.tags.length>0?e.tags:d.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:d.existingId??`draft-${o}`}}let p=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(p))return{action:"updated_draft",id:"in-flight-dedup"};let u=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(u){let d=u.belief,l=e.confidence,m=d.confidence,g={low:0,medium:1,high:2},A=g[l]>g[m]||e.allowDowngrade&&g[l]<g[m],f={op:"believe",content:e.content,confidence:A?l:m,tags:e.tags.length>0?e.tags:d.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:u.id};return this.ops.push(f),{action:"updated_store",id:u.id}}this.inFlightBeliefs.add(p);let c={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(c),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=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.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),i={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:n},s=`draft-reflect-${this.ops.length}`;return this.ops.push(i),{id:s,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?Pe(e.dueBy):void 0,n={op:"set_goal",tempId:Ke(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(n),{id:n.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 n of this.ops)if(n.op==="believe"){let i=n;this.inFlightBeliefs.delete(i.content.trim().toLowerCase()),e?i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0,createdAt:i.createdAt,updatedAt:t},i.vector):i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="reflect"){let i=n;if(i.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content:i.content,pinned:i.pinned,tags:i.tags,relatedTo:i.relatedTo,error:e||void 0,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="set_goal"){if(!e){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=n;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(n.op==="update_goal"){if(!e){let i=n;await this.store.updateGoal(i.id,{description:i.description,priority:i.priority,appendProgress:i.progress})}}else if(n.op==="unpin_reflection"&&!e){let i=n;await this.store.updateReflection(i.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,i)=>({op:n,idx:i})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:i}of t){let s=n;if(s.vector.length===0)continue;if(Be(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function Ne(r,e,t){return[Ve(r,t),Je(r,e,t),Ye(e,t),Xe(e),Qe(e,t),Ze(r,e),et(r)]}function Ve(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 n=String(t.query??""),i=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,p=typeof t.pinned=="boolean"?t.pinned:void 0,u=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=(i==="belief"||i==="reflection"||i==="all")&&n.trim()?await r.embed(n):null;if(i==="goal"||i==="all"){let A=await r.keywordSearchGoals(n,{limit:d,status:s,tags:o});for(let f of A)l.push(tt(f))}if(g&&(i==="belief"||i==="all")){let A=await r.queryBeliefs(g,{limit:d,threshold:c,tags:o,includeExpired:u});for(let f of A)l.push(nt(f))}if(g&&(i==="reflection"||i==="all")){let A=await r.queryReflections(g,{limit:d,threshold:c,tags:o,pinned:p});for(let f of A)l.push(it(f))}return l}}}function Je(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 n=>({status:"ok",...await e.addBelieve({content:String(n.content),confidence:n.confidence??"medium",tags:Array.isArray(n.tags)?n.tags.map(String):[],expiresIn:n.expiresIn?String(n.expiresIn):void 0,allowDowngrade:n.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Ye(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 Xe(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 Qe(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 Ze(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 et(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 tt(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 nt(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 it(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 $e=D(()=>{"use strict";h()});async function Ge(r,e){let[t,n,i,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(l=>rt(l)),p=n.map(l=>`- ${l.content}`),{beliefLines:u,reflectionLines:c}=st(i,s,e.tokenBudget);if(o.length===0&&p.length===0&&u.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return o.length>0&&(d.push("## Goals"),d.push(...o),d.push("")),p.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...p),d.push("")),u.length>0&&(d.push("## Beliefs"),d.push(...u),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
- `)}function rt(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 st(r,e,t){let n=t,i=[],s=[];for(let o of r){let p=`- ${o.content} (${o.confidence} confidence)`,u=ce(p);if(u>n)break;i.push(p),n-=u}for(let o of e){let u=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,c=ce(u);if(c>n)break;s.push(u),n-=c}return{beliefLines:i,reflectionLines:s}}var Oe=D(()=>{"use strict";h();de()});var Le={};we(Le,{AgentMind:()=>le});function ft(r,e){let t=Math.min(e.maxGoals??ct,mt),n=Math.min(e.maxPinnedReflections??dt,gt);return{tokenBudget:e.tokenBudget??ot,recencyWindowDays:e.recencyWindowDays??at,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??lt,retrievalThreshold:e.retrievalThreshold??pt,ttlDefaults:{belief:e.ttlDefaults?.belief??ut,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var ot,at,ct,dt,lt,pt,ut,mt,gt,le,Ue=D(()=>{"use strict";h();De();Ee();$e();Oe();ot=300,at=7,ct=10,dt=10,lt=.85,pt=.35,ut="30d",mt=10,gt=10,le=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let n;if(t.provider)n=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),p=t.namespace??`mind/${e}`;n=new o({namespace:p})}let i=ft(e,t),s=new V(n,t.embedder);return await s.initialize(),new r(s,i)}async createRunContext(){let[e,t,n]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),Ge(this.store,this.config)]),i=new J(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Ne(this.store,i,this.config);return{mindHeader:n,tools:s,flush:async p=>{p?await i.flushOnError():await i.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var ue={};we(ue,{EphemeralAgent:()=>pe});var pe,me=D(()=>{"use strict";h();Y();pe=class extends L{name;description;mode;constructor(e,t,n,i){super(i),this.name=e,this.description=t,this.mode=n}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0})}}});import{EventEmitter as ht}from"events";import{AsyncLocalStorage as yt}from"async_hooks";import{Toolpack as wt,InMemoryConversationStore as At,AGENT_MODE as X}from"toolpack-sdk";var L,Y=D(()=>{"use strict";h();Ie();Re();Te();Me();L=class extends ht{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new yt;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new At,"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 wt.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(Ue(),Le));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?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,n){let i=n?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:i}),this.emit("agent:start",{message:e}),await this._ensureMind();let s,o="",p=[];if(this._mind){let u=await this._mind.createRunContext();o=u.mindHeader,p=u.tools,s=u.flush}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let u=[];if(o&&u.push({role:"system",content:o}),i)try{let y=await Se(this.conversationHistory,i,this.name,this.name,this._resolveAssemblerOptions()),w=y.messages[y.messages.length-1],v=e.trim(),I=v!==""&&w?.role==="user"&&typeof w.content=="string"&&(w.content===v||w.content.endsWith(`: ${v}`))?y.messages.slice(0,-1):y.messages;u.push(...I)}catch{}e.trim()&&u.push({role:"user",content:e});let c=[...p];if(i){let y=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 w=>{let v=await y.search(i,String(w.query??""),{limit:typeof w.limit=="number"?w.limit:5});return{results:v.map(R=>({role:R.participant.kind==="agent"?"assistant":"user",content:R.content,timestamp:R.timestamp})),count:v.length}}})}if(this.delegation?.enabled&&this._registry){let y=this.delegation.allowedAgents,w=this._registry.getAllAgents().filter(v=>v.name!==this.name&&(y===void 0||y.includes(v.name)));if(w.length>0){let v=w.map(I=>I.name),R=w.map(I=>`- ${I.name}: ${I.description}`).join(`
1
+ var qe=Object.defineProperty;var P=(r,e)=>()=>(r&&(e=r(r=0)),e);var Ae=(r,e)=>{for(var t in e)qe(r,t,{get:e[t],enumerable:!0})};import _t from"path";import{fileURLToPath as Mt}from"url";var h=P(()=>{"use strict"});function ve(r){return r===V}function ke(){return V}var V,Z=P(()=>{"use strict";h();V=Symbol("interceptor-skip-sentinel")});function be(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let d=(c=>({agent:e,channel:t,registry:n,invocationDepth:c,delegateAndWait:async(p,g)=>{let m=c+1;if(m>s)throw new ee(m,s);if(!n)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let w=n.getAgent(p);if(!w)throw new Error(`Agent "${p}" not found for delegation`);let f={message:g.message??"",intent:g.intent,data:g.data,context:g.context,conversationId:g.conversationId??o.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(f)},skip:ke}))(0),l=async c=>{let p=c??o;return await e.invokeAgent(p)};for(let c=r.length-1;c>=0;c--){let p=r[c],g=l;l=async m=>await p(m??o,d,g)}return await l()}}}async function Ie(r,e){let t=await r.execute(e);return t===V?null:t}var ee,xe=P(()=>{"use strict";h();Z();ee=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});import{randomUUID as Ce}from"crypto";function Fe(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function Re(r){let e=r.captureAgentReplies??!0,t=r.getScope??Fe,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??Ce()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,u,d)=>{let l=o.conversationId;if(!l)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await d();let c=o.participant;if(c){let g={id:n(o),conversationId:l,participant:c,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:i(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured inbound message",{messageId:g.id,participantId:c.id,conversationId:l})}catch(m){u.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let p=await d();if(e&&!ve(p)&&p.output!=null){let g={kind:"agent",id:u.agent.name,displayName:u.agent.name},m={id:Ce(),conversationId:l,participant:g,content:p.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:u.agent.name,conversationId:l})}catch(w){u.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return p};return s[te]=!0,s}var te,_e=P(()=>{"use strict";h();Z();te=Symbol.for("toolpack:capture-history")});import{randomUUID as ze}from"crypto";function Se(r){return Math.ceil(r.length/4)}function He(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function We(r,e){let{participant:t,content:n}=r;return t.kind==="system"?{role:"system",content:n}:t.kind==="agent"?t.id===e?{role:"assistant",content:n}:{role:"user",content:`${t.displayName??t.id} (agent): ${n}`}:{role:"user",content:`${t.displayName??t.id}: ${n}`}}function Ke(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function Me(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:u=!0,tokenBudget:d=3e3,rollingSummaryThreshold:l=40,timeWindowMinutes:c,maxTurnsToLoad:p=100,agentAliases:g}=i,m=new Set([t,...g??[]]),w=c!==void 0?new Date(Date.now()-c*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:w,limit:p}),D=f.length;if(u){let v=new Set;for(let I=0;I<f.length;I++){let j=f[I];if(Ke(j,t,m)&&v.add(j.id),I<f.length-1){let k=f[I+1];k.participant.kind==="agent"&&k.participant.id===t&&v.add(j.id)}}let _=f[f.length-1];_&&v.add(_.id),f=f.filter(I=>v.has(I.id))}let y=!1;if(f.length>l&&s){let v=Math.floor(f.length/2),_=f.slice(0,v),I=f.slice(v),j=_.filter(k=>!k.metadata?.isSummary);try{let k=await s.invokeAgent({message:"summarize",data:{turns:j.map(He),agentName:n,agentId:t,maxTokens:Math.floor(d*.25),extractDecisions:!0}}),T=JSON.parse(k.output),N={id:`summary-${ze()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${T.turnsSummarized} earlier turns]: ${T.summary}`,timestamp:_[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[N,...I],y=!0;try{await r.append(N),await r.deleteMessages(e,_.map(q=>q.id))}catch{}}catch{f=f.slice(-l)}}else f.length>l&&(f=f.slice(-l));let A=f.map(v=>We(v,t));if(A.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:D,hasSummary:y};let x=A[A.length-1],R=[x],b=Se(x.content);for(let v=A.length-2;v>=0;v--){let _=A[v],I=Se(_.content);if(b+I>d)break;R.unshift(_),b+=I}return{messages:R,estimatedTokens:b,turnsLoaded:D,hasSummary:y}}var Pe=P(()=>{"use strict";h()});var E,Te=P(()=>{"use strict";h();E=class extends Error{constructor(e){super(e),this.name="AgentError"}}});import{randomUUID as ne}from"crypto";var ie,re,se,oe,ae,a,J,De=P(()=>{"use strict";h();ie=.6,re=.2,se=.2,oe={low:.3,medium:.6,high:1},ae=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"},J=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,n)=>{let i={high:0,normal:1,low:2},s=i[t.priority]-i[n.priority];return s!==0?s:t.createdAt-n.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(i=>i[a.type]==="belief"&&i[a.confidence]==="high"&&!i[a.error]&&!(i[a.expiresAt]&&i[a.expiresAt]<t))).map(i=>{let s=this.chunkToBelief(i),o=(t-s.createdAt)/864e5,d=Math.exp(-o/ae)*re+oe.high*se+ie;return{...s,score:d}}).sort((i,s)=>s.score-i.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:i="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[a.type]:"goal",[a.status]:i}})).map(d=>this.chunkToGoal(d.chunk));else{let u=i;if(o=(await this._getAllByMeta(l=>l[a.type]==="goal"&&l[a.status]===u)).map(l=>this.chunkToGoal(l)),e.trim()){let l=e.toLowerCase();o=o.filter(c=>c.description.toLowerCase().includes(l))}}return s?.length&&(o=o.filter(u=>s.every(d=>u.tags.includes(d)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,u=Date.now(),d=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),l=[];for(let c of d){let p=this.chunkToBelief(c.chunk);if(!o&&p.expiresAt&&p.expiresAt<u||s?.length&&!s.every(D=>p.tags.includes(D)))continue;let g=(u-p.createdAt)/864e5,m=Math.exp(-g/ae),w=p.error?.3:oe[p.confidence],f=c.score*ie+m*re+w*se;f<i||l.push({...p,score:f})}return l.sort((c,p)=>p.score-c.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,u=Date.now(),d={[a.type]:"reflection"};o===!0&&(d[a.pinned]=!0);let l=await this.provider.query(e,{limit:n*4,threshold:0,filter:d}),c=[];for(let p of l){let g=this.chunkToReflection(p.chunk);if(o===!1&&g.pinned||s?.length&&!s.every(D=>g.tags.includes(D)))continue;let m=(u-g.createdAt)/864e5,w=Math.exp(-m/ae),f=p.score*ie+w*re+oe.medium*se;f<i||c.push({...g,score:f})}return c.sort((p,g)=>g.score-p.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),i=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of i){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=ne();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n),s={...i,description:t.description??i.description,priority:t.priority??i.priority,status:t.status??i.status,outcome:t.outcome??i.outcome,progress:t.appendProgress?[...i.progress,t.appendProgress]:i.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...i,status:"completed",outcome:t??i.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=ne();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(i),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},u=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,u)])}async addReflection(e,t){let n=ne();return await this.provider.add([this.reflectionToChunk({...e,id:n},t)]),n}async updateReflection(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Reflection not found: ${e}`);let i=this.chunkToReflection(n),s={...i,pinned:t.pinned??i.pinned,error:t.error??i.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,n.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(n=>n.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(n=>e(n.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function ce(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),n=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[n]}function Be(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=ce(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ee(r,e){let t=0,n=0,i=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],i+=e[o]*e[o];let s=Math.sqrt(n)*Math.sqrt(i);return s===0?0:t/s}function de(r){return Math.ceil(r.length/4)}var le=P(()=>{"use strict";h()});import{randomUUID as Ve}from"crypto";var Y,Ne=P(()=>{"use strict";h();le();Y=class{constructor(e,t,n,i,s,o,u){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=u}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;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(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+ce(s));let o=this._findSimilarInDraft(n);if(o!==null){let c=this.ops[o],p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},w=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g];return this.ops[o]={...c,content:e.content,confidence:w?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:c.existingId??`draft-${o}`}}let u=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(u))return{action:"updated_draft",id:"in-flight-dedup"};let d=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(d){let c=d.belief,p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},w=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g],f={op:"believe",content:e.content,confidence:w?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:d.id};return this.ops.push(f),{action:"updated_store",id:d.id}}this.inFlightBeliefs.add(u);let l={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(l),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=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.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),i={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:n},s=`draft-reflect-${this.ops.length}`;return this.ops.push(i),{id:s,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?Be(e.dueBy):void 0,n={op:"set_goal",tempId:Ve(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(n),{id:n.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 n of this.ops)if(n.op==="believe"){let i=n;this.inFlightBeliefs.delete(i.content.trim().toLowerCase()),e?i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0,createdAt:i.createdAt,updatedAt:t},i.vector):i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="reflect"){let i=n;if(i.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content:i.content,pinned:i.pinned,tags:i.tags,relatedTo:i.relatedTo,error:e||void 0,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="set_goal"){if(!e){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=n;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(n.op==="update_goal"){if(!e){let i=n;await this.store.updateGoal(i.id,{description:i.description,priority:i.priority,appendProgress:i.progress})}}else if(n.op==="unpin_reflection"&&!e){let i=n;await this.store.updateReflection(i.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,i)=>({op:n,idx:i})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:i}of t){let s=n;if(s.vector.length===0)continue;if(Ee(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function $e(r,e,t){return[Je(r,t),Ye(r,e,t),Xe(e,t),Qe(e),Ze(e,t),et(r,e),tt(r)]}function Je(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 n=String(t.query??""),i=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,d=t.includeExpired===!0,l=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,c=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,p=[],m=(i==="belief"||i==="reflection"||i==="all")&&n.trim()?await r.embed(n):null;if(i==="goal"||i==="all"){let w=await r.keywordSearchGoals(n,{limit:c,status:s,tags:o});for(let f of w)p.push(nt(f))}if(m&&(i==="belief"||i==="all")){let w=await r.queryBeliefs(m,{limit:c,threshold:l,tags:o,includeExpired:d});for(let f of w)p.push(it(f))}if(m&&(i==="reflection"||i==="all")){let w=await r.queryReflections(m,{limit:c,threshold:l,tags:o,pinned:u});for(let f of w)p.push(rt(f))}return p}}}function Ye(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 n=>({status:"ok",...await e.addBelieve({content:String(n.content),confidence:n.confidence??"medium",tags:Array.isArray(n.tags)?n.tags.map(String):[],expiresIn:n.expiresIn?String(n.expiresIn):void 0,allowDowngrade:n.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Xe(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 Qe(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 Ze(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 et(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 tt(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 nt(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 it(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 rt(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 Ge=P(()=>{"use strict";h()});async function Oe(r,e){let[t,n,i,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(p=>st(p)),u=n.map(p=>`- ${p.content}`),{beliefLines:d,reflectionLines:l}=ot(i,s,e.tokenBudget);if(o.length===0&&u.length===0&&d.length===0&&l.length===0)return"";let c=["--- AGENT MIND ---",""];return o.length>0&&(c.push("## Goals"),c.push(...o),c.push("")),u.length>0&&(c.push("## Standing Rules (Pinned)"),c.push(...u),c.push("")),d.length>0&&(c.push("## Beliefs"),c.push(...d),c.push("")),l.length>0&&(c.push("## Recent Reflections"),c.push(...l),c.push("")),c.push("---"),c.join(`
2
+ `)}function st(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 ot(r,e,t){let n=t,i=[],s=[];for(let o of r){let u=`- ${o.content} (${o.confidence} confidence)`,d=de(u);if(d>n)break;i.push(u),n-=d}for(let o of e){let d=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,l=de(d);if(l>n)break;s.push(d),n-=l}return{beliefLines:i,reflectionLines:s}}var Le=P(()=>{"use strict";h();le()});var je={};Ae(je,{AgentMind:()=>pe});function ht(r,e){let t=Math.min(e.maxGoals??dt,gt),n=Math.min(e.maxPinnedReflections??lt,ft);return{tokenBudget:e.tokenBudget??at,recencyWindowDays:e.recencyWindowDays??ct,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??pt,retrievalThreshold:e.retrievalThreshold??ut,ttlDefaults:{belief:e.ttlDefaults?.belief??mt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var at,ct,dt,lt,pt,ut,mt,gt,ft,pe,Ue=P(()=>{"use strict";h();De();Ne();Ge();Le();at=300,ct=7,dt=10,lt=10,pt=.85,ut=.35,mt="30d",gt=10,ft=10,pe=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let n;if(t.provider)n=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;n=new o({namespace:u})}let i=ht(e,t),s=new J(n,t.embedder);return await s.initialize(),new r(s,i)}async createRunContext(){let[e,t,n]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),Oe(this.store,this.config)]),i=new Y(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=$e(this.store,i,this.config),o={manifest:{key:"mind",name:"mind",displayName:"Agent Mind",version:"1.0.0",description:"Agent cognitive tools for beliefs, goals, and reflections.",category:"mind",tools:s.map(d=>d.name)},tools:s};return{mindHeader:n,toolProject:o,flush:async d=>{d?await i.flushOnError():await i.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var me={};Ae(me,{EphemeralAgent:()=>ue});var ue,ge=P(()=>{"use strict";h();X();ue=class extends L{name;description;mode;constructor(e,t,n,i){super(i),this.name=e,this.description=t,this.mode=n}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0},e.attachments)}}});import{EventEmitter as yt}from"events";import{AsyncLocalStorage as wt}from"async_hooks";import{Toolpack as At,InMemoryConversationStore as vt,AGENT_MODE as Q}from"toolpack-sdk";var L,X=P(()=>{"use strict";h();xe();_e();Pe();Te();L=class extends yt{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new wt;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new vt,"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 At.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(Ue(),je));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?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,n,i){let s=n?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:s}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,u="";if(this._mind){let d=await this._mind.createRunContext();u=d.mindHeader,o=d.flush,this.toolpack.loadRequestToolProject(d.toolProject)}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let d=[];if(u&&d.push({role:"system",content:u}),s)try{let y=await Me(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),A=y.messages[y.messages.length-1],x=e.trim(),b=x!==""&&A?.role==="user"&&typeof A.content=="string"&&(A.content===x||A.content.endsWith(`: ${x}`))?y.messages.slice(0,-1):y.messages;d.push(...b)}catch{}let l=i&&i.length>0;if(e.trim()||l)if(l){let y=[...e.trim()?[{type:"text",text:e}]:[],...i];d.push({role:"user",content:y})}else d.push({role:"user",content:e});let c=[];if(s){let y=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 A=>{let x=await y.search(s,String(A.query??""),{limit:typeof A.limit=="number"?A.limit:5});return{results:x.map(R=>({role:R.participant.kind==="agent"?"assistant":"user",content:R.content,timestamp:R.timestamp})),count:x.length}}})}if(this.delegation?.enabled&&this._registry){let y=this.delegation.allowedAgents,A=this._registry.getAllAgents().filter(x=>x.name!==this.name&&(y===void 0||y.includes(x.name)));if(A.length>0){let x=A.map(b=>b.name),R=A.map(b=>`- ${b.name}: ${b.description}`).join(`
3
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.
4
4
 
5
5
  Available agents:
6
- ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:v,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 I=>{let P=String(I.agent),b=String(I.message??"");return this._registry.invoke(P,{message:b,conversationId:i,context:{delegatedBy:this.name},signal:t?.signal}).catch(x=>{console.error(`[${this.name}] delegate_and_forget to ${P} failed:`,x)}),{status:"delegated",agent:P}}}):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.
6
+ ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:x,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 b=>{let v=String(b.agent),_=String(b.message??"");return this._registry.invoke(v,{message:_,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal}).catch(I=>{console.error(`[${this.name}] delegate_and_forget to ${v} failed:`,I)}),{status:"delegated",agent:v}}}):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.
7
7
 
8
8
  Available agents:
9
- ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:v,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 I=>{let P=String(I.agent),b=String(I.message??""),x=await this._registry.invoke(P,{message:b,conversationId:i,context:{delegatedBy:this.name},signal:t?.signal});return{...x,output:`[Response from ${P} \u2014 task complete]
9
+ ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:x,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 b=>{let v=String(b.agent),_=String(b.message??""),I=await this._registry.invoke(v,{message:_,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal});return{...I,output:`[Response from ${v} \u2014 task complete]
10
10
 
11
- ${x.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let y=n?.spawnDepth??0,w=this.spawn,v=w.maxDepth??3;if(y<v){let R=w.templates,I=R.some(k=>k.name==="self"),P=R.some(k=>k.allowPromptAddition),b=R.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
12
- `),x=I?`Use template name "self" to spawn a replica of the current agent.
13
- `:"",M=P?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
11
+ ${I.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let y=n?.spawnDepth??0,A=this.spawn,x=A.maxDepth??3;if(y<x){let R=A.templates,b=R.some(k=>k.name==="self"),v=R.some(k=>k.allowPromptAddition),_=R.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
12
+ `),I=b?`Use template name "self" to spawn a replica of the current agent.
13
+ `:"",j=v?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
14
14
 
15
15
  Available templates:
16
- ${b}
17
- `+x+`Spawn depth: ${y}/${v}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:I?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...M},required:["template","task"]},execute:async k=>{let _=String(k.template),$=String(k.task??""),U,B,G,O,C=R.find(E=>E.name===_);if(!C)throw new Error(`Unknown spawn template: "${_}"`);let z=C.allowPromptAddition&&k.systemPromptAddition?`
16
+ ${_}
17
+ `+I+`Spawn depth: ${y}/${x}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:b?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...j},required:["template","task"]},execute:async k=>{let T=String(k.template),N=String(k.task??""),q,$,G,O,C=R.find(B=>B.name===T);if(!C)throw new Error(`Unknown spawn template: "${T}"`);let H=C.allowPromptAddition&&k.systemPromptAddition?`
18
18
 
19
- ${String(k.systemPromptAddition)}`:"";if(_==="self"){let E=typeof this.mode=="string"?{...X,name:this.mode}:this.mode,F=C.systemPrompt($);U={...E,name:`${E.name}-replica-${Date.now()}`,systemPrompt:(E.systemPrompt??"")+(F?`
19
+ ${String(k.systemPromptAddition)}`:"";if(T==="self"){let B=typeof this.mode=="string"?{...Q,name:this.mode}:this.mode,z=C.systemPrompt(N);q={...B,name:`${B.name}-replica-${Date.now()}`,systemPrompt:(B.systemPrompt??"")+(z?`
20
20
 
21
- ${F}`:"")+z},B=`${this.name}-replica`,G=this.description,O=this.model}else U={...X,name:`ephemeral-${C.name}-${Date.now()}`,systemPrompt:C.systemPrompt($)+z},B=C.name,G=C.description,O=C.model;let{EphemeralAgent:H}=await Promise.resolve().then(()=>(me(),ue)),q=new H(B,G,U,{toolpack:this.toolpack});O&&(q.model=O),q.spawn={...w};let j=await q.invokeAgent({message:$,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:j.output,spawnedTemplate:_,depth:y+1,metadata:j.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
21
+ ${z}`:"")+H},$=`${this.name}-replica`,G=this.description,O=this.model}else q={...Q,name:`ephemeral-${C.name}-${Date.now()}`,systemPrompt:C.systemPrompt(N)+H},$=C.name,G=C.description,O=C.model;let{EphemeralAgent:W}=await Promise.resolve().then(()=>(ge(),me)),U=new W($,G,q,{toolpack:this.toolpack});O&&(U.model=O),U.spawn={...A};let F=await U.invokeAgent({message:N,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:F.output,spawnedTemplate:T,depth:y+1,metadata:F.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
22
22
 
23
23
  Available templates:
24
- ${b}
25
- `+x+`Spawn depth: ${y}/${v}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:I?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...P?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let _=k.tasks;if(!Array.isArray(_)||_.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:$}=await Promise.resolve().then(()=>(me(),ue));return{results:await Promise.all(_.map(async B=>{let G=String(B.template),O=String(B.task??""),C=R.find(W=>W.name===G);if(!C)throw new Error(`Unknown spawn template: "${G}"`);let z=C.allowPromptAddition&&B.systemPromptAddition?`
24
+ ${_}
25
+ `+I+`Spawn depth: ${y}/${x}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:b?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...v?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let T=k.tasks;if(!Array.isArray(T)||T.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:N}=await Promise.resolve().then(()=>(ge(),me));return{results:await Promise.all(T.map(async $=>{let G=String($.template),O=String($.task??""),C=R.find(K=>K.name===G);if(!C)throw new Error(`Unknown spawn template: "${G}"`);let H=C.allowPromptAddition&&$.systemPromptAddition?`
26
26
 
27
- ${String(B.systemPromptAddition)}`:"",H,q,j,E;if(G==="self"){let W=typeof this.mode=="string"?{...X,name:this.mode}:this.mode,ye=C.systemPrompt(O);H={...W,name:`${W.name}-replica-${Date.now()}`,systemPrompt:(W.systemPrompt??"")+(ye?`
27
+ ${String($.systemPromptAddition)}`:"",W,U,F,B;if(G==="self"){let K=typeof this.mode=="string"?{...Q,name:this.mode}:this.mode,we=C.systemPrompt(O);W={...K,name:`${K.name}-replica-${Date.now()}`,systemPrompt:(K.systemPrompt??"")+(we?`
28
28
 
29
- ${ye}`:"")+z},q=`${this.name}-replica`,j=this.description,E=this.model}else H={...X,name:`ephemeral-${C.name}-${Date.now()}`,systemPrompt:C.systemPrompt(O)+z},q=C.name,j=C.description,E=C.model;let F=new $(q,j,H,{toolpack:this.toolpack});E&&(F.model=E),F.spawn={...w};let he=await F.invokeAgent({message:O,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:he.output,spawnedTemplate:G,depth:y+1,metadata:he.metadata}}))}}})}}let d={messages:u,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},l=null,m,g;if(typeof this.mode!="string"&&this.mode?.streaming){let y="";for await(let w of this.toolpack.stream(d,this.provider))y+=w.delta||"",w.usage&&(m=w.usage);l=y||null,g={content:l,usage:m}}else{let y=await this.toolpack.generate(d,this.provider);l=y.content??null,m=y.usage,g=y}let f={output:l||"",steps:this.extractSteps(g),metadata:m?{usage:m}:void 0};return await this.onComplete(f),s&&await s(!1),this.emit("agent:complete",f),f}catch(u){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(u),this.emit("agent:error",u),u}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}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 N("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,i=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new N("No conversationId available - ask() requires a conversation channel");if(i)throw new N("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!s||s.trim()==="")throw new N("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:n,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new N("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){if(n?.simpleValidation)return n.simpleValidation(t);let i=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
29
+ ${we}`:"")+H},U=`${this.name}-replica`,F=this.description,B=this.model}else W={...Q,name:`ephemeral-${C.name}-${Date.now()}`,systemPrompt:C.systemPrompt(O)+H},U=C.name,F=C.description,B=C.model;let z=new N(U,F,W,{toolpack:this.toolpack});B&&(z.model=B),z.spawn={...A};let ye=await z.invokeAgent({message:O,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:ye.output,spawnedTemplate:G,depth:y+1,metadata:ye.metadata}}))}}})}}let p={messages:d,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},g=null,m,w;if(typeof this.mode!="string"&&this.mode?.streaming){let y="";for await(let A of this.toolpack.stream(p,this.provider))y+=A.delta||"",A.usage&&(m=A.usage);g=y||null,w={content:g,usage:m}}else{let y=await this.toolpack.generate(p,this.provider);g=y.content??null,m=y.usage,w=y}let D={output:g||"",steps:this.extractSteps(w),metadata:m?{usage:m}:void 0};return await this.onComplete(D),o&&await o(!1),this.emit("agent:complete",D),D}catch(d){throw o&&o(!0).catch(l=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,l)}),await this.onError(d),this.emit("agent:error",d),d}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}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 E("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,i=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new E("No conversationId available - ask() requires a conversation channel");if(i)throw new E("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!s||s.trim()==="")throw new E("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:n,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new E("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){if(n?.simpleValidation)return n.simpleValidation(t);let i=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
30
30
 
31
31
  Question: "${e}"
32
32
  Answer: "${t}"
33
33
 
34
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return 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 N("Agent not registered - cannot use delegateAndWait()");let n={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,n)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(i=>i.botUserId).filter(i=>typeof i=="string"&&i.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let n=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[ee]===!0)?this.interceptors:[Ce({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 n=await this._acquireConversationLock(t.conversationId);await this._channelCtx.run({conversationId:t.conversationId,triggeringChannel:e.name??"",isTriggerChannel:e.isTriggerChannel},async()=>{try{let i=ke(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await be(i,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(i){let s=i instanceof Error?i.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(i=>{t=i});return this._conversationLocks.set(e,n),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let n=t.plan;if(Array.isArray(n.steps))return n.steps.map(i=>({number:i.number||0,description:i.description||"",status:i.status||"completed",result:i.result}))}if(Array.isArray(t.steps))return t.steps}}});h();h();Y();import{CHAT_MODE as vt}from"toolpack-sdk";var kt={...vt,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(`
35
- `)},ge=class extends L{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=kt;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 n=[];if(n.push(`Context: Public channel #${t.channelName}`),n.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),n.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){n.push(`
36
- Recent conversation:`);for(let p of t.recentContext)n.push(` ${p.sender}: ${p.content.substring(0,100)}`)}n.push(`
34
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return 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 E("Agent not registered - cannot use delegateAndWait()");let n={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,n)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(i=>i.botUserId).filter(i=>typeof i=="string"&&i.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let n=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[te]===!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 n=await this._acquireConversationLock(t.conversationId);await this._channelCtx.run({conversationId:t.conversationId,triggeringChannel:e.name??"",isTriggerChannel:e.isTriggerChannel},async()=>{try{let i=be(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await Ie(i,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(i){let s=i instanceof Error?i.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(i=>{t=i});return this._conversationLocks.set(e,n),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let n=t.plan;if(Array.isArray(n.steps))return n.steps.map(i=>({number:i.number||0,description:i.description||"",status:i.status||"completed",result:i.result}))}if(Array.isArray(t.steps))return t.steps}}});h();h();X();import{CHAT_MODE as kt}from"toolpack-sdk";var bt={...kt,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(`
35
+ `)},fe=class extends L{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=bt;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 n=[];if(n.push(`Context: Public channel #${t.channelName}`),n.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),n.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){n.push(`
36
+ Recent conversation:`);for(let u of t.recentContext)n.push(` ${u.sender}: ${u.content.substring(0,100)}`)}n.push(`
37
37
  Message to classify: "${t.message}"`),t.includeExamples&&(n.push(`
38
38
  Examples of classifications:`),n.push(` "@${t.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
39
39
  Classification (start with direct, indirect, passive, or ignore):`);let i=n.join(`
40
- `),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t: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"}};h();Y();import{CHAT_MODE as bt}from"toolpack-sdk";var It={...bt,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(`
41
- `)},fe=class extends L{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=It;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 n=t.maxTokens??800,i=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${i?"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}]`),s.push(g)}s.push("","Generate a JSON summary object:");let o=s.join(`
42
- `),p=await this.run(o),u=this.parseSummarizerOutput(p.output,t.turns.length);return{output:JSON.stringify(u),metadata:{turnsProcessed:t.turns.length,rawOutputLength:p.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),i=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);i&&(n=i[1].trim());try{let s=JSON.parse(n);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.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{ge as IntentClassifierAgent,fe as SummarizerAgent};
40
+ `),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t: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"}};h();X();import{CHAT_MODE as It}from"toolpack-sdk";var xt={...It,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(`
41
+ `)},he=class extends L{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=xt;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 n=t.maxTokens??800,i=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${i?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let l of t.turns){let c=new Date(l.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=l.participant.displayName??l.participant.id,g=l.participant.kind==="agent"?`[BOT] ${p}`:p,m=`[${c}] ${g}: ${l.content.substring(0,200)}`;l.content.length>200&&(m+="..."),l.metadata?.isToolCall&&l.metadata.toolName&&(m+=` [tool: ${l.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let o=s.join(`
42
+ `),u=await this.run(o),d=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(d),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),i=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);i&&(n=i[1].trim());try{let s=JSON.parse(n);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.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{fe as IntentClassifierAgent,he as SummarizerAgent};
@@ -1,3 +1,3 @@
1
- "use strict";var B=Object.create;var y=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var H=(d,e)=>{for(var n in e)y(d,n,{get:e[n],enumerable:!0})},R=(d,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!W.call(d,i)&&i!==n&&y(d,i,{get:()=>e[i],enumerable:!(t=F(e,i))||t.enumerable});return d};var p=(d,e,n)=>(n=d!=null?B(j(d)):{},R(e||!d||!d.__esModule?y(n,"default",{value:d,enumerable:!0}):n,d)),J=d=>R(y({},"__esModule",{value:!0}),d);var G={};H(G,{BaseChannel:()=>l,DiscordChannel:()=>_,EmailChannel:()=>x,McpChannel:()=>M,SMSChannel:()=>$,ScheduledChannel:()=>T,SlackChannel:()=>b,TelegramChannel:()=>P,WebhookChannel:()=>I});module.exports=J(G);var l=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};var S=require("crypto");var b=class extends l{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,c=`v0=${(0,S.createHmac)("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(c.length!==i.length)return!1;try{return(0,S.timingSafeEqual)(Buffer.from(c),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,a=n.user,c=a?{kind:"user",id:a}:void 0,m=/<@([A-Z0-9]+)>/g,k=[],f;for(;(f=m.exec(i))!==null;)k.push(f[1]);let w=n.channel;return{message:i,conversationId:o?r:w||s||"",data:n,participant:c,context:{user:a,channel:w,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:k.length>0?k:void 0,channelId:w,channelName:typeof this.config.channel=="string"?this.config.channel:w}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let a={kind:"user",id:n};return this.participantCache.set(n,a),a}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let a=e.channel;if(!a||!this.allowedChannels.includes(a))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var I=class extends l{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((a,c)=>{this.pendingResponses.set(r,{resolve:a,reject:c}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(a=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(a))}).catch(a=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:a.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var D=require("cron-parser"),T=class extends l{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{D.CronExpressionParser.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return D.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};var P=class extends l{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=e.metadata?.replyMarkup,i=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown",...t?{reply_markup:t}:{}})});if(!i.ok)throw new Error(`Failed to send Telegram message: ${i.statusText}`);let s=await i.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,n){let t=await fetch(`https://api.telegram.org/bot${this.config.token}/answerCallbackQuery`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callback_query_id:e,...n?{text:n}:{}})});if(!t.ok)throw new Error(`Failed to answer Telegram callback query: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.callback_query;if(t){let C=t.message||{},u=C.chat||{},g=t.from||{},v=g.id!=null?String(g.id):void 0,O=g.first_name||g.username||v,U=v?{kind:"user",id:v,displayName:O??v}:void 0,E=u.id!=null?String(u.id):"";return{message:t.data??"",conversationId:E,data:n,participant:U,context:{isCallback:!0,callbackQueryId:t.id,callbackData:t.data,chatId:u.id,userId:g.id,username:g.username,firstName:g.first_name,lastName:g.last_name,messageId:C.message_id,channelType:u.type,channelId:E,channelName:u.title}}}let i=n.message||n.edited_message||{},s=i.text||"",r=i.chat||{},o=i.from||{},a=o.id!=null?String(o.id):void 0,c=o.first_name||o.username||a,m=a?{kind:"user",id:a,displayName:c??a}:void 0,k=i.entities??[],f=[];for(let C of k)if(C.type==="text_mention"&&C.user){let u=C.user;u.id!=null&&f.push(String(u.id))}let w=r.type,A=r.id!=null?String(r.id):"";return{message:s,conversationId:A,data:n,participant:m,context:{chatId:r.id,userId:o.id,username:o.username,firstName:o.first_name,lastName:o.last_name,messageId:i.message_id,channelType:w,channelId:A,channelName:r.title,mentions:f.length>0?f:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var q=new Set([1,3]),N=/<@!?(\d+)>/g,L="https://discord.com/api/v10",_=class extends l{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&q.has(s),o=n.author?.id,a=n.author?.globalName??n.author?.username,c=[];if(n.content){N.lastIndex=0;let m;for(;(m=N.exec(n.content))!==null;)c.push(m[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:a??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:c.length>0?c:void 0,isMentioned:this.botUserId?c.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${L}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var x=class extends l{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
1
+ "use strict";var z=Object.create;var b=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty;var q=(d,e)=>{for(var n in e)b(d,n,{get:e[n],enumerable:!0})},O=(d,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!J.call(d,i)&&i!==n&&b(d,i,{get:()=>e[i],enumerable:!(t=j(e,i))||t.enumerable});return d};var m=(d,e,n)=>(n=d!=null?z(H(d)):{},O(e||!d||!d.__esModule?b(n,"default",{value:d,enumerable:!0}):n,d)),L=d=>O(b({},"__esModule",{value:!0}),d);var Q={};q(Q,{BaseChannel:()=>l,ChatChannel:()=>I,DiscordChannel:()=>$,EmailChannel:()=>A,McpChannel:()=>E,SMSChannel:()=>M,ScheduledChannel:()=>x,SlackChannel:()=>S,TelegramChannel:()=>_,WebhookChannel:()=>T});module.exports=L(Q);var v=require("toolpack-sdk"),l=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}validateAttachments(e){if(!(!e||e.length===0)){for(let n of e)if(n.type==="file"){let{url:t,mimeType:i,size:s,name:r}=n.file,o=r??t,a=i.startsWith("image/"),c=a?v.FILE_LIMITS.image.maxBytes:v.FILE_LIMITS.document.maxBytes,g=c/(1024*1024);if(s!==void 0&&s>c)throw new Error(`Attachment "${o}" exceeds the ${a?"image":"document"} size limit of ${g} MB`)}else if(n.type==="image_data"&&Math.ceil(n.image_data.data.length*.75)>v.FILE_LIMITS.image.maxBytes){let i=v.FILE_LIMITS.image.maxBytes/1048576;throw new Error(`Inline image exceeds the size limit of ${i} MB`)}}}};var I=class extends l{isTriggerChannel=!1;constructor(e={}){super(),this.name=e.name}listen(){}async send(e){}normalize(e){let n=e,t=Array.isArray(n.attachments)?n.attachments:void 0;return this.validateAttachments(t),{message:n.message??"",attachments:t,conversationId:n.conversationId??void 0,participant:n.participant,context:{source:"chat"}}}};var P=require("crypto");var S=class extends l{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let n=e.channel;this.allowedChannels=n==null?null:Array.isArray(n)?n:[n]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SlackChannel] Listening on port ${this.config.port}`),this.runStartupCheck().catch(()=>{})})}).catch(e=>{console.error("[SlackChannel] Failed to start HTTP server:",e)})}async runStartupCheck(){try{let n=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();n.ok?(this.botUserId=n.user_id,this.botId=n.bot_id,console.log(`[SlackChannel] Connected as @${n.user} (${n.user_id}) in workspace "${n.team}" \u2014 ${n.url}`)):console.warn(`[SlackChannel] auth.test failed: ${n.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,n){let t=e["x-slack-request-timestamp"],i=e["x-slack-signature"];if(!t||!i||Array.isArray(t)||Array.isArray(i))return!1;let s=parseInt(t,10),r=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(r-s)>300)return!1;let o=`v0:${t}:${n}`,c=`v0=${(0,P.createHmac)("sha256",this.config.signingSecret).update(o).digest("hex")}`;if(c.length!==i.length)return!1;try{return(0,P.timingSafeEqual)(Buffer.from(c),Buffer.from(i))}catch{return!1}}async send(e){let n=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,i=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!i)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:i,text:e.output};n&&(s.thread_ts=n);let r=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send Slack message: ${r.statusText}`);let o=await r.json();if(!o.ok)throw new Error(`Slack API error: ${o.error}`)}normalize(e){let n=e,i=(n.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=n.ts,r=n.thread_ts,o=r!==void 0&&r!==s,a=n.user,c=a?{kind:"user",id:a}:void 0,g=/<@([A-Z0-9]+)>/g,y=[],f;for(;(f=g.exec(i))!==null;)y.push(f[1]);let w=n.channel;return{message:i,conversationId:o?r:w||s||"",data:n,participant:c,context:{user:a,channel:w,team:n.team,channelType:n.channel_type,threadId:o?r:void 0,mentions:y.length>0?y:void 0,channelId:w,channelName:typeof this.config.channel=="string"?this.config.channel:w}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.user;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(n)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!i.ok)return{kind:"user",id:n};let s=await i.json();if(!s.ok||!s.user){let a={kind:"user",id:n};return this.participantCache.set(n,a),a}let r=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||n,o={kind:"user",id:n,displayName:r,metadata:{slackUser:s.user}};return this.participantCache.set(n,o),o}catch{return{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let n=e.type;if(n!=="message"&&n!=="app_mention")return!1;if(this.allowedChannels!==null){let r=e.channel_type;if(!(r==="im"||r==="mpim")){let a=e.channel;if(!a||!this.allowedChannels.includes(a))return!1}}let t=e.user;if(this.botUserId&&t===this.botUserId)return!1;let i=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${t} bot_id=${i} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!i)return!0;if(this.botId&&i===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(i)||t!==void 0&&s.includes(t))return!1;if(this.config.allowedBotIds!==void 0){let r=this.config.allowedBotIds;return r.includes(i)||t!==void 0&&r.includes(t)}return!0}handleRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,t)){n.writeHead(401),n.end("Invalid signature");return}try{let i=JSON.parse(t);if(i.type==="url_verification"){n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({challenge:i.challenge}));return}if(i.type==="event_callback"&&i.event){let s=i.event;if(this.shouldProcessEvent(s)){let r=this.normalize(s);this.handleMessage(r)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);n.writeHead(200),n.end("OK");return}n.writeHead(200),n.end("OK")}catch(i){console.error("[SlackChannel] Error handling request:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var T=class extends l{isTriggerChannel=!1;config;server;pendingResponses=new Map;constructor(e){super(),this.name=e.name,this.config={port:e.port??3e3,path:e.path??"/webhook"}}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[WebhookChannel] Listening on port ${this.config.port}${this.config.path}`)})}).catch(e=>{console.error("[WebhookChannel] Failed to start HTTP server:",e)})}async send(e){let n=e.metadata?.conversationId;if(n&&this.pendingResponses.has(n)){let t=this.pendingResponses.get(n);this.pendingResponses.delete(n),t.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let n=e,t=n.headers||{},i=t["x-session-id"]||t["X-Session-Id"]||n.sessionId||n.conversationId||this.generateSessionId();return{message:n.message||n.text||"",intent:n.intent,conversationId:i,data:n,context:{headers:n.headers,method:n.method,sessionId:i}}}handleRequest(e,n){if(e.url!==this.config.path){n.writeHead(404),n.end("Not found");return}if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t),s=this.normalize(i),r=s.conversationId||this.generateSessionId(),o=new Promise((a,c)=>{this.pendingResponses.set(r,{resolve:a,reject:c}),setTimeout(()=>{this.pendingResponses.has(r)&&(this.pendingResponses.delete(r),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:r,context:{...s.context,sessionId:r}}),o.then(a=>{n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify(a))}).catch(a=>{n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:a.message}))})}catch(i){console.error("[WebhookChannel] Error handling request:",i),n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Bad request"}))}})}generateSessionId(){return`webhook-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var R=require("cron-parser"),x=class extends l{isTriggerChannel=!0;config;timer;_stopped=!1;_generation=0;constructor(e){if(super(),!e.cron&&!e.store)throw new Error("ScheduledChannel: provide at least one of `cron` (static schedule) or `store` (dynamic scheduling).");if(e.cron)try{R.CronExpressionParser.parse(e.cron)}catch(n){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${n.message}`)}if(e.store&&!e.name&&console.warn("[ScheduledChannel] A `store` was provided without a `name`. All store queries will be unscoped and will pick up jobs from every channel. Set `name` to scope this channel to its own jobs."),e.idlePollMs!==void 0&&e.idlePollMs<1e3)throw new Error(`ScheduledChannel: idlePollMs must be at least 1000ms (got ${e.idlePollMs}). Values below 1 second create a tight polling loop.`);this.config=e,this.name=e.name}listen(){this._generation++,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this._stopped=!1,this.config.store?this._listenWithStore():this._listenStatic()}async stop(){this._stopped=!0,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}async send(e){}normalize(e){let n=e,t=new Date,i=`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`;return{intent:n?.intent??this.config.intent,message:n?.message??this.config.message??`Scheduled task triggered at ${t.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${i}`,data:{...n?.payload??{},scheduled:!0,jobId:n?.id,cron:n?.cron??this.config.cron,timestamp:t.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let n=this._nextRunFromCron(this.config.cron),t=n.getTime()-Date.now();if(t<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${n.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},t)}async _triggerStatic(){if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Cron fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing triggers.`);return}let e=this.normalize(null);try{await this.handleMessage(e)}catch(n){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,n)}}_listenWithStore(){let e=this.config.store,n=this._generation;if(n===1){let i=e.resetStuck(this.name);i>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${i} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:i}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});i||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let t=e.getDue(Date.now(),this.name);t.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${t.length} overdue job(s).`),Promise.allSettled(t.map(i=>this._triggerJob(i)))),this._scheduleNextFromStore(n)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let n=this.config.store,t=n.getNextPending(this.name);if(!t){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let i=Math.max(0,t.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(t.nextRunAt).toISOString()} (in ${Math.round(i/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=n.getDue(Date.now(),this.name);await Promise.allSettled(s.map(r=>this._triggerJob(r))),this._scheduleNextFromStore(e)},i)}async _triggerJob(e){let n=this.config.store;if(!this._handler){console.warn(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} fired but no message handler is registered. Call onMessage() before listen() to avoid silently losing jobs.`),n.markFailed(e.id,"No message handler registered");return}n.markRunning(e.id);let t=this.normalize(e);try{await this.handleMessage(t),n.markCompleted(e.id)}catch(i){let s=i instanceof Error?i.message:String(i);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,i),n.markFailed(e.id,s)}}_nextRunFromCron(e){return R.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};var _=class extends l{isTriggerChannel=!1;config;offset=0;pollingInterval;server;botUserId;botUsername;constructor(e){super(),this.name=e.name,this.config=e}listen(){this.runStartupCheck().catch(()=>{}),this.config.webhookUrl?this.startWebhook():this.startPolling()}async runStartupCheck(){try{let n=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(n.ok&&n.result){let t=n.result;this.botUserId=t.id!=null?String(t.id):void 0,this.botUsername=t.username,console.log(`[TelegramChannel] Connected as @${t.username} (id: ${t.id}, name: ${t.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${n.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let n=e.metadata?.chatId;if(!n)throw new Error("Telegram send requires chatId in metadata");let t=e.metadata?.replyMarkup,i=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:n,text:e.output,parse_mode:"Markdown",...t?{reply_markup:t}:{}})});if(!i.ok)throw new Error(`Failed to send Telegram message: ${i.statusText}`);let s=await i.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,n){let t=await fetch(`https://api.telegram.org/bot${this.config.token}/answerCallbackQuery`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callback_query_id:e,...n?{text:n}:{}})});if(!t.ok)throw new Error(`Failed to answer Telegram callback query: ${t.statusText}`);let i=await t.json();if(!i.ok)throw new Error(`Telegram API error: ${i.description}`)}normalize(e){let n=e,t=n.callback_query;if(t){let C=t.message||{},u=C.chat||{},p=t.from||{},k=p.id!=null?String(p.id):void 0,U=p.first_name||p.username||k,F=k?{kind:"user",id:k,displayName:U??k}:void 0,N=u.id!=null?String(u.id):"";return{message:t.data??"",conversationId:N,data:n,participant:F,context:{isCallback:!0,callbackQueryId:t.id,callbackData:t.data,chatId:u.id,userId:p.id,username:p.username,firstName:p.first_name,lastName:p.last_name,messageId:C.message_id,channelType:u.type,channelId:N,channelName:u.title}}}let i=n.message||n.edited_message||{},s=i.text||"",r=i.chat||{},o=i.from||{},a=o.id!=null?String(o.id):void 0,c=o.first_name||o.username||a,g=a?{kind:"user",id:a,displayName:c??a}:void 0,y=i.entities??[],f=[];for(let C of y)if(C.type==="text_mention"&&C.user){let u=C.user;u.id!=null&&f.push(String(u.id))}let w=r.type,D=r.id!=null?String(r.id):"";return{message:s,conversationId:D,data:n,participant:g,context:{chatId:r.id,userId:o.id,username:o.username,firstName:o.first_name,lastName:o.last_name,messageId:i.message_id,channelType:w,channelId:D,channelName:r.title,mentions:f.length>0?f:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,n=await fetch(e);if(!n.ok)throw new Error(`Telegram getUpdates failed: ${n.statusText}`);let t=await n.json();if(!t.ok)throw new Error("Telegram getUpdates returned not ok");for(let i of t.result){let s=i.update_id;s>=this.offset&&(this.offset=s+1);try{let r=this.normalize(i);await this.handleMessage(r)}catch(r){console.error("[TelegramChannel] Error processing update:",r)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((i,s)=>{this.handleWebhookRequest(i,s)});let n=new URL(this.config.webhookUrl||"http://localhost:3000"),t=parseInt(n.port,10)||3e3;this.server.listen(t,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${t}`)}),this.setWebhook()}).catch(e=>{console.error("[TelegramChannel] Failed to start webhook server:",e)}))}async setWebhook(){if(!this.config.webhookUrl)return;let e=await fetch(`https://api.telegram.org/bot${this.config.token}/setWebhook`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:this.config.webhookUrl})});if(!e.ok){console.error("[TelegramChannel] Failed to set webhook");return}let n=await e.json();n.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",n.description)}handleWebhookRequest(e,n){if(e.method!=="POST"){n.writeHead(405),n.end("Method not allowed");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=JSON.parse(t);this.handleMessage(this.normalize(i)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),n.writeHead(200),n.end("OK")}catch(i){console.error("[TelegramChannel] Error parsing webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=void 0),this.server)return new Promise(e=>{this.server.close(e)});if(this.config.webhookUrl)try{await fetch(`https://api.telegram.org/bot${this.config.token}/deleteWebhook`,{method:"POST"})}catch(e){console.error("[TelegramChannel] Failed to delete webhook:",e)}}};var G=new Set([1,3]),B=/<@!?(\d+)>/g,K="https://discord.com/api/v10",$=class extends l{isTriggerChannel=!1;config;allowedChannelIds;botUserId;participantCache=new Map;client;constructor(e){super(),this.config=e,this.name=e.name,e.channelId==null?this.allowedChannelIds=new Set:Array.isArray(e.channelId)?this.allowedChannelIds=new Set(e.channelId):this.allowedChannelIds=new Set([e.channelId])}shouldProcessEvent(e){return!e.author||e.webhookId||this.botUserId&&e.author.id===this.botUserId||this.config.guildId&&e.guildId!==this.config.guildId||this.allowedChannelIds.size>0&&(!e.channelId||!this.allowedChannelIds.has(e.channelId))?!1:e.author.bot||e.author.system?this.config.blockedBotIds?.includes(e.author.id)?!1:this.config.allowedBotIds?this.config.allowedBotIds.includes(e.author.id):!1:!0}normalize(e){let n=e,t=n.channelId,i=(t??"")+(n.thread?.id?`:${n.thread.id}`:""),s=n.channel?.type,r=s!==void 0&&G.has(s),o=n.author?.id,a=n.author?.globalName??n.author?.username,c=[];if(n.content){B.lastIndex=0;let g;for(;(g=B.exec(n.content))!==null;)c.push(g[1])}return{message:n.content,conversationId:i,data:n,participant:o?{kind:"user",id:o,displayName:a??void 0}:void 0,context:{userId:o,username:n.author?.username,channelType:r?"dm":"channel",channelId:t,channelName:n.channel?.name,guildId:n.guildId,threadId:n.thread?.id,messageId:n.id,mentions:c.length>0?c:void 0,isMentioned:this.botUserId?c.includes(this.botUserId):void 0}}}async resolveParticipant(e){let n=e.participant?.id??e.context?.userId;if(!n)return;let t=this.participantCache.get(n);if(t)return t;try{let i=await fetch(`${K}/users/${n}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!i.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${n}: HTTP ${i.status}`),{kind:"user",id:n};let s=await i.json(),r=s.global_name??s.username,o={kind:"user",id:s.id,displayName:r};return this.participantCache.set(n,o),o}catch(i){return console.warn(`[DiscordChannel] resolveParticipant error for ${n}:`,i),{kind:"user",id:n}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let n=e.metadata?.threadId;if(n){let s=await this.client.channels.fetch(n);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(r){throw console.error("[DiscordChannel] Failed to send to thread:",r),new Error(`[DiscordChannel] Failed to send Discord message: ${r instanceof Error?r.message:String(r)}`)}console.warn(`[DiscordChannel] Thread ${n} not found or not sendable; falling back to channel send.`)}let t=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!t)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let i=await this.client.channels.fetch(t);if(!i||!("send"in i))throw new Error(`[DiscordChannel] Channel ${t} not found or is not a text channel`);try{await i.send({content:e.output})}catch(s){throw console.error("[DiscordChannel] Failed to send to channel:",s),new Error(`[DiscordChannel] Failed to send Discord message: ${s instanceof Error?s.message:String(s)}`)}}listen(){typeof process>"u"||import("discord.js").then(e=>{let{Client:n,GatewayIntentBits:t}=e;this.client=new n({intents:[t.Guilds,t.GuildMessages,t.MessageContent,t.DirectMessages]}),this.client.on("ready",()=>{let i=this.client.user;this.botUserId=i?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),r=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${i?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${r} | channels=${s}`)}),this.client.on("messageCreate",i=>{let s=i;if(!this.shouldProcessEvent(s))return;let r=this.normalize(s);this.handleMessage(r)}),this.client.on("userUpdate",(i,s)=>{let r=s;r?.id&&this.invalidateParticipant(r.id)}),this.client.login(this.config.token).catch(i=>{console.error("[DiscordChannel] Failed to login to Discord:",i)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};var A=class extends l{isTriggerChannel=!0;config;transporter;constructor(e){super(),this.config=e,this.name=e.name}listen(){typeof process<"u"&&import("nodemailer").then(e=>{this.transporter=e.default.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure??this.config.smtp.port===465,auth:{user:this.config.smtp.auth.user,pass:this.config.smtp.auth.pass}}),console.log(`[EmailChannel] Email transporter initialized for ${this.config.from}`)}).catch(e=>{console.error("[EmailChannel] Failed to initialize nodemailer:",e),console.error("[EmailChannel] Make sure to install nodemailer: npm install nodemailer")})}async send(e){if(!this.transporter)throw new Error("Email transporter not initialized. Did you call listen()?");let n=Array.isArray(this.config.to)?this.config.to:[this.config.to],t=this.config.subject||"Message from Agent",i={from:this.config.from,to:n.join(", "),subject:t,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(i)}catch(s){throw console.error("[EmailChannel] Failed to send email:",s),new Error(`Failed to send email: ${s instanceof Error?s.message:String(s)}`)}}normalize(e){throw new Error("EmailChannel is outbound-only. Use WebhookChannel with email webhook events for inbound email.")}formatAsHtml(e){return e.split(`
2
2
 
3
- `).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var $=class extends l{config;twilioClient;server;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name}get isTriggerChannel(){return!this.config.webhookPath}listen(){typeof process<"u"&&import("twilio").then(e=>{this.twilioClient=e.default(this.config.accountSid,this.config.authToken),console.log("[SMSChannel] Twilio client initialized"),this.config.webhookPath&&this.startWebhookServer()}).catch(e=>{console.error("[SMSChannel] Failed to initialize Twilio client:",e),console.error("[SMSChannel] Make sure to install twilio: npm install twilio")})}async send(e){if(!this.twilioClient)throw new Error("Twilio client not initialized. Did you call listen()?");let n=e.metadata?.from||this.config.to;if(!n)throw new Error('No recipient phone number specified. Set "to" in config or provide in output.metadata.from');try{await this.twilioClient.messages.create({body:e.output,from:this.config.from,to:n})}catch(t){throw console.error("[SMSChannel] Failed to send SMS:",t),new Error(`Failed to send SMS: ${t instanceof Error?t.message:String(t)}`)}}normalize(e){let n=e,t=n.From,i=n.Body,s=n.MessageSid;return{message:i,conversationId:t,data:n,context:{from:t,to:n.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleWebhookRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SMSChannel] Webhook server listening on port ${this.config.port} at ${this.config.webhookPath}`)})}).catch(e=>{console.error("[SMSChannel] Failed to start webhook server:",e)})}handleWebhookRequest(e,n){if(e.method!=="POST"||e.url!==this.config.webhookPath){n.writeHead(404),n.end("Not found");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=new URLSearchParams(t),s={};i.forEach((o,a)=>{s[a]=o});let r=this.normalize(s);this.handleMessage(r),n.writeHead(200,{"Content-Type":"text/xml"}),n.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(i){console.error("[SMSChannel] Error handling webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var M=class extends l{isTriggerChannel=!1;_timeout;_pendingResolve;constructor(e={}){super(),this._timeout=e.timeout??12e4}listen(){}async send(e){this._pendingResolve?.(e),this._pendingResolve=void 0}normalize(e){let n=e;return{message:typeof n.message=="string"?n.message:JSON.stringify(n),data:n,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let n=this.normalize(e);return new Promise((t,i)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,i(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=r=>{clearTimeout(s),t(r.output)},this.handleMessage(n).catch(r=>{clearTimeout(s),this._pendingResolve=void 0,i(r instanceof Error?r:new Error(String(r)))})})}asAgentDefinition(e,n){return{name:e.name,description:e.description,...n!==void 0&&{inputSchema:n},invoke:t=>this.trigger(t)}}};0&&(module.exports={BaseChannel,DiscordChannel,EmailChannel,McpChannel,SMSChannel,ScheduledChannel,SlackChannel,TelegramChannel,WebhookChannel});
3
+ `).map(n=>`<p>${n.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};var M=class extends l{config;twilioClient;server;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name}get isTriggerChannel(){return!this.config.webhookPath}listen(){typeof process<"u"&&import("twilio").then(e=>{this.twilioClient=e.default(this.config.accountSid,this.config.authToken),console.log("[SMSChannel] Twilio client initialized"),this.config.webhookPath&&this.startWebhookServer()}).catch(e=>{console.error("[SMSChannel] Failed to initialize Twilio client:",e),console.error("[SMSChannel] Make sure to install twilio: npm install twilio")})}async send(e){if(!this.twilioClient)throw new Error("Twilio client not initialized. Did you call listen()?");let n=e.metadata?.from||this.config.to;if(!n)throw new Error('No recipient phone number specified. Set "to" in config or provide in output.metadata.from');try{await this.twilioClient.messages.create({body:e.output,from:this.config.from,to:n})}catch(t){throw console.error("[SMSChannel] Failed to send SMS:",t),new Error(`Failed to send SMS: ${t instanceof Error?t.message:String(t)}`)}}normalize(e){let n=e,t=n.From,i=n.Body,s=n.MessageSid;return{message:i,conversationId:t,data:n,context:{from:t,to:n.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((n,t)=>{this.handleWebhookRequest(n,t)}),this.server.listen(this.config.port,()=>{console.log(`[SMSChannel] Webhook server listening on port ${this.config.port} at ${this.config.webhookPath}`)})}).catch(e=>{console.error("[SMSChannel] Failed to start webhook server:",e)})}handleWebhookRequest(e,n){if(e.method!=="POST"||e.url!==this.config.webhookPath){n.writeHead(404),n.end("Not found");return}let t="";e.on("data",i=>{t+=i.toString()}),e.on("end",()=>{try{let i=new URLSearchParams(t),s={};i.forEach((o,a)=>{s[a]=o});let r=this.normalize(s);this.handleMessage(r),n.writeHead(200,{"Content-Type":"text/xml"}),n.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(i){console.error("[SMSChannel] Error handling webhook:",i),n.writeHead(400),n.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};var E=class extends l{isTriggerChannel=!1;_timeout;_pendingResolve;constructor(e={}){super(),this._timeout=e.timeout??12e4}listen(){}async send(e){this._pendingResolve?.(e),this._pendingResolve=void 0}normalize(e){let n=e;return{message:typeof n.message=="string"?n.message:JSON.stringify(n),data:n,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let n=this.normalize(e);return new Promise((t,i)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,i(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=r=>{clearTimeout(s),t(r.output)},this.handleMessage(n).catch(r=>{clearTimeout(s),this._pendingResolve=void 0,i(r instanceof Error?r:new Error(String(r)))})})}asAgentDefinition(e,n){return{name:e.name,description:e.description,...n!==void 0&&{inputSchema:n},invoke:t=>this.trigger(t)}}};0&&(module.exports={BaseChannel,ChatChannel,DiscordChannel,EmailChannel,McpChannel,SMSChannel,ScheduledChannel,SlackChannel,TelegramChannel,WebhookChannel});
@@ -1,4 +1,4 @@
1
- export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-a2wZU6Eu.cjs';
2
- import '../types-CJinv165.cjs';
1
+ export { B as BaseChannel, C as ChatChannel, a as ChatChannelConfig, D as DiscordChannel, d as DiscordChannelConfig, E as EmailChannel, e as EmailChannelConfig, M as McpChannel, f as McpChannelConfig, g as SMSChannel, h as SMSChannelConfig, i as ScheduledChannel, j as ScheduledChannelConfig, l as SlackChannel, m as SlackChannelConfig, T as TelegramChannel, n as TelegramChannelConfig, W as WebhookChannel, o as WebhookChannelConfig } from '../index-Cuyk9sbf.cjs';
2
+ import '../types-D5dxhUX8.cjs';
3
3
  import 'toolpack-sdk';
4
4
  import 'events';
@@ -1,4 +1,4 @@
1
- export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-DQuf4mxT.js';
2
- import '../types-CJinv165.js';
1
+ export { B as BaseChannel, C as ChatChannel, a as ChatChannelConfig, D as DiscordChannel, d as DiscordChannelConfig, E as EmailChannel, e as EmailChannelConfig, M as McpChannel, f as McpChannelConfig, g as SMSChannel, h as SMSChannelConfig, i as ScheduledChannel, j as ScheduledChannelConfig, l as SlackChannel, m as SlackChannelConfig, T as TelegramChannel, n as TelegramChannelConfig, W as WebhookChannel, o as WebhookChannelConfig } from '../index-Bd2nQrax.js';
2
+ import '../types-D5dxhUX8.js';
3
3
  import 'toolpack-sdk';
4
4
  import 'events';