@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.
package/dist/index.cjs CHANGED
@@ -1,48 +1,48 @@
1
- "use strict";var an=Object.create;var xe=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var dn=Object.getOwnPropertyNames;var ln=Object.getPrototypeOf,pn=Object.prototype.hasOwnProperty;var N=(o,e)=>()=>(o&&(e=o(o=0)),e);var it=(o,e)=>{for(var t in e)xe(o,t,{get:e[t],enumerable:!0})},Mt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of dn(e))!pn.call(o,r)&&r!==t&&xe(o,r,{get:()=>e[r],enumerable:!(n=cn(e,r))||n.enumerable});return o};var j=(o,e,t)=>(t=o!=null?an(ln(o)):{},Mt(e||!o||!o.__esModule?xe(t,"default",{value:o,enumerable:!0}):t,o)),un=o=>Mt(xe({},"__esModule",{value:!0}),o);var c=N(()=>{"use strict"});function L(o){return o===H}function oe(){return H}var H,Q=N(()=>{"use strict";c();H=Symbol("interceptor-skip-sentinel")});function ie(o,e,t,n,r={}){let s=r.maxInvocationDepth??5;return{async execute(i){let l=(p=>({agent:e,channel:t,registry:n,invocationDepth:p,delegateAndWait:async(g,u)=>{let m=p+1;if(m>s)throw new Z(m,s);if(!n)throw new Error(`Cannot delegate to "${g}": agent is running in standalone mode without a registry`);let w=n.getAgent(g);if(!w)throw new Error(`Agent "${g}" not found for delegation`);let y={message:u.message??"",intent:u.intent,data:u.data,context:u.context,conversationId:u.conversationId??i.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(y)},skip:oe}))(0),d=async p=>{let g=p??i;return await e.invokeAgent(g)};for(let p=o.length-1;p>=0;p--){let g=o[p],u=d;d=async m=>await g(m??i,l,u)}return await d()}}}async function ae(o,e){let t=await o.execute(e);return t===H?null:t}var Z,at=N(()=>{"use strict";c();Q();Z=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function gn(o){let e=o.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function ee(o){let e=o.captureAgentReplies??!0,t=o.getScope??gn,n=o.getMessageId??(i=>i.context?.messageId??i.context?.eventId??(0,ct.randomUUID)()),r=o.getMentions??(i=>i.context?.mentions??[]),s=async(i,a,l)=>{let d=i.conversationId;if(!d)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await l();let p=i.participant;if(p){let u={id:n(i),conversationId:d,participant:p,content:i.message??"",timestamp:new Date().toISOString(),scope:t(i),metadata:{channelType:i.context?.channelType,threadId:i.context?.threadId,messageId:i.context?.messageId,mentions:r(i),channelName:i.context?.channelName,channelId:i.context?.channelId}};try{await o.store.append(u),o.onCaptured?.(u),a.logger?.debug("[capture-history] Captured inbound message",{messageId:u.id,participantId:p.id,conversationId:d})}catch(m){a.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let g=await l();if(e&&!L(g)&&g.output!=null){let u={kind:"agent",id:a.agent.name,displayName:a.agent.name},m={id:(0,ct.randomUUID)(),conversationId:d,participant:u,content:g.output,timestamp:new Date().toISOString(),scope:t(i),metadata:{channelType:i.context?.channelType,threadId:i.context?.threadId,channelName:i.context?.channelName,channelId:i.context?.channelId}};try{await o.store.append(m),o.onCaptured?.(m),a.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:a.agent.name,conversationId:d})}catch(w){a.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return g};return s[ce]=!0,s}var ct,ce,dt=N(()=>{"use strict";c();ct=require("crypto");Q();ce=Symbol.for("toolpack:capture-history")});function Dt(o){return Math.ceil(o.length/4)}function mn(o){return{id:o.id,participant:o.participant,content:o.content,timestamp:o.timestamp}}function hn(o,e){let{participant:t,content:n}=o;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 fn(o,e,t){return!!(o.participant.id===e||o.metadata?.mentions?.some(n=>t.has(n)))}async function de(o,e,t,n,r={},s){let{scope:i,addressedOnlyMode:a=!0,tokenBudget:l=3e3,rollingSummaryThreshold:d=40,timeWindowMinutes:p,maxTurnsToLoad:g=100,agentAliases:u}=r,m=new Set([t,...u??[]]),w=p!==void 0?new Date(Date.now()-p*60*1e3).toISOString():void 0,y=await o.get(e,{scope:i,sinceTimestamp:w,limit:g}),v=y.length;if(a){let k=new Set;for(let D=0;D<y.length;D++){let C=y[D];if(fn(C,t,m)&&k.add(C.id),D<y.length-1){let M=y[D+1];M.participant.kind==="agent"&&M.participant.id===t&&k.add(C.id)}}let _=y[y.length-1];_&&k.add(_.id),y=y.filter(D=>k.has(D.id))}let A=!1;if(y.length>d&&s){let k=Math.floor(y.length/2),_=y.slice(0,k),D=y.slice(k),C=_.filter(M=>!M.metadata?.isSummary);try{let M=await s.invokeAgent({message:"summarize",data:{turns:C.map(mn),agentName:n,agentId:t,maxTokens:Math.floor(l*.25),extractDecisions:!0}}),G=JSON.parse(M.output),z={id:`summary-${(0,Nt.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${G.turnsSummarized} earlier turns]: ${G.summary}`,timestamp:_[0].timestamp,scope:i??"channel",metadata:{isSummary:!0}};y=[z,...D],A=!0;try{await o.append(z),await o.deleteMessages(e,_.map(O=>O.id))}catch{}}catch{y=y.slice(-d)}}else y.length>d&&(y=y.slice(-d));let b=y.map(k=>hn(k,t));if(b.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:v,hasSummary:A};let S=b[b.length-1],I=[S],P=Dt(S.content);for(let k=b.length-2;k>=0;k--){let _=b[k],D=Dt(_.content);if(P+D>l)break;I.unshift(_),P+=D}return{messages:I,estimatedTokens:P,turnsLoaded:v,hasSummary:A}}var Nt,lt=N(()=>{"use strict";c();Nt=require("crypto")});var R,le=N(()=>{"use strict";c();R=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var Se,pt,ut,gt,mt,ht,h,Te,Ot=N(()=>{"use strict";c();Se=require("crypto"),pt=.6,ut=.2,gt=.2,mt={low:.3,medium:.6,high:1},ht=30,h={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"},Te=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[h.type]==="goal"&&t[h.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,n)=>{let r={high:0,normal:1,low:2},s=r[t.priority]-r[n.priority];return s!==0?s:t.createdAt-n.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[h.type]==="goal"&&t[h.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[h.type]==="reflection"&&t[h.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[h.type]==="reflection"&&t[h.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(r=>r[h.type]==="belief"&&r[h.confidence]==="high"&&!r[h.error]&&!(r[h.expiresAt]&&r[h.expiresAt]<t))).map(r=>{let s=this.chunkToBelief(r),i=(t-s.createdAt)/864e5,l=Math.exp(-i/ht)*ut+mt.high*gt+pt;return{...s,score:l}}).sort((r,s)=>s.score-r.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[h.type]==="reflection"&&!s[h.pinned]&&!s[h.error]&&s[h.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,i)=>i.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:r="active",tags:s}=t,i;if(e.trim()&&typeof this.provider.keywordQuery=="function")i=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[h.type]:"goal",[h.status]:r}})).map(l=>this.chunkToGoal(l.chunk));else{let a=r;if(i=(await this._getAllByMeta(d=>d[h.type]==="goal"&&d[h.status]===a)).map(d=>this.chunkToGoal(d)),e.trim()){let d=e.toLowerCase();i=i.filter(p=>p.description.toLowerCase().includes(d))}}return s?.length&&(i=i.filter(a=>s.every(l=>a.tags.includes(l)))),i.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:r=0,tags:s,includeExpired:i=!1}=t,a=Date.now(),l=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[h.type]:"belief"}}),d=[];for(let p of l){let g=this.chunkToBelief(p.chunk);if(!i&&g.expiresAt&&g.expiresAt<a||s?.length&&!s.every(v=>g.tags.includes(v)))continue;let u=(a-g.createdAt)/864e5,m=Math.exp(-u/ht),w=g.error?.3:mt[g.confidence],y=p.score*pt+m*ut+w*gt;y<r||d.push({...g,score:y})}return d.sort((p,g)=>g.score-p.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:r=0,tags:s,pinned:i}=t,a=Date.now(),l={[h.type]:"reflection"};i===!0&&(l[h.pinned]=!0);let d=await this.provider.query(e,{limit:n*4,threshold:0,filter:l}),p=[];for(let g of d){let u=this.chunkToReflection(g.chunk);if(i===!1&&u.pinned||s?.length&&!s.every(v=>u.tags.includes(v)))continue;let m=(a-u.createdAt)/864e5,w=Math.exp(-m/ht),y=g.score*pt+w*ut+mt.medium*gt;y<r||p.push({...u,score:y})}return p.sort((g,u)=>u.score-g.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),r=await this.provider.query(e,{limit:5,threshold:t,filter:{[h.type]:"belief"}});for(let s of r){let i=this.chunkToBelief(s.chunk);if(!(i.expiresAt&&i.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:i}}return null}async addGoal(e){let t=(0,Se.randomUUID)();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 r=this.chunkToGoal(n),s={...r,description:t.description??r.description,priority:t.priority??r.priority,status:t.status??r.status,outcome:t.outcome??r.outcome,progress:t.appendProgress?[...r.progress,t.appendProgress]:r.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 r=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...r,status:"completed",outcome:t??r.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=(0,Se.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let r=await this._getById(e);if(!r)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(r),i={...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()},a=n??r.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(i,a)])}async addReflection(e,t){let n=(0,Se.randomUUID)();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 r=this.chunkToReflection(n),s={...r,pinned:t.pinned??r.pinned,error:t.error??r.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:{[h.type]:"goal",[h.status]:e.status,[h.priority]:e.priority,[h.tags]:JSON.stringify(e.tags),[h.progress]:JSON.stringify(e.progress),[h.dueBy]:e.dueBy??"",[h.outcome]:e.outcome??"",[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[h.status],priority:t[h.priority],tags:this._parseTags(t[h.tags]),progress:this._parseTags(t[h.progress]),dueBy:t[h.dueBy]||void 0,outcome:t[h.outcome]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[h.type]:"belief",[h.confidence]:e.confidence,[h.tags]:JSON.stringify(e.tags),[h.expiresAt]:e.expiresAt??0,[h.error]:e.error===!0,[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[h.confidence],tags:this._parseTags(t[h.tags]),expiresAt:t[h.expiresAt]||void 0,error:t[h.error]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[h.type]:"reflection",[h.pinned]:e.pinned,[h.tags]:JSON.stringify(e.tags),[h.relatedTo]:e.relatedTo??"",[h.error]:e.error===!0,[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[h.pinned],tags:this._parseTags(t[h.tags]),relatedTo:t[h.relatedTo]||void 0,error:t[h.error]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.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 ft(o){let e=o.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${o}". 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 $t(o){if(/^\d{4}-\d{2}-\d{2}/.test(o))return o;let e=ft(o);return new Date(Date.now()+e).toISOString().slice(0,10)}function jt(o,e){let t=0,n=0,r=0;for(let i=0;i<o.length;i++)t+=o[i]*e[i],n+=o[i]*o[i],r+=e[i]*e[i];let s=Math.sqrt(n)*Math.sqrt(r);return s===0?0:t/s}function yt(o){return Math.ceil(o.length/4)}var vt=N(()=>{"use strict";c()});var Bt,_e,Lt=N(()=>{"use strict";c();Bt=require("crypto");vt();_e=class{constructor(e,t,n,r,s,i,a){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=r;this.committedGoalCount=s;this.committedPinnedReflectionCount=i;this.inFlightBeliefs=a}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),r,s=e.expiresIn??e.ttlDefault;s&&(r=t+ft(s));let i=this._findSimilarInDraft(n);if(i!==null){let p=this.ops[i],g=e.confidence,u=p.confidence,m={low:0,medium:1,high:2},w=m[g]>m[u]||e.allowDowngrade&&m[g]<m[u];return this.ops[i]={...p,content:e.content,confidence:w?g:u,tags:e.tags.length>0?e.tags:p.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:p.existingId??`draft-${i}`}}let a=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(a))return{action:"updated_draft",id:"in-flight-dedup"};let l=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(l){let p=l.belief,g=e.confidence,u=p.confidence,m={low:0,medium:1,high:2},w=m[g]>m[u]||e.allowDowngrade&&m[g]<m[u],y={op:"believe",content:e.content,confidence:w?g:u,tags:e.tags.length>0?e.tags:p.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:l.id};return this.ops.push(y),{action:"updated_store",id:l.id}}this.inFlightBeliefs.add(a);let d={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(d),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let i=this.totalPinnedReflectionCount;if(i>=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.`);i>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${i+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),r={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(r),{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?$t(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Bt.randomUUID)(),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 r=n;this.inFlightBeliefs.delete(r.content.trim().toLowerCase()),e?r.existingId?await this.store.updateBelief(r.existingId,{content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,error:!0},r.vector):await this.store.addBelief({type:"belief",content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,error:!0,createdAt:r.createdAt,updatedAt:t},r.vector):r.existingId?await this.store.updateBelief(r.existingId,{content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt},r.vector):await this.store.addBelief({type:"belief",content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,createdAt:r.createdAt,updatedAt:t},r.vector)}else if(n.op==="reflect"){let r=n;if(r.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:r.content,pinned:r.pinned,tags:r.tags,relatedTo:r.relatedTo,error:e||void 0,createdAt:r.createdAt,updatedAt:t},r.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 r=n;await this.store.updateGoal(r.id,{description:r.description,priority:r.priority,appendProgress:r.progress})}}else if(n.op==="unpin_reflection"&&!e){let r=n;await this.store.updateReflection(r.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,r)=>({op:n,idx:r})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:r}of t){let s=n;if(s.vector.length===0)continue;if(jt(e,s.vector)>=this.deduplicationThreshold)return r}return null}}});function Ft(o,e,t){return[yn(o,t),vn(o,e,t),wn(e,t),An(e),bn(e,t),In(o,e),Cn(o)]}function yn(o,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??""),r=t.type??"all",s=t.status??"active",i=Array.isArray(t.tags)?t.tags.map(String):void 0,a=typeof t.pinned=="boolean"?t.pinned:void 0,l=t.includeExpired===!0,d=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,p=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,g=[],m=(r==="belief"||r==="reflection"||r==="all")&&n.trim()?await o.embed(n):null;if(r==="goal"||r==="all"){let w=await o.keywordSearchGoals(n,{limit:p,status:s,tags:i});for(let y of w)g.push(kn(y))}if(m&&(r==="belief"||r==="all")){let w=await o.queryBeliefs(m,{limit:p,threshold:d,tags:i,includeExpired:l});for(let y of w)g.push(Rn(y))}if(m&&(r==="reflection"||r==="all")){let w=await o.queryReflections(m,{limit:p,threshold:d,tags:i,pinned:a});for(let y of w)g.push(xn(y))}return g}}}function vn(o,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 wn(o,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 o.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 An(o){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=>(o.addUnpinReflection(String(e.id)),{status:"ok"})}}function bn(o,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",...o.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 In(o,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 Cn(o){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 o.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function kn(o){return{id:o.id,type:"goal",content:o.description,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,priority:o.priority,status:o.status,progress:o.progress,outcome:o.outcome,dueBy:o.dueBy}}function Rn(o){return{id:o.id,type:"belief",content:o.content,score:o.score,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,confidence:o.confidence,expiresAt:o.expiresAt,error:o.error}}function xn(o){return{id:o.id,type:"reflection",content:o.content,score:o.score,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,pinned:o.pinned,relatedTo:o.relatedTo,error:o.error}}var Ut=N(()=>{"use strict";c()});async function Gt(o,e){let[t,n,r,s]=await Promise.all([o.getActiveGoals(),o.getPinnedReflections(),o.getHighConfidenceBeliefs(20),o.getRecentReflections(e.recencyWindowDays,3)]),i=t.map(g=>Sn(g)),a=n.map(g=>`- ${g.content}`),{beliefLines:l,reflectionLines:d}=Tn(r,s,e.tokenBudget);if(i.length===0&&a.length===0&&l.length===0&&d.length===0)return"";let p=["--- AGENT MIND ---",""];return i.length>0&&(p.push("## Goals"),p.push(...i),p.push("")),a.length>0&&(p.push("## Standing Rules (Pinned)"),p.push(...a),p.push("")),l.length>0&&(p.push("## Beliefs"),p.push(...l),p.push("")),d.length>0&&(p.push("## Recent Reflections"),p.push(...d),p.push("")),p.push("---"),p.join(`
2
- `)}function Sn(o){let e=o.progress[o.progress.length-1],t=`[${o.priority}] ${o.description}`;return e&&(t+=` \u2014 last progress: ${e}`),o.dueBy&&(t+=` (due: ${o.dueBy})`),t}function Tn(o,e,t){let n=t,r=[],s=[];for(let i of o){let a=`- ${i.content} (${i.confidence} confidence)`,l=yt(a);if(l>n)break;r.push(a),n-=l}for(let i of e){let l=`- [${new Date(i.createdAt).toISOString().slice(0,10)}] ${i.content}`,d=yt(l);if(d>n)break;s.push(l),n-=d}return{beliefLines:r,reflectionLines:s}}var Jt=N(()=>{"use strict";c();vt()});var qt={};it(qt,{AgentMind:()=>pe});function Bn(o,e){let t=Math.min(e.maxGoals??Pn,$n),n=Math.min(e.maxPinnedReflections??Mn,jn);return{tokenBudget:e.tokenBudget??_n,recencyWindowDays:e.recencyWindowDays??En,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??Dn,retrievalThreshold:e.retrievalThreshold??Nn,ttlDefaults:{belief:e.ttlDefaults?.belief??On,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${o}`}}var _n,En,Pn,Mn,Dn,Nn,On,$n,jn,pe,wt=N(()=>{"use strict";c();Ot();Lt();Ut();Jt();_n=300,En=7,Pn=10,Mn=10,Dn=.85,Nn=.35,On="30d",$n=10,jn=10,pe=class o{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:i}=await import("@toolpack-sdk/knowledge"),a=t.namespace??`mind/${e}`;n=new i({namespace:a})}let r=Bn(e,t),s=new Te(n,t.embedder);return await s.initialize(),new o(s,r)}async createRunContext(){let[e,t,n]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),Gt(this.store,this.config)]),r=new _e(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Ft(this.store,r,this.config);return{mindHeader:n,tools:s,flush:async a=>{a?await r.flushOnError():await r.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var At={};it(At,{EphemeralAgent:()=>ue});var ue,Ee=N(()=>{"use strict";c();F();ue=class extends T{name;description;mode;constructor(e,t,n,r){super(r),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})}}});var zt,Wt,U,T,F=N(()=>{"use strict";c();zt=require("events"),Wt=require("async_hooks"),U=require("toolpack-sdk");at();dt();lt();le();T=class extends zt.EventEmitter{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.AsyncLocalStorage;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new U.InMemoryConversationStore,"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 U.Toolpack.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(()=>(wt(),qt));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 r=n?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:r}),this.emit("agent:start",{message:e}),await this._ensureMind();let s,i="",a=[];if(this._mind){let l=await this._mind.createRunContext();i=l.mindHeader,a=l.tools,s=l.flush}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let l=[];if(i&&l.push({role:"system",content:i}),r)try{let v=await de(this.conversationHistory,r,this.name,this.name,this._resolveAssemblerOptions()),A=v.messages[v.messages.length-1],b=e.trim(),I=b!==""&&A?.role==="user"&&typeof A.content=="string"&&(A.content===b||A.content.endsWith(`: ${b}`))?v.messages.slice(0,-1):v.messages;l.push(...I)}catch{}e.trim()&&l.push({role:"user",content:e});let d=[...a];if(r){let v=this.conversationHistory;d.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 b=await v.search(r,String(A.query??""),{limit:typeof A.limit=="number"?A.limit:5});return{results:b.map(S=>({role:S.participant.kind==="agent"?"assistant":"user",content:S.content,timestamp:S.timestamp})),count:b.length}}})}if(this.delegation?.enabled&&this._registry){let v=this.delegation.allowedAgents,A=this._registry.getAllAgents().filter(b=>b.name!==this.name&&(v===void 0||v.includes(b.name)));if(A.length>0){let b=A.map(I=>I.name),S=A.map(I=>`- ${I.name}: ${I.description}`).join(`
3
- `);this.delegation.mode==="forget"?d.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.
1
+ "use strict";var ln=Object.create;var Te=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,mn=Object.prototype.hasOwnProperty;var D=(o,e)=>()=>(o&&(e=o(o=0)),e);var dt=(o,e)=>{for(var t in e)Te(o,t,{get:e[t],enumerable:!0})},Ot=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of un(e))!mn.call(o,r)&&r!==t&&Te(o,r,{get:()=>e[r],enumerable:!(n=pn(e,r))||n.enumerable});return o};var $=(o,e,t)=>(t=o!=null?ln(gn(o)):{},Ot(e||!o||!o.__esModule?Te(t,"default",{value:o,enumerable:!0}):t,o)),hn=o=>Ot(Te({},"__esModule",{value:!0}),o);var c=D(()=>{"use strict"});function B(o){return o===H}function ie(){return H}var H,Z=D(()=>{"use strict";c();H=Symbol("interceptor-skip-sentinel")});function ae(o,e,t,n,r={}){let s=r.maxInvocationDepth??5;return{async execute(i){let d=(l=>({agent:e,channel:t,registry:n,invocationDepth:l,delegateAndWait:async(g,u)=>{let m=l+1;if(m>s)throw new ee(m,s);if(!n)throw new Error(`Cannot delegate to "${g}": agent is running in standalone mode without a registry`);let v=n.getAgent(g);if(!v)throw new Error(`Agent "${g}" not found for delegation`);let y={message:u.message??"",intent:u.intent,data:u.data,context:u.context,conversationId:u.conversationId??i.conversationId??`delegation-${Date.now()}`};return await v.invokeAgent(y)},skip:ie}))(0),p=async l=>{let g=l??i;return await e.invokeAgent(g)};for(let l=o.length-1;l>=0;l--){let g=o[l],u=p;p=async m=>await g(m??i,d,u)}return await p()}}}async function ce(o,e){let t=await o.execute(e);return t===H?null:t}var ee,lt=D(()=>{"use strict";c();Z();ee=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function fn(o){let e=o.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function te(o){let e=o.captureAgentReplies??!0,t=o.getScope??fn,n=o.getMessageId??(i=>i.context?.messageId??i.context?.eventId??(0,pt.randomUUID)()),r=o.getMentions??(i=>i.context?.mentions??[]),s=async(i,a,d)=>{let p=i.conversationId;if(!p)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await d();let l=i.participant;if(l){let u={id:n(i),conversationId:p,participant:l,content:i.message??"",timestamp:new Date().toISOString(),scope:t(i),metadata:{channelType:i.context?.channelType,threadId:i.context?.threadId,messageId:i.context?.messageId,mentions:r(i),channelName:i.context?.channelName,channelId:i.context?.channelId}};try{await o.store.append(u),o.onCaptured?.(u),a.logger?.debug("[capture-history] Captured inbound message",{messageId:u.id,participantId:l.id,conversationId:p})}catch(m){a.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let g=await d();if(e&&!B(g)&&g.output!=null){let u={kind:"agent",id:a.agent.name,displayName:a.agent.name},m={id:(0,pt.randomUUID)(),conversationId:p,participant:u,content:g.output,timestamp:new Date().toISOString(),scope:t(i),metadata:{channelType:i.context?.channelType,threadId:i.context?.threadId,channelName:i.context?.channelName,channelId:i.context?.channelId}};try{await o.store.append(m),o.onCaptured?.(m),a.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:a.agent.name,conversationId:p})}catch(v){a.logger?.warn("[capture-history] Failed to store agent reply",{error:v instanceof Error?v.message:String(v)})}}return g};return s[de]=!0,s}var pt,de,ut=D(()=>{"use strict";c();pt=require("crypto");Z();de=Symbol.for("toolpack:capture-history")});function $t(o){return Math.ceil(o.length/4)}function yn(o){return{id:o.id,participant:o.participant,content:o.content,timestamp:o.timestamp}}function vn(o,e){let{participant:t,content:n}=o;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 wn(o,e,t){return!!(o.participant.id===e||o.metadata?.mentions?.some(n=>t.has(n)))}async function le(o,e,t,n,r={},s){let{scope:i,addressedOnlyMode:a=!0,tokenBudget:d=3e3,rollingSummaryThreshold:p=40,timeWindowMinutes:l,maxTurnsToLoad:g=100,agentAliases:u}=r,m=new Set([t,...u??[]]),v=l!==void 0?new Date(Date.now()-l*60*1e3).toISOString():void 0,y=await o.get(e,{scope:i,sinceTimestamp:v,limit:g}),b=y.length;if(a){let C=new Set;for(let S=0;S<y.length;S++){let q=y[S];if(wn(q,t,m)&&C.add(q.id),S<y.length-1){let k=y[S+1];k.participant.kind==="agent"&&k.participant.id===t&&C.add(q.id)}}let M=y[y.length-1];M&&C.add(M.id),y=y.filter(S=>C.has(S.id))}let w=!1;if(y.length>p&&s){let C=Math.floor(y.length/2),M=y.slice(0,C),S=y.slice(C),q=M.filter(k=>!k.metadata?.isSummary);try{let k=await s.invokeAgent({message:"summarize",data:{turns:q.map(yn),agentName:n,agentId:t,maxTokens:Math.floor(d*.25),extractDecisions:!0}}),N=JSON.parse(k.output),U={id:`summary-${(0,jt.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${N.turnsSummarized} earlier turns]: ${N.summary}`,timestamp:M[0].timestamp,scope:i??"channel",metadata:{isSummary:!0}};y=[U,...S],w=!0;try{await o.append(U),await o.deleteMessages(e,M.map(Y=>Y.id))}catch{}}catch{y=y.slice(-p)}}else y.length>p&&(y=y.slice(-p));let A=y.map(C=>vn(C,t));if(A.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:b,hasSummary:w};let x=A[A.length-1],_=[x],I=$t(x.content);for(let C=A.length-2;C>=0;C--){let M=A[C],S=$t(M.content);if(I+S>d)break;_.unshift(M),I+=S}return{messages:_,estimatedTokens:I,turnsLoaded:b,hasSummary:w}}var jt,gt=D(()=>{"use strict";c();jt=require("crypto")});var T,pe=D(()=>{"use strict";c();T=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var _e,mt,ht,ft,yt,vt,h,Ee,Bt=D(()=>{"use strict";c();_e=require("crypto"),mt=.6,ht=.2,ft=.2,yt={low:.3,medium:.6,high:1},vt=30,h={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"},Ee=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[h.type]==="goal"&&t[h.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,n)=>{let r={high:0,normal:1,low:2},s=r[t.priority]-r[n.priority];return s!==0?s:t.createdAt-n.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[h.type]==="goal"&&t[h.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[h.type]==="reflection"&&t[h.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[h.type]==="reflection"&&t[h.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(r=>r[h.type]==="belief"&&r[h.confidence]==="high"&&!r[h.error]&&!(r[h.expiresAt]&&r[h.expiresAt]<t))).map(r=>{let s=this.chunkToBelief(r),i=(t-s.createdAt)/864e5,d=Math.exp(-i/vt)*ht+yt.high*ft+mt;return{...s,score:d}}).sort((r,s)=>s.score-r.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[h.type]==="reflection"&&!s[h.pinned]&&!s[h.error]&&s[h.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,i)=>i.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:r="active",tags:s}=t,i;if(e.trim()&&typeof this.provider.keywordQuery=="function")i=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[h.type]:"goal",[h.status]:r}})).map(d=>this.chunkToGoal(d.chunk));else{let a=r;if(i=(await this._getAllByMeta(p=>p[h.type]==="goal"&&p[h.status]===a)).map(p=>this.chunkToGoal(p)),e.trim()){let p=e.toLowerCase();i=i.filter(l=>l.description.toLowerCase().includes(p))}}return s?.length&&(i=i.filter(a=>s.every(d=>a.tags.includes(d)))),i.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:r=0,tags:s,includeExpired:i=!1}=t,a=Date.now(),d=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[h.type]:"belief"}}),p=[];for(let l of d){let g=this.chunkToBelief(l.chunk);if(!i&&g.expiresAt&&g.expiresAt<a||s?.length&&!s.every(b=>g.tags.includes(b)))continue;let u=(a-g.createdAt)/864e5,m=Math.exp(-u/vt),v=g.error?.3:yt[g.confidence],y=l.score*mt+m*ht+v*ft;y<r||p.push({...g,score:y})}return p.sort((l,g)=>g.score-l.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:r=0,tags:s,pinned:i}=t,a=Date.now(),d={[h.type]:"reflection"};i===!0&&(d[h.pinned]=!0);let p=await this.provider.query(e,{limit:n*4,threshold:0,filter:d}),l=[];for(let g of p){let u=this.chunkToReflection(g.chunk);if(i===!1&&u.pinned||s?.length&&!s.every(b=>u.tags.includes(b)))continue;let m=(a-u.createdAt)/864e5,v=Math.exp(-m/vt),y=g.score*mt+v*ht+yt.medium*ft;y<r||l.push({...u,score:y})}return l.sort((g,u)=>u.score-g.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),r=await this.provider.query(e,{limit:5,threshold:t,filter:{[h.type]:"belief"}});for(let s of r){let i=this.chunkToBelief(s.chunk);if(!(i.expiresAt&&i.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:i}}return null}async addGoal(e){let t=(0,_e.randomUUID)();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 r=this.chunkToGoal(n),s={...r,description:t.description??r.description,priority:t.priority??r.priority,status:t.status??r.status,outcome:t.outcome??r.outcome,progress:t.appendProgress?[...r.progress,t.appendProgress]:r.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 r=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...r,status:"completed",outcome:t??r.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=(0,_e.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let r=await this._getById(e);if(!r)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(r),i={...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()},a=n??r.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(i,a)])}async addReflection(e,t){let n=(0,_e.randomUUID)();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 r=this.chunkToReflection(n),s={...r,pinned:t.pinned??r.pinned,error:t.error??r.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:{[h.type]:"goal",[h.status]:e.status,[h.priority]:e.priority,[h.tags]:JSON.stringify(e.tags),[h.progress]:JSON.stringify(e.progress),[h.dueBy]:e.dueBy??"",[h.outcome]:e.outcome??"",[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[h.status],priority:t[h.priority],tags:this._parseTags(t[h.tags]),progress:this._parseTags(t[h.progress]),dueBy:t[h.dueBy]||void 0,outcome:t[h.outcome]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[h.type]:"belief",[h.confidence]:e.confidence,[h.tags]:JSON.stringify(e.tags),[h.expiresAt]:e.expiresAt??0,[h.error]:e.error===!0,[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[h.confidence],tags:this._parseTags(t[h.tags]),expiresAt:t[h.expiresAt]||void 0,error:t[h.error]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[h.type]:"reflection",[h.pinned]:e.pinned,[h.tags]:JSON.stringify(e.tags),[h.relatedTo]:e.relatedTo??"",[h.error]:e.error===!0,[h.createdAt]:e.createdAt,[h.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[h.pinned],tags:this._parseTags(t[h.tags]),relatedTo:t[h.relatedTo]||void 0,error:t[h.error]||void 0,createdAt:t[h.createdAt],updatedAt:t[h.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 wt(o){let e=o.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${o}". 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 Lt(o){if(/^\d{4}-\d{2}-\d{2}/.test(o))return o;let e=wt(o);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ft(o,e){let t=0,n=0,r=0;for(let i=0;i<o.length;i++)t+=o[i]*e[i],n+=o[i]*o[i],r+=e[i]*e[i];let s=Math.sqrt(n)*Math.sqrt(r);return s===0?0:t/s}function At(o){return Math.ceil(o.length/4)}var bt=D(()=>{"use strict";c()});var Ut,Pe,Gt=D(()=>{"use strict";c();Ut=require("crypto");bt();Pe=class{constructor(e,t,n,r,s,i,a){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=r;this.committedGoalCount=s;this.committedPinnedReflectionCount=i;this.inFlightBeliefs=a}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),r,s=e.expiresIn??e.ttlDefault;s&&(r=t+wt(s));let i=this._findSimilarInDraft(n);if(i!==null){let l=this.ops[i],g=e.confidence,u=l.confidence,m={low:0,medium:1,high:2},v=m[g]>m[u]||e.allowDowngrade&&m[g]<m[u];return this.ops[i]={...l,content:e.content,confidence:v?g:u,tags:e.tags.length>0?e.tags:l.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:l.existingId??`draft-${i}`}}let a=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(a))return{action:"updated_draft",id:"in-flight-dedup"};let d=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(d){let l=d.belief,g=e.confidence,u=l.confidence,m={low:0,medium:1,high:2},v=m[g]>m[u]||e.allowDowngrade&&m[g]<m[u],y={op:"believe",content:e.content,confidence:v?g:u,tags:e.tags.length>0?e.tags:l.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:d.id};return this.ops.push(y),{action:"updated_store",id:d.id}}this.inFlightBeliefs.add(a);let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let i=this.totalPinnedReflectionCount;if(i>=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.`);i>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${i+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),r={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(r),{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?Lt(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Ut.randomUUID)(),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 r=n;this.inFlightBeliefs.delete(r.content.trim().toLowerCase()),e?r.existingId?await this.store.updateBelief(r.existingId,{content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,error:!0},r.vector):await this.store.addBelief({type:"belief",content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,error:!0,createdAt:r.createdAt,updatedAt:t},r.vector):r.existingId?await this.store.updateBelief(r.existingId,{content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt},r.vector):await this.store.addBelief({type:"belief",content:r.content,confidence:r.confidence,tags:r.tags,expiresAt:r.expiresAt,createdAt:r.createdAt,updatedAt:t},r.vector)}else if(n.op==="reflect"){let r=n;if(r.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:r.content,pinned:r.pinned,tags:r.tags,relatedTo:r.relatedTo,error:e||void 0,createdAt:r.createdAt,updatedAt:t},r.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 r=n;await this.store.updateGoal(r.id,{description:r.description,priority:r.priority,appendProgress:r.progress})}}else if(n.op==="unpin_reflection"&&!e){let r=n;await this.store.updateReflection(r.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,r)=>({op:n,idx:r})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:r}of t){let s=n;if(s.vector.length===0)continue;if(Ft(e,s.vector)>=this.deduplicationThreshold)return r}return null}}});function Jt(o,e,t){return[An(o,t),bn(o,e,t),In(e,t),Cn(e),kn(e,t),Rn(o,e),xn(o)]}function An(o,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??""),r=t.type??"all",s=t.status??"active",i=Array.isArray(t.tags)?t.tags.map(String):void 0,a=typeof t.pinned=="boolean"?t.pinned:void 0,d=t.includeExpired===!0,p=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,l=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,g=[],m=(r==="belief"||r==="reflection"||r==="all")&&n.trim()?await o.embed(n):null;if(r==="goal"||r==="all"){let v=await o.keywordSearchGoals(n,{limit:l,status:s,tags:i});for(let y of v)g.push(Sn(y))}if(m&&(r==="belief"||r==="all")){let v=await o.queryBeliefs(m,{limit:l,threshold:p,tags:i,includeExpired:d});for(let y of v)g.push(Tn(y))}if(m&&(r==="reflection"||r==="all")){let v=await o.queryReflections(m,{limit:l,threshold:p,tags:i,pinned:a});for(let y of v)g.push(_n(y))}return g}}}function bn(o,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 In(o,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 o.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 Cn(o){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=>(o.addUnpinReflection(String(e.id)),{status:"ok"})}}function kn(o,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",...o.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 Rn(o,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 xn(o){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 o.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Sn(o){return{id:o.id,type:"goal",content:o.description,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,priority:o.priority,status:o.status,progress:o.progress,outcome:o.outcome,dueBy:o.dueBy}}function Tn(o){return{id:o.id,type:"belief",content:o.content,score:o.score,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,confidence:o.confidence,expiresAt:o.expiresAt,error:o.error}}function _n(o){return{id:o.id,type:"reflection",content:o.content,score:o.score,tags:o.tags,createdAt:o.createdAt,updatedAt:o.updatedAt,pinned:o.pinned,relatedTo:o.relatedTo,error:o.error}}var zt=D(()=>{"use strict";c()});async function qt(o,e){let[t,n,r,s]=await Promise.all([o.getActiveGoals(),o.getPinnedReflections(),o.getHighConfidenceBeliefs(20),o.getRecentReflections(e.recencyWindowDays,3)]),i=t.map(g=>En(g)),a=n.map(g=>`- ${g.content}`),{beliefLines:d,reflectionLines:p}=Pn(r,s,e.tokenBudget);if(i.length===0&&a.length===0&&d.length===0&&p.length===0)return"";let l=["--- AGENT MIND ---",""];return i.length>0&&(l.push("## Goals"),l.push(...i),l.push("")),a.length>0&&(l.push("## Standing Rules (Pinned)"),l.push(...a),l.push("")),d.length>0&&(l.push("## Beliefs"),l.push(...d),l.push("")),p.length>0&&(l.push("## Recent Reflections"),l.push(...p),l.push("")),l.push("---"),l.join(`
2
+ `)}function En(o){let e=o.progress[o.progress.length-1],t=`[${o.priority}] ${o.description}`;return e&&(t+=` \u2014 last progress: ${e}`),o.dueBy&&(t+=` (due: ${o.dueBy})`),t}function Pn(o,e,t){let n=t,r=[],s=[];for(let i of o){let a=`- ${i.content} (${i.confidence} confidence)`,d=At(a);if(d>n)break;r.push(a),n-=d}for(let i of e){let d=`- [${new Date(i.createdAt).toISOString().slice(0,10)}] ${i.content}`,p=At(d);if(p>n)break;s.push(d),n-=p}return{beliefLines:r,reflectionLines:s}}var Wt=D(()=>{"use strict";c();bt()});var Ht={};dt(Ht,{AgentMind:()=>ue});function Un(o,e){let t=Math.min(e.maxGoals??Nn,Ln),n=Math.min(e.maxPinnedReflections??On,Fn);return{tokenBudget:e.tokenBudget??Mn,recencyWindowDays:e.recencyWindowDays??Dn,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??$n,retrievalThreshold:e.retrievalThreshold??jn,ttlDefaults:{belief:e.ttlDefaults?.belief??Bn,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${o}`}}var Mn,Dn,Nn,On,$n,jn,Bn,Ln,Fn,ue,It=D(()=>{"use strict";c();Bt();Gt();zt();Wt();Mn=300,Dn=7,Nn=10,On=10,$n=.85,jn=.35,Bn="30d",Ln=10,Fn=10,ue=class o{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:i}=await import("@toolpack-sdk/knowledge"),a=t.namespace??`mind/${e}`;n=new i({namespace:a})}let r=Un(e,t),s=new Ee(n,t.embedder);return await s.initialize(),new o(s,r)}async createRunContext(){let[e,t,n]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),qt(this.store,this.config)]),r=new Pe(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Jt(this.store,r,this.config),i={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:i,flush:async d=>{d?await r.flushOnError():await r.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var Ct={};dt(Ct,{EphemeralAgent:()=>ge});var ge,Me=D(()=>{"use strict";c();L();ge=class extends E{name;description;mode;constructor(e,t,n,r){super(r),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)}}});var Kt,Vt,F,E,L=D(()=>{"use strict";c();Kt=require("events"),Vt=require("async_hooks"),F=require("toolpack-sdk");lt();ut();gt();pe();E=class extends Kt.EventEmitter{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 Vt.AsyncLocalStorage;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new F.InMemoryConversationStore,"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 F.Toolpack.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(()=>(It(),Ht));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,r){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 i,a="";if(this._mind){let d=await this._mind.createRunContext();a=d.mindHeader,i=d.flush,this.toolpack.loadRequestToolProject(d.toolProject)}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let d=[];if(a&&d.push({role:"system",content:a}),s)try{let w=await le(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),A=w.messages[w.messages.length-1],x=e.trim(),I=x!==""&&A?.role==="user"&&typeof A.content=="string"&&(A.content===x||A.content.endsWith(`: ${x}`))?w.messages.slice(0,-1):w.messages;d.push(...I)}catch{}let p=r&&r.length>0;if(e.trim()||p)if(p){let w=[...e.trim()?[{type:"text",text:e}]:[],...r];d.push({role:"user",content:w})}else d.push({role:"user",content:e});let l=[];if(s){let w=this.conversationHistory;l.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 w.search(s,String(A.query??""),{limit:typeof A.limit=="number"?A.limit:5});return{results:x.map(_=>({role:_.participant.kind==="agent"?"assistant":"user",content:_.content,timestamp:_.timestamp})),count:x.length}}})}if(this.delegation?.enabled&&this._registry){let w=this.delegation.allowedAgents,A=this._registry.getAllAgents().filter(x=>x.name!==this.name&&(w===void 0||w.includes(x.name)));if(A.length>0){let x=A.map(I=>I.name),_=A.map(I=>`- ${I.name}: ${I.description}`).join(`
3
+ `);this.delegation.mode==="forget"?l.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
- ${S}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:b,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),k=String(I.message??"");return this._registry.invoke(P,{message:k,conversationId:r,context:{delegatedBy:this.name},signal:t?.signal}).catch(_=>{console.error(`[${this.name}] delegate_and_forget to ${P} failed:`,_)}),{status:"delegated",agent:P}}}):d.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
+ ${_}`,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 I=>{let C=String(I.agent),M=String(I.message??"");return this._registry.invoke(C,{message:M,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal}).catch(S=>{console.error(`[${this.name}] delegate_and_forget to ${C} failed:`,S)}),{status:"delegated",agent:C}}}):l.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
- ${S}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:b,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),k=String(I.message??""),_=await this._registry.invoke(P,{message:k,conversationId:r,context:{delegatedBy:this.name},signal:t?.signal});return{..._,output:`[Response from ${P} \u2014 task complete]
9
+ ${_}`,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 I=>{let C=String(I.agent),M=String(I.message??""),S=await this._registry.invoke(C,{message:M,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal});return{...S,output:`[Response from ${C} \u2014 task complete]
10
10
 
11
- ${_.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let v=n?.spawnDepth??0,A=this.spawn,b=A.maxDepth??3;if(v<b){let S=A.templates,I=S.some(C=>C.name==="self"),P=S.some(C=>C.allowPromptAddition),k=S.filter(C=>C.name!=="self").map(C=>`- ${C.name}: ${C.description}`).join(`
12
- `),_=I?`Use template name "self" to spawn a replica of the current agent.
13
- `:"",D=P?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};d.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
+ ${S.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let w=n?.spawnDepth??0,A=this.spawn,x=A.maxDepth??3;if(w<x){let _=A.templates,I=_.some(k=>k.name==="self"),C=_.some(k=>k.allowPromptAddition),M=_.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
12
+ `),S=I?`Use template name "self" to spawn a replica of the current agent.
13
+ `:"",q=C?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};l.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
- ${k}
17
- `+_+`Spawn depth: ${v}/${b}`,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."},...D},required:["template","task"]},execute:async C=>{let M=String(C.template),G=String(C.task??""),z,O,J,q,E=S.find($=>$.name===M);if(!E)throw new Error(`Unknown spawn template: "${M}"`);let ne=E.allowPromptAddition&&C.systemPromptAddition?`
16
+ ${M}
17
+ `+S+`Spawn depth: ${w}/${x}`,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."},...q},required:["template","task"]},execute:async k=>{let N=String(k.template),U=String(k.task??""),Y,G,J,z,P=_.find(O=>O.name===N);if(!P)throw new Error(`Unknown spawn template: "${N}"`);let re=P.allowPromptAddition&&k.systemPromptAddition?`
18
18
 
19
- ${String(C.systemPromptAddition)}`:"";if(M==="self"){let $=typeof this.mode=="string"?{...U.AGENT_MODE,name:this.mode}:this.mode,X=E.systemPrompt(G);z={...$,name:`${$.name}-replica-${Date.now()}`,systemPrompt:($.systemPrompt??"")+(X?`
19
+ ${String(k.systemPromptAddition)}`:"";if(N==="self"){let O=typeof this.mode=="string"?{...F.AGENT_MODE,name:this.mode}:this.mode,Q=P.systemPrompt(U);Y={...O,name:`${O.name}-replica-${Date.now()}`,systemPrompt:(O.systemPrompt??"")+(Q?`
20
20
 
21
- ${X}`:"")+ne},O=`${this.name}-replica`,J=this.description,q=this.model}else z={...U.AGENT_MODE,name:`ephemeral-${E.name}-${Date.now()}`,systemPrompt:E.systemPrompt(G)+ne},O=E.name,J=E.description,q=E.model;let{EphemeralAgent:re}=await Promise.resolve().then(()=>(Ee(),At)),W=new re(O,J,z,{toolpack:this.toolpack});q&&(W.model=q),W.spawn={...A};let Y=await W.invokeAgent({message:G,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:v+1}});return{output:Y.output,spawnedTemplate:M,depth:v+1,metadata:Y.metadata}}}),d.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
+ ${Q}`:"")+re},G=`${this.name}-replica`,J=this.description,z=this.model}else Y={...F.AGENT_MODE,name:`ephemeral-${P.name}-${Date.now()}`,systemPrompt:P.systemPrompt(U)+re},G=P.name,J=P.description,z=P.model;let{EphemeralAgent:se}=await Promise.resolve().then(()=>(Me(),Ct)),W=new se(G,J,Y,{toolpack:this.toolpack});z&&(W.model=z),W.spawn={...A};let X=await W.invokeAgent({message:U,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:w+1}});return{output:X.output,spawnedTemplate:N,depth:w+1,metadata:X.metadata}}}),l.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
- ${k}
25
- `+_+`Spawn depth: ${v}/${b}`,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 C=>{let M=C.tasks;if(!Array.isArray(M)||M.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:G}=await Promise.resolve().then(()=>(Ee(),At));return{results:await Promise.all(M.map(async O=>{let J=String(O.template),q=String(O.task??""),E=S.find(se=>se.name===J);if(!E)throw new Error(`Unknown spawn template: "${J}"`);let ne=E.allowPromptAddition&&O.systemPromptAddition?`
24
+ ${M}
25
+ `+S+`Spawn depth: ${w}/${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: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."},...C?{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 N=k.tasks;if(!Array.isArray(N)||N.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:U}=await Promise.resolve().then(()=>(Me(),Ct));return{results:await Promise.all(N.map(async G=>{let J=String(G.template),z=String(G.task??""),P=_.find(oe=>oe.name===J);if(!P)throw new Error(`Unknown spawn template: "${J}"`);let re=P.allowPromptAddition&&G.systemPromptAddition?`
26
26
 
27
- ${String(O.systemPromptAddition)}`:"",re,W,Y,$;if(J==="self"){let se=typeof this.mode=="string"?{...U.AGENT_MODE,name:this.mode}:this.mode,Pt=E.systemPrompt(q);re={...se,name:`${se.name}-replica-${Date.now()}`,systemPrompt:(se.systemPrompt??"")+(Pt?`
27
+ ${String(G.systemPromptAddition)}`:"",se,W,X,O;if(J==="self"){let oe=typeof this.mode=="string"?{...F.AGENT_MODE,name:this.mode}:this.mode,Nt=P.systemPrompt(z);se={...oe,name:`${oe.name}-replica-${Date.now()}`,systemPrompt:(oe.systemPrompt??"")+(Nt?`
28
28
 
29
- ${Pt}`:"")+ne},W=`${this.name}-replica`,Y=this.description,$=this.model}else re={...U.AGENT_MODE,name:`ephemeral-${E.name}-${Date.now()}`,systemPrompt:E.systemPrompt(q)+ne},W=E.name,Y=E.description,$=E.model;let X=new G(W,Y,re,{toolpack:this.toolpack});$&&(X.model=$),X.spawn={...A};let Et=await X.invokeAgent({message:q,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:v+1}});return{output:Et.output,spawnedTemplate:J,depth:v+1,metadata:Et.metadata}}))}}})}}let p={messages:l,model:this.model||"",requestTools:d.length>0?d:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},g=null,u,m;if(typeof this.mode!="string"&&this.mode?.streaming){let v="";for await(let A of this.toolpack.stream(p,this.provider))v+=A.delta||"",A.usage&&(u=A.usage);g=v||null,m={content:g,usage:u}}else{let v=await this.toolpack.generate(p,this.provider);g=v.content??null,u=v.usage,m=v}let y={output:g||"",steps:this.extractSteps(m),metadata:u?{usage:u}:void 0};return await this.onComplete(y),s&&await s(!1),this.emit("agent:complete",y),y}catch(l){throw s&&s(!0).catch(d=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,d)}),await this.onError(l),this.emit("agent:error",l),l}}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 R("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,r=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new R("No conversationId available - ask() requires a conversation channel");if(r)throw new R("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 R("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=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:i.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 R("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 r=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
29
+ ${Nt}`:"")+re},W=`${this.name}-replica`,X=this.description,O=this.model}else se={...F.AGENT_MODE,name:`ephemeral-${P.name}-${Date.now()}`,systemPrompt:P.systemPrompt(z)+re},W=P.name,X=P.description,O=P.model;let Q=new U(W,X,se,{toolpack:this.toolpack});O&&(Q.model=O),Q.spawn={...A};let Dt=await Q.invokeAgent({message:z,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:w+1}});return{output:Dt.output,spawnedTemplate:J,depth:w+1,metadata:Dt.metadata}}))}}})}}let g={messages:d,model:this.model||"",requestTools:l.length>0?l:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},u=null,m,v;if(typeof this.mode!="string"&&this.mode?.streaming){let w="";for await(let A of this.toolpack.stream(g,this.provider))w+=A.delta||"",A.usage&&(m=A.usage);u=w||null,v={content:u,usage:m}}else{let w=await this.toolpack.generate(g,this.provider);u=w.content??null,m=w.usage,v=w}let b={output:u||"",steps:this.extractSteps(v),metadata:m?{usage:m}:void 0};return await this.onComplete(b),i&&await i(!1),this.emit("agent:complete",b),b}catch(d){throw i&&i(!0).catch(p=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,p)}),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 T("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,r=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new T("No conversationId available - ask() requires a conversation channel");if(r)throw new T("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 T("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=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:i.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 T("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 r=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:r})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,r){if(await this.evaluateAnswer(e.question,t,{simpleValidation:i=>i.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let i=this._ctx()?.triggeringChannel??this._triggeringChannel;return i&&await this.sendTo(i,"I was unable to get enough information to proceed. Skipping this step."),r?r():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId: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 R("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(r=>r.botUserId).filter(r=>typeof r=="string"&&r.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[ce]===!0)?this.interceptors:[ee({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 r=ie(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await ae(r,t);if(s===null)return;let i={output:s.output,metadata:s.metadata};await e.send({output:i.output,metadata:{...i.metadata,conversationId:t.conversationId,...t.context}})}catch(r){let s=r instanceof Error?r.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(i){console.error(`[${this.name}] Failed to send error to channel: ${i}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(r=>{t=r});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(r=>({number:r.number||0,description:r.description||"",status:r.status||"completed",result:r.result}))}if(Array.isArray(t.steps))return t.steps}}});var Yn={};it(Yn,{AgentError:()=>R,AgentJsonRpcServer:()=>me,AgentMind:()=>pe,AgentRegistry:()=>Pe,BaseAgent:()=>T,BaseChannel:()=>x,BrowserAgent:()=>$e,CodingAgent:()=>Ne,ContainsScorer:()=>Ce,CustomScorer:()=>Re,DataAgent:()=>Oe,DepthExceededError:()=>V,DiscordChannel:()=>Ge,EmailChannel:()=>Je,EphemeralAgent:()=>ue,EvalDataset:()=>Ae,EvalRunner:()=>be,ExactMatchScorer:()=>Ie,HotReloadWatcher:()=>Me,InMemoryConversationStore:()=>We.InMemoryConversationStore,IntentClassifierAgent:()=>he,InvocationDepthExceededError:()=>Z,JsonRpcTransport:()=>ge,LLMJudgeScorer:()=>ke,LocalTransport:()=>K,McpChannel:()=>ze,OTelSpanStatusCode:()=>ye,ResearchAgent:()=>De,SKIP_SENTINEL:()=>H,SMSChannel:()=>qe,ScheduledChannel:()=>Fe,SchedulerStore:()=>we,SlackChannel:()=>je,SummarizerAgent:()=>fe,TelegramChannel:()=>Ue,WebhookChannel:()=>Le,assemblePrompt:()=>de,compareEvalRuns:()=>Tt,composeChain:()=>ie,createAddressCheckInterceptor:()=>Qe,createCaptureInterceptor:()=>ee,createConversationSearchTool:()=>Ct,createDepthGuardInterceptor:()=>et,createEventDedupInterceptor:()=>He,createIntentClassifierInterceptor:()=>Ze,createNoiseFilterInterceptor:()=>Ke,createOTelTracerInterceptor:()=>nt,createParticipantResolverInterceptor:()=>Xe,createRateLimitInterceptor:()=>Ye,createSchedulerTools:()=>St,createSelfFilterInterceptor:()=>Ve,createTracerInterceptor:()=>tt,executeChain:()=>ae,formatEvalReport:()=>_t,isSkipSentinel:()=>L,skip:()=>oe});module.exports=un(Yn);c();c();F();Ee();c();var Ht=require("crypto");c();var bt=require("crypto");le();var K=class{constructor(e){this.registry=e}registry;async invoke(e,t){let n=this.registry.getAgent(e);if(!n)throw new R(`Agent "${e}" not found in registry. Available agents: ${this.registry.getAllAgents().map(l=>l.name).join(", ")}`);let r=n.conversationHistory,s=t.conversationId,i=t.context?.delegatedBy;if(r&&s&&i){let l={id:t.context?.messageId??(0,bt.randomUUID)(),conversationId:s,participant:{kind:"agent",id:i,displayName:i},content:t.message??"",timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(l)}catch{}}let a=await n.invokeAgent(t);if(r&&s){let l={id:(0,bt.randomUUID)(),conversationId:s,participant:{kind:"agent",id:e,displayName:e},content:a.output,timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(l)}catch{}}return a}};var Pe=class{agentList;instances=new Map;channels=new Map;_transport;pendingAsks=new Map;_started=!1;_restarting=!1;_restartScheduled=!1;_deadlineTimer;constructor(e,t){this.agentList=e,this._transport=t?.transport||new K(this)}async start(){for(let e of this.agentList){await e._ensureToolpack(),e._registry=this,this.instances.set(e.name,e);for(let t of e.channels??[])t.name&&this.channels.set(t.name,t)}for(let e of this.agentList)await e.start();this._started=!0}async addAgent(e){if(this.agentList.push(e),!!this._started){await e._ensureToolpack(),e._registry=this,this.instances.set(e.name,e);for(let t of e.channels??[])t.name&&this.channels.set(t.name,t);await e.start()}}async removeAgent(e){let t=this.instances.get(e);if(t){await t.stop(),this.instances.delete(e),this.agentList=this.agentList.filter(n=>n.name!==e);for(let n of t.channels??[])n.name&&this.channels.delete(n.name)}}isAllIdle(){return this.agentList.every(e=>e.isIdle())}scheduleRestart(e){if(this._restartScheduled)return;this._restartScheduled=!0;let t=(e?.maxWaitMinutes??30)*60*1e3,n=()=>{!this._restarting&&this.isAllIdle()&&this._executeRestart()};if(n(),!this._restarting){for(let r of this.agentList)r.on("agent:complete",n);this._deadlineTimer=setTimeout(()=>{this._executeRestart()},t)}}async _executeRestart(){if(this._restarting)return;this._restarting=!0,this._deadlineTimer&&(clearTimeout(this._deadlineTimer),this._deadlineTimer=void 0),await this.stop();let e=Date.now()+3e4;for(;!this.isAllIdle()&&Date.now()<e;)await new Promise(t=>setTimeout(t,100));this._exit(0)}_exit(e){process.exit(e)}async sendTo(e,t){let n=this.channels.get(e);if(!n)throw new Error(`No channel registered with name "${e}"`);await n.send(t)}getAgent(e){return this.instances.get(e)}getAllAgents(){return Array.from(this.instances.values())}getChannel(e){return this.channels.get(e)}async invoke(e,t){return this._transport.invoke(e,t)}async stop(){for(let e of this.agentList)await e.stop();this.instances.clear(),this.channels.clear(),this.pendingAsks.clear()}getPendingAsk(e){let t=this.pendingAsks.get(e);if(!t||t.length===0)return;let n=new Date;for(;t.length>0;){let r=t[0];if(r.expiresAt&&r.expiresAt<n)t.shift();else break}if(t.length===0){this.pendingAsks.delete(e);return}return t[0]}hasPendingAsks(e){let t=this.pendingAsks.get(e);if(!t||t.length===0)return!1;let n=new Date,r=t.filter(s=>!s.expiresAt||s.expiresAt>=n);return r.length===0?(this.pendingAsks.delete(e),!1):(r.length!==t.length&&this.pendingAsks.set(e,r),r.some(s=>s.status==="pending"))}cleanupExpiredAsks(){let e=0,t=new Date;for(let[n,r]of this.pendingAsks.entries()){let s=r.filter(i=>!i.expiresAt||i.expiresAt>=t);e+=r.length-s.length,s.length===0?this.pendingAsks.delete(n):s.length!==r.length&&this.pendingAsks.set(n,s)}return e}addPendingAsk(e){let t={...e,id:(0,Ht.randomUUID)(),askedAt:new Date,retries:0,status:"pending"},n=this.pendingAsks.get(e.conversationId);return n?n.push(t):this.pendingAsks.set(e.conversationId,[t]),t}incrementRetries(e){for(let t of this.pendingAsks.values()){let n=t.find(r=>r.id===e);if(n)return n.retries+=1,n.retries}}async resolvePendingAsk(e,t){for(let[n,r]of this.pendingAsks.entries()){let s=r.findIndex(i=>i.id===e);if(s!==-1){r[s].status="answered",r[s].answer=t;let i=r[s].channelName;if(r.splice(s,1),r.length>0){let a=r[0];if(i&&i.trim()!=="")try{await this.sendTo(i,{output:a.question})}catch(l){console.error(`[AgentRegistry] Failed to auto-send next ask: ${l instanceof Error?l.message:"Unknown error"}`)}else console.warn(`[AgentRegistry] Cannot auto-send next ask: channelName is empty for conversation ${n}`)}r.length===0&&this.pendingAsks.delete(n);return}}throw new Error(`Pending ask with id "${e}" not found`)}};le();c();var Kt=require("fs"),Vt=require("child_process"),Yt=require("path"),Me=class{cwd;debounceMs;onRestartNeeded;onCompileError;spawnFn;watchFn;watchPaths;watchers=[];debounceTimer;constructor(e){this.watchPaths=e.watchPaths,this.cwd=e.cwd??process.cwd(),this.debounceMs=e.debounceMs??3e4,this.onRestartNeeded=e.onRestartNeeded,this.onCompileError=e.onCompileError,this.spawnFn=e.spawnFn??Vt.spawn,this.watchFn=e.watchFn??Kt.watch}start(){for(let e of this.watchPaths){let t=this.watchFn(e,{recursive:!0},(n,r)=>{r&&this._handleFileChange(r)});this.watchers.push(t)}}stop(){for(let e of this.watchers)e.close();this.watchers=[],this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}_handleFileChange(e){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,(0,Yt.basename)(e).startsWith(".env")?this.onRestartNeeded():(e.endsWith(".ts")||e.endsWith(".tsx"))&&this._runCompile()},this.debounceMs)}_runCompile(){return new Promise(e=>{let t="",n=this.spawnFn("npx",["tsc","--build"],{cwd:this.cwd,stdio:["ignore","ignore","pipe"]});n.stderr?.on("data",r=>{t+=r.toString()}),n.on("close",r=>{if(r===0)this.onRestartNeeded();else{let s=t||`tsc --build exited with code ${String(r)}`;this.onCompileError?.(s)}e()}),n.on("error",r=>{let s=r instanceof Error?r.message:String(r);this.onCompileError?.(s),e()})})}};c();F();var Xt=require("toolpack-sdk"),Ln={...Xt.AGENT_MODE,name:"research-agent-mode",systemPrompt:["You are a research agent specialized in web research and information gathering.","Use web.search to find relevant information, web.fetch to retrieve content, and web.scrape when needed.","Always cite your sources with URLs.","Provide comprehensive, well-structured summaries.","Flag any conflicting information or uncertainty in your findings."].join(" ")},De=class extends T{name="research-agent";description="Web research agent for summarization, fact-finding, competitive analysis, and trend monitoring";mode=Ln;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId});return await this.onComplete(t),t}};c();F();var Qt=require("toolpack-sdk"),Fn={...Qt.CODING_MODE,name:"coding-agent-mode",systemPrompt:["You are a coding agent specialized in software development tasks.","Use coding.* tools for code analysis, fs.* for file operations, and git.* for version control.","Write clean, idiomatic code following best practices.","Always verify your changes and check for potential issues.","Provide clear explanations of your code changes."].join(" ")},Ne=class extends T{name="coding-agent";description="Coding agent for code generation, refactoring, debugging, test writing, and code review";mode=Fn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId});return await this.onComplete(t),t}};c();F();var Zt=require("toolpack-sdk"),Un={...Zt.AGENT_MODE,name:"data-agent-mode",systemPrompt:["You are a data agent specialized in database operations and data analysis.","Use db.* tools for database queries, fs.* for file operations, and http.* for API requests.","Generate clear, well-formatted reports and summaries.","Always validate data integrity and handle errors gracefully.","Provide insights and patterns when analyzing data."].join(" ")},Oe=class extends T{name="data-agent";description="Data agent for database queries, CSV generation, data analysis, reporting, and aggregation";mode=Un;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId});return await this.onComplete(t),t}};c();F();var en=require("toolpack-sdk"),Gn={...en.CHAT_MODE,name:"browser-agent-mode",systemPrompt:["You are a browser agent specialized in web interaction and content extraction.","Use web.fetch to retrieve pages, web.screenshot for visual content, and web.extract_links for navigation.","Follow links intelligently to gather comprehensive information.","Extract structured data from web pages when possible.","Be mindful of rate limits and respectful of website resources."].join(" ")},$e=class extends T{name="browser-agent";description="Browser agent for web browsing, form interaction, page extraction, and link following";mode=Gn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId});return await this.onComplete(t),t}};c();var x=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};c();var Be=require("crypto");var je=class extends x{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let t=e.channel;this.allowedChannels=t==null?null:Array.isArray(t)?t:[t]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((t,n)=>{this.handleRequest(t,n)}),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 t=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();t.ok?(this.botUserId=t.user_id,this.botId=t.bot_id,console.log(`[SlackChannel] Connected as @${t.user} (${t.user_id}) in workspace "${t.team}" \u2014 ${t.url}`)):console.warn(`[SlackChannel] auth.test failed: ${t.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,t){let n=e["x-slack-request-timestamp"],r=e["x-slack-signature"];if(!n||!r||Array.isArray(n)||Array.isArray(r))return!1;let s=parseInt(n,10),i=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(i-s)>300)return!1;let a=`v0:${n}:${t}`,d=`v0=${(0,Be.createHmac)("sha256",this.config.signingSecret).update(a).digest("hex")}`;if(d.length!==r.length)return!1;try{return(0,Be.timingSafeEqual)(Buffer.from(d),Buffer.from(r))}catch{return!1}}async send(e){let t=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,r=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!r)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:r,text:e.output};t&&(s.thread_ts=t);let i=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok)throw new Error(`Failed to send Slack message: ${i.statusText}`);let a=await i.json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`)}normalize(e){let t=e,r=(t.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=t.ts,i=t.thread_ts,a=i!==void 0&&i!==s,l=t.user,d=l?{kind:"user",id:l}:void 0,p=/<@([A-Z0-9]+)>/g,g=[],u;for(;(u=p.exec(r))!==null;)g.push(u[1]);let m=t.channel;return{message:r,conversationId:a?i:m||s||"",data:t,participant:d,context:{user:l,channel:m,team:t.team,channelType:t.channel_type,threadId:a?i:void 0,mentions:g.length>0?g:void 0,channelId:m,channelName:typeof this.config.channel=="string"?this.config.channel:m}}}async resolveParticipant(e){let t=e.participant?.id??e.context?.user;if(!t)return;let n=this.participantCache.get(t);if(n)return n;try{let r=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!r.ok)return{kind:"user",id:t};let s=await r.json();if(!s.ok||!s.user){let l={kind:"user",id:t};return this.participantCache.set(t,l),l}let i=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||t,a={kind:"user",id:t,displayName:i,metadata:{slackUser:s.user}};return this.participantCache.set(t,a),a}catch{return{kind:"user",id:t}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let t=e.type;if(t!=="message"&&t!=="app_mention")return!1;if(this.allowedChannels!==null){let i=e.channel_type;if(!(i==="im"||i==="mpim")){let l=e.channel;if(!l||!this.allowedChannels.includes(l))return!1}}let n=e.user;if(this.botUserId&&n===this.botUserId)return!1;let r=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${n} bot_id=${r} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!r)return!0;if(this.botId&&r===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(r)||n!==void 0&&s.includes(n))return!1;if(this.config.allowedBotIds!==void 0){let i=this.config.allowedBotIds;return i.includes(r)||n!==void 0&&i.includes(n)}return!0}handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,n)){t.writeHead(401),t.end("Invalid signature");return}try{let r=JSON.parse(n);if(r.type==="url_verification"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({challenge:r.challenge}));return}if(r.type==="event_callback"&&r.event){let s=r.event;if(this.shouldProcessEvent(s)){let i=this.normalize(s);this.handleMessage(i)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);t.writeHead(200),t.end("OK");return}t.writeHead(200),t.end("OK")}catch(r){console.error("[SlackChannel] Error handling request:",r),t.writeHead(400),t.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};c();var Le=class extends x{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((t,n)=>{this.handleRequest(t,n)}),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 t=e.metadata?.conversationId;if(t&&this.pendingResponses.has(t)){let n=this.pendingResponses.get(t);this.pendingResponses.delete(t),n.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let t=e,n=t.headers||{},r=n["x-session-id"]||n["X-Session-Id"]||t.sessionId||t.conversationId||this.generateSessionId();return{message:t.message||t.text||"",intent:t.intent,conversationId:r,data:t,context:{headers:t.headers,method:t.method,sessionId:r}}}handleRequest(e,t){if(e.url!==this.config.path){t.writeHead(404),t.end("Not found");return}if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(n),s=this.normalize(r),i=s.conversationId||this.generateSessionId(),a=new Promise((l,d)=>{this.pendingResponses.set(i,{resolve:l,reject:d}),setTimeout(()=>{this.pendingResponses.has(i)&&(this.pendingResponses.delete(i),d(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:i,context:{...s.context,sessionId:i}}),a.then(l=>{t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(l))}).catch(l=>{t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:l.message}))})}catch(r){console.error("[WebhookChannel] Error handling request:",r),t.writeHead(400,{"Content-Type":"application/json"}),t.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)})}};c();var It=require("cron-parser"),Fe=class extends x{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{It.CronExpressionParser.parse(e.cron)}catch(t){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${t.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 t=e,n=new Date,r=`${n.getFullYear()}-${n.getMonth()+1}-${n.getDate()}`;return{intent:t?.intent??this.config.intent,message:t?.message??this.config.message??`Scheduled task triggered at ${n.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${r}`,data:{...t?.payload??{},scheduled:!0,jobId:t?.id,cron:t?.cron??this.config.cron,timestamp:n.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let t=this._nextRunFromCron(this.config.cron),n=t.getTime()-Date.now();if(n<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${t.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},n)}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(t){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,t)}}_listenWithStore(){let e=this.config.store,t=this._generation;if(t===1){let r=e.resetStuck(this.name);r>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${r} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:r}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});r||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let n=e.getDue(Date.now(),this.name);n.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${n.length} overdue job(s).`),Promise.allSettled(n.map(r=>this._triggerJob(r)))),this._scheduleNextFromStore(t)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let t=this.config.store,n=t.getNextPending(this.name);if(!n){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let r=Math.max(0,n.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(n.nextRunAt).toISOString()} (in ${Math.round(r/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=t.getDue(Date.now(),this.name);await Promise.allSettled(s.map(i=>this._triggerJob(i))),this._scheduleNextFromStore(e)},r)}async _triggerJob(e){let t=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.`),t.markFailed(e.id,"No message handler registered");return}t.markRunning(e.id);let n=this.normalize(e);try{await this.handleMessage(n),t.markCompleted(e.id)}catch(r){let s=r instanceof Error?r.message:String(r);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,r),t.markFailed(e.id,s)}}_nextRunFromCron(e){return It.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};c();var Ue=class extends x{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 t=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(t.ok&&t.result){let n=t.result;this.botUserId=n.id!=null?String(n.id):void 0,this.botUsername=n.username,console.log(`[TelegramChannel] Connected as @${n.username} (id: ${n.id}, name: ${n.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${t.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let t=e.metadata?.chatId;if(!t)throw new Error("Telegram send requires chatId in metadata");let n=e.metadata?.replyMarkup,r=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:t,text:e.output,parse_mode:"Markdown",...n?{reply_markup:n}:{}})});if(!r.ok)throw new Error(`Failed to send Telegram message: ${r.statusText}`);let s=await r.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,t){let n=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,...t?{text:t}:{}})});if(!n.ok)throw new Error(`Failed to answer Telegram callback query: ${n.statusText}`);let r=await n.json();if(!r.ok)throw new Error(`Telegram API error: ${r.description}`)}normalize(e){let t=e,n=t.callback_query;if(n){let y=n.message||{},v=y.chat||{},A=n.from||{},b=A.id!=null?String(A.id):void 0,S=A.first_name||A.username||b,I=b?{kind:"user",id:b,displayName:S??b}:void 0,P=v.id!=null?String(v.id):"";return{message:n.data??"",conversationId:P,data:t,participant:I,context:{isCallback:!0,callbackQueryId:n.id,callbackData:n.data,chatId:v.id,userId:A.id,username:A.username,firstName:A.first_name,lastName:A.last_name,messageId:y.message_id,channelType:v.type,channelId:P,channelName:v.title}}}let r=t.message||t.edited_message||{},s=r.text||"",i=r.chat||{},a=r.from||{},l=a.id!=null?String(a.id):void 0,d=a.first_name||a.username||l,p=l?{kind:"user",id:l,displayName:d??l}:void 0,g=r.entities??[],u=[];for(let y of g)if(y.type==="text_mention"&&y.user){let v=y.user;v.id!=null&&u.push(String(v.id))}let m=i.type,w=i.id!=null?String(i.id):"";return{message:s,conversationId:w,data:t,participant:p,context:{chatId:i.id,userId:a.id,username:a.username,firstName:a.first_name,lastName:a.last_name,messageId:r.message_id,channelType:m,channelId:w,channelName:i.title,mentions:u.length>0?u:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,t=await fetch(e);if(!t.ok)throw new Error(`Telegram getUpdates failed: ${t.statusText}`);let n=await t.json();if(!n.ok)throw new Error("Telegram getUpdates returned not ok");for(let r of n.result){let s=r.update_id;s>=this.offset&&(this.offset=s+1);try{let i=this.normalize(r);await this.handleMessage(i)}catch(i){console.error("[TelegramChannel] Error processing update:",i)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((r,s)=>{this.handleWebhookRequest(r,s)});let t=new URL(this.config.webhookUrl||"http://localhost:3000"),n=parseInt(t.port,10)||3e3;this.server.listen(n,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${n}`)}),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 t=await e.json();t.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",t.description)}handleWebhookRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(n);this.handleMessage(this.normalize(r)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),t.writeHead(200),t.end("OK")}catch(r){console.error("[TelegramChannel] Error parsing webhook:",r),t.writeHead(400),t.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)}}};c();var Jn=new Set([1,3]),tn=/<@!?(\d+)>/g,qn="https://discord.com/api/v10",Ge=class extends x{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 t=e,n=t.channelId,r=(n??"")+(t.thread?.id?`:${t.thread.id}`:""),s=t.channel?.type,i=s!==void 0&&Jn.has(s),a=t.author?.id,l=t.author?.globalName??t.author?.username,d=[];if(t.content){tn.lastIndex=0;let p;for(;(p=tn.exec(t.content))!==null;)d.push(p[1])}return{message:t.content,conversationId:r,data:t,participant:a?{kind:"user",id:a,displayName:l??void 0}:void 0,context:{userId:a,username:t.author?.username,channelType:i?"dm":"channel",channelId:n,channelName:t.channel?.name,guildId:t.guildId,threadId:t.thread?.id,messageId:t.id,mentions:d.length>0?d:void 0,isMentioned:this.botUserId?d.includes(this.botUserId):void 0}}}async resolveParticipant(e){let t=e.participant?.id??e.context?.userId;if(!t)return;let n=this.participantCache.get(t);if(n)return n;try{let r=await fetch(`${qn}/users/${t}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!r.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${t}: HTTP ${r.status}`),{kind:"user",id:t};let s=await r.json(),i=s.global_name??s.username,a={kind:"user",id:s.id,displayName:i};return this.participantCache.set(t,a),a}catch(r){return console.warn(`[DiscordChannel] resolveParticipant error for ${t}:`,r),{kind:"user",id:t}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let t=e.metadata?.threadId;if(t){let s=await this.client.channels.fetch(t);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(i){throw console.error("[DiscordChannel] Failed to send to thread:",i),new Error(`[DiscordChannel] Failed to send Discord message: ${i instanceof Error?i.message:String(i)}`)}console.warn(`[DiscordChannel] Thread ${t} not found or not sendable; falling back to channel send.`)}let n=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!n)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let r=await this.client.channels.fetch(n);if(!r||!("send"in r))throw new Error(`[DiscordChannel] Channel ${n} not found or is not a text channel`);try{await r.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:t,GatewayIntentBits:n}=e;this.client=new t({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]}),this.client.on("ready",()=>{let r=this.client.user;this.botUserId=r?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),i=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${r?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${i} | channels=${s}`)}),this.client.on("messageCreate",r=>{let s=r;if(!this.shouldProcessEvent(s))return;let i=this.normalize(s);this.handleMessage(i)}),this.client.on("userUpdate",(r,s)=>{let i=s;i?.id&&this.invalidateParticipant(i.id)}),this.client.login(this.config.token).catch(r=>{console.error("[DiscordChannel] Failed to login to Discord:",r)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};c();var Je=class extends x{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 t=Array.isArray(this.config.to)?this.config.to:[this.config.to],n=this.config.subject||"Message from Agent",r={from:this.config.from,to:t.join(", "),subject:n,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(r)}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(`
34
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:r})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,r){if(await this.evaluateAnswer(e.question,t,{simpleValidation:i=>i.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let i=this._ctx()?.triggeringChannel??this._triggeringChannel;return i&&await this.sendTo(i,"I was unable to get enough information to proceed. Skipping this step."),r?r():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId: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 T("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(r=>r.botUserId).filter(r=>typeof r=="string"&&r.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[de]===!0)?this.interceptors:[te({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 r=ae(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await ce(r,t);if(s===null)return;let i={output:s.output,metadata:s.metadata};await e.send({output:i.output,metadata:{...i.metadata,conversationId:t.conversationId,...t.context}})}catch(r){let s=r instanceof Error?r.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(i){console.error(`[${this.name}] Failed to send error to channel: ${i}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(r=>{t=r});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(r=>({number:r.number||0,description:r.description||"",status:r.status||"completed",result:r.result}))}if(Array.isArray(t.steps))return t.steps}}});var Zn={};dt(Zn,{AgentError:()=>T,AgentJsonRpcServer:()=>fe,AgentMind:()=>ue,AgentRegistry:()=>De,BaseAgent:()=>E,BaseChannel:()=>R,BrowserAgent:()=>Be,ChatChannel:()=>Ke,CodingAgent:()=>$e,ContainsScorer:()=>Re,CustomScorer:()=>Se,DataAgent:()=>je,DepthExceededError:()=>V,DiscordChannel:()=>ze,EmailChannel:()=>qe,EphemeralAgent:()=>ge,EvalDataset:()=>Ie,EvalRunner:()=>Ce,ExactMatchScorer:()=>ke,HotReloadWatcher:()=>Ne,InMemoryConversationStore:()=>Ve.InMemoryConversationStore,IntentClassifierAgent:()=>ye,InvocationDepthExceededError:()=>ee,JsonRpcTransport:()=>he,LLMJudgeScorer:()=>xe,LocalTransport:()=>K,McpChannel:()=>He,OTelSpanStatusCode:()=>we,ResearchAgent:()=>Oe,SKIP_SENTINEL:()=>H,SMSChannel:()=>We,ScheduledChannel:()=>Ge,SchedulerStore:()=>be,SlackChannel:()=>Le,SummarizerAgent:()=>ve,TelegramChannel:()=>Je,WebhookChannel:()=>Ue,assemblePrompt:()=>le,compareEvalRuns:()=>Pt,composeChain:()=>ae,createAddressCheckInterceptor:()=>tt,createCaptureInterceptor:()=>te,createConversationSearchTool:()=>xt,createDepthGuardInterceptor:()=>rt,createEventDedupInterceptor:()=>Ye,createIntentClassifierInterceptor:()=>nt,createNoiseFilterInterceptor:()=>Xe,createOTelTracerInterceptor:()=>ot,createParticipantResolverInterceptor:()=>et,createRateLimitInterceptor:()=>Ze,createSchedulerTools:()=>Et,createSelfFilterInterceptor:()=>Qe,createTracerInterceptor:()=>st,executeChain:()=>ce,formatEvalReport:()=>Mt,isSkipSentinel:()=>B,skip:()=>ie});module.exports=hn(Zn);c();c();L();Me();c();var Yt=require("crypto");c();var kt=require("crypto");pe();var K=class{constructor(e){this.registry=e}registry;async invoke(e,t){let n=this.registry.getAgent(e);if(!n)throw new T(`Agent "${e}" not found in registry. Available agents: ${this.registry.getAllAgents().map(d=>d.name).join(", ")}`);let r=n.conversationHistory,s=t.conversationId,i=t.context?.delegatedBy;if(r&&s&&i){let d={id:t.context?.messageId??(0,kt.randomUUID)(),conversationId:s,participant:{kind:"agent",id:i,displayName:i},content:t.message??"",timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(d)}catch{}}let a=await n.invokeAgent(t);if(r&&s){let d={id:(0,kt.randomUUID)(),conversationId:s,participant:{kind:"agent",id:e,displayName:e},content:a.output,timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(d)}catch{}}return a}};var De=class{agentList;instances=new Map;channels=new Map;_transport;pendingAsks=new Map;_started=!1;_restarting=!1;_restartScheduled=!1;_deadlineTimer;constructor(e,t){this.agentList=e,this._transport=t?.transport||new K(this)}async start(){for(let e of this.agentList){await e._ensureToolpack(),e._registry=this,this.instances.set(e.name,e);for(let t of e.channels??[])t.name&&this.channels.set(t.name,t)}for(let e of this.agentList)await e.start();this._started=!0}async addAgent(e){if(this.agentList.push(e),!!this._started){await e._ensureToolpack(),e._registry=this,this.instances.set(e.name,e);for(let t of e.channels??[])t.name&&this.channels.set(t.name,t);await e.start()}}async removeAgent(e){let t=this.instances.get(e);if(t){await t.stop(),this.instances.delete(e),this.agentList=this.agentList.filter(n=>n.name!==e);for(let n of t.channels??[])n.name&&this.channels.delete(n.name)}}isAllIdle(){return this.agentList.every(e=>e.isIdle())}scheduleRestart(e){if(this._restartScheduled)return;this._restartScheduled=!0;let t=(e?.maxWaitMinutes??30)*60*1e3,n=()=>{!this._restarting&&this.isAllIdle()&&this._executeRestart()};if(n(),!this._restarting){for(let r of this.agentList)r.on("agent:complete",n);this._deadlineTimer=setTimeout(()=>{this._executeRestart()},t)}}async _executeRestart(){if(this._restarting)return;this._restarting=!0,this._deadlineTimer&&(clearTimeout(this._deadlineTimer),this._deadlineTimer=void 0),await this.stop();let e=Date.now()+3e4;for(;!this.isAllIdle()&&Date.now()<e;)await new Promise(t=>setTimeout(t,100));this._exit(0)}_exit(e){process.exit(e)}async sendTo(e,t){let n=this.channels.get(e);if(!n)throw new Error(`No channel registered with name "${e}"`);await n.send(t)}getAgent(e){return this.instances.get(e)}getAllAgents(){return Array.from(this.instances.values())}getChannel(e){return this.channels.get(e)}async invoke(e,t){return this._transport.invoke(e,t)}async stop(){for(let e of this.agentList)await e.stop();this.instances.clear(),this.channels.clear(),this.pendingAsks.clear()}getPendingAsk(e){let t=this.pendingAsks.get(e);if(!t||t.length===0)return;let n=new Date;for(;t.length>0;){let r=t[0];if(r.expiresAt&&r.expiresAt<n)t.shift();else break}if(t.length===0){this.pendingAsks.delete(e);return}return t[0]}hasPendingAsks(e){let t=this.pendingAsks.get(e);if(!t||t.length===0)return!1;let n=new Date,r=t.filter(s=>!s.expiresAt||s.expiresAt>=n);return r.length===0?(this.pendingAsks.delete(e),!1):(r.length!==t.length&&this.pendingAsks.set(e,r),r.some(s=>s.status==="pending"))}cleanupExpiredAsks(){let e=0,t=new Date;for(let[n,r]of this.pendingAsks.entries()){let s=r.filter(i=>!i.expiresAt||i.expiresAt>=t);e+=r.length-s.length,s.length===0?this.pendingAsks.delete(n):s.length!==r.length&&this.pendingAsks.set(n,s)}return e}addPendingAsk(e){let t={...e,id:(0,Yt.randomUUID)(),askedAt:new Date,retries:0,status:"pending"},n=this.pendingAsks.get(e.conversationId);return n?n.push(t):this.pendingAsks.set(e.conversationId,[t]),t}incrementRetries(e){for(let t of this.pendingAsks.values()){let n=t.find(r=>r.id===e);if(n)return n.retries+=1,n.retries}}async resolvePendingAsk(e,t){for(let[n,r]of this.pendingAsks.entries()){let s=r.findIndex(i=>i.id===e);if(s!==-1){r[s].status="answered",r[s].answer=t;let i=r[s].channelName;if(r.splice(s,1),r.length>0){let a=r[0];if(i&&i.trim()!=="")try{await this.sendTo(i,{output:a.question})}catch(d){console.error(`[AgentRegistry] Failed to auto-send next ask: ${d instanceof Error?d.message:"Unknown error"}`)}else console.warn(`[AgentRegistry] Cannot auto-send next ask: channelName is empty for conversation ${n}`)}r.length===0&&this.pendingAsks.delete(n);return}}throw new Error(`Pending ask with id "${e}" not found`)}};pe();c();var Xt=require("fs"),Qt=require("child_process"),Zt=require("path"),Ne=class{cwd;debounceMs;onRestartNeeded;onCompileError;spawnFn;watchFn;watchPaths;watchers=[];debounceTimer;constructor(e){this.watchPaths=e.watchPaths,this.cwd=e.cwd??process.cwd(),this.debounceMs=e.debounceMs??3e4,this.onRestartNeeded=e.onRestartNeeded,this.onCompileError=e.onCompileError,this.spawnFn=e.spawnFn??Qt.spawn,this.watchFn=e.watchFn??Xt.watch}start(){for(let e of this.watchPaths){let t=this.watchFn(e,{recursive:!0},(n,r)=>{r&&this._handleFileChange(r)});this.watchers.push(t)}}stop(){for(let e of this.watchers)e.close();this.watchers=[],this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}_handleFileChange(e){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,(0,Zt.basename)(e).startsWith(".env")?this.onRestartNeeded():(e.endsWith(".ts")||e.endsWith(".tsx"))&&this._runCompile()},this.debounceMs)}_runCompile(){return new Promise(e=>{let t="",n=this.spawnFn("npx",["tsc","--build"],{cwd:this.cwd,stdio:["ignore","ignore","pipe"]});n.stderr?.on("data",r=>{t+=r.toString()}),n.on("close",r=>{if(r===0)this.onRestartNeeded();else{let s=t||`tsc --build exited with code ${String(r)}`;this.onCompileError?.(s)}e()}),n.on("error",r=>{let s=r instanceof Error?r.message:String(r);this.onCompileError?.(s),e()})})}};c();L();var en=require("toolpack-sdk"),Gn={...en.AGENT_MODE,name:"research-agent-mode",systemPrompt:["You are a research agent specialized in web research and information gathering.","Use web.search to find relevant information, web.fetch to retrieve content, and web.scrape when needed.","Always cite your sources with URLs.","Provide comprehensive, well-structured summaries.","Flag any conflicting information or uncertainty in your findings."].join(" ")},Oe=class extends E{name="research-agent";description="Web research agent for summarization, fact-finding, competitive analysis, and trend monitoring";mode=Gn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId},e.attachments);return await this.onComplete(t),t}};c();L();var tn=require("toolpack-sdk"),Jn={...tn.CODING_MODE,name:"coding-agent-mode",systemPrompt:["You are a coding agent specialized in software development tasks.","Use coding.* tools for code analysis, fs.* for file operations, and git.* for version control.","Write clean, idiomatic code following best practices.","Always verify your changes and check for potential issues.","Provide clear explanations of your code changes."].join(" ")},$e=class extends E{name="coding-agent";description="Coding agent for code generation, refactoring, debugging, test writing, and code review";mode=Jn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId},e.attachments);return await this.onComplete(t),t}};c();L();var nn=require("toolpack-sdk"),zn={...nn.AGENT_MODE,name:"data-agent-mode",systemPrompt:["You are a data agent specialized in database operations and data analysis.","Use db.* tools for database queries, fs.* for file operations, and http.* for API requests.","Generate clear, well-formatted reports and summaries.","Always validate data integrity and handle errors gracefully.","Provide insights and patterns when analyzing data."].join(" ")},je=class extends E{name="data-agent";description="Data agent for database queries, CSV generation, data analysis, reporting, and aggregation";mode=zn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId},e.attachments);return await this.onComplete(t),t}};c();L();var rn=require("toolpack-sdk"),qn={...rn.CHAT_MODE,name:"browser-agent-mode",systemPrompt:["You are a browser agent specialized in web interaction and content extraction.","Use web.fetch to retrieve pages, web.screenshot for visual content, and web.extract_links for navigation.","Follow links intelligently to gather comprehensive information.","Extract structured data from web pages when possible.","Be mindful of rate limits and respectful of website resources."].join(" ")},Be=class extends E{name="browser-agent";description="Browser agent for web browsing, form interaction, page extraction, and link following";mode=qn;constructor(e){super(e)}async invokeAgent(e){let t=await this.run(e.message||"",void 0,{conversationId:e.conversationId},e.attachments);return await this.onComplete(t),t}};c();var me=require("toolpack-sdk"),R=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 t of e)if(t.type==="file"){let{url:n,mimeType:r,size:s,name:i}=t.file,a=i??n,d=r.startsWith("image/"),p=d?me.FILE_LIMITS.image.maxBytes:me.FILE_LIMITS.document.maxBytes,l=p/(1024*1024);if(s!==void 0&&s>p)throw new Error(`Attachment "${a}" exceeds the ${d?"image":"document"} size limit of ${l} MB`)}else if(t.type==="image_data"&&Math.ceil(t.image_data.data.length*.75)>me.FILE_LIMITS.image.maxBytes){let r=me.FILE_LIMITS.image.maxBytes/1048576;throw new Error(`Inline image exceeds the size limit of ${r} MB`)}}}};c();var Fe=require("crypto");var Le=class extends R{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;botId;allowedChannels;constructor(e){super(),this.config={port:3e3,...e},this.name=e.name;let t=e.channel;this.allowedChannels=t==null?null:Array.isArray(t)?t:[t]}listen(){typeof process<"u"&&import("http").then(e=>{this.server=e.createServer((t,n)=>{this.handleRequest(t,n)}),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 t=await(await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"}})).json();t.ok?(this.botUserId=t.user_id,this.botId=t.bot_id,console.log(`[SlackChannel] Connected as @${t.user} (${t.user_id}) in workspace "${t.team}" \u2014 ${t.url}`)):console.warn(`[SlackChannel] auth.test failed: ${t.error}. Check your bot token.`)}catch(e){console.warn("[SlackChannel] Startup self-check failed (network error):",e)}}verifySignature(e,t){let n=e["x-slack-request-timestamp"],r=e["x-slack-signature"];if(!n||!r||Array.isArray(n)||Array.isArray(r))return!1;let s=parseInt(n,10),i=Math.floor(Date.now()/1e3);if(isNaN(s)||Math.abs(i-s)>300)return!1;let a=`v0:${n}:${t}`,p=`v0=${(0,Fe.createHmac)("sha256",this.config.signingSecret).update(a).digest("hex")}`;if(p.length!==r.length)return!1;try{return(0,Fe.timingSafeEqual)(Buffer.from(p),Buffer.from(r))}catch{return!1}}async send(e){let t=e.metadata?.threadTs??e.metadata?.thread_ts??e.metadata?.threadId,r=e.metadata?.channelId??(this.allowedChannels&&this.allowedChannels.length>0?this.allowedChannels[0]:void 0);if(!r)throw new Error("[SlackChannel] Cannot send: no channel configured and metadata.channelId is missing. Provide a target via SlackChannelConfig.channel or output.metadata.channelId.");let s={channel:r,text:e.output};t&&(s.thread_ts=t);let i=await fetch("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok)throw new Error(`Failed to send Slack message: ${i.statusText}`);let a=await i.json();if(!a.ok)throw new Error(`Slack API error: ${a.error}`)}normalize(e){let t=e,r=(t.text||"").replace(/<(https?:\/\/[^|>]+)\|([^>]+)>/g,"$2 ($1)").replace(/<(https?:\/\/[^>]+)>/g,"$1").replace(/<!here>/g,"@here").replace(/<!channel>/g,"@channel").replace(/<!everyone>/g,"@everyone"),s=t.ts,i=t.thread_ts,a=i!==void 0&&i!==s,d=t.user,p=d?{kind:"user",id:d}:void 0,l=/<@([A-Z0-9]+)>/g,g=[],u;for(;(u=l.exec(r))!==null;)g.push(u[1]);let m=t.channel;return{message:r,conversationId:a?i:m||s||"",data:t,participant:p,context:{user:d,channel:m,team:t.team,channelType:t.channel_type,threadId:a?i:void 0,mentions:g.length>0?g:void 0,channelId:m,channelName:typeof this.config.channel=="string"?this.config.channel:m}}}async resolveParticipant(e){let t=e.participant?.id??e.context?.user;if(!t)return;let n=this.participantCache.get(t);if(n)return n;try{let r=await fetch(`https://slack.com/api/users.info?user=${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`Bearer ${this.config.token}`}});if(!r.ok)return{kind:"user",id:t};let s=await r.json();if(!s.ok||!s.user){let d={kind:"user",id:t};return this.participantCache.set(t,d),d}let i=s.user.profile?.display_name||s.user.profile?.real_name||s.user.real_name||s.user.name||t,a={kind:"user",id:t,displayName:i,metadata:{slackUser:s.user}};return this.participantCache.set(t,a),a}catch{return{kind:"user",id:t}}}invalidateParticipant(e){this.participantCache.delete(e)}shouldProcessEvent(e){let t=e.type;if(t!=="message"&&t!=="app_mention")return!1;if(this.allowedChannels!==null){let i=e.channel_type;if(!(i==="im"||i==="mpim")){let d=e.channel;if(!d||!this.allowedChannels.includes(d))return!1}}let n=e.user;if(this.botUserId&&n===this.botUserId)return!1;let r=e.bot_id;if(console.log(`[SlackChannel:shouldProcessEvent] subtype=${e.subtype} user=${n} bot_id=${r} this.botUserId=${this.botUserId} this.botId=${this.botId}`),!r)return!0;if(this.botId&&r===this.botId)return!1;let s=this.config.blockedBotIds??[];if(s.includes(r)||n!==void 0&&s.includes(n))return!1;if(this.config.allowedBotIds!==void 0){let i=this.config.allowedBotIds;return i.includes(r)||n!==void 0&&i.includes(n)}return!0}handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{if(!this.verifySignature(e.headers,n)){t.writeHead(401),t.end("Invalid signature");return}try{let r=JSON.parse(n);if(r.type==="url_verification"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({challenge:r.challenge}));return}if(r.type==="event_callback"&&r.event){let s=r.event;if(this.shouldProcessEvent(s)){let i=this.normalize(s);this.handleMessage(i)}else s.type==="user_change"&&s.user&&this.invalidateParticipant(s.user.id);t.writeHead(200),t.end("OK");return}t.writeHead(200),t.end("OK")}catch(r){console.error("[SlackChannel] Error handling request:",r),t.writeHead(400),t.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};c();var Ue=class extends R{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((t,n)=>{this.handleRequest(t,n)}),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 t=e.metadata?.conversationId;if(t&&this.pendingResponses.has(t)){let n=this.pendingResponses.get(t);this.pendingResponses.delete(t),n.resolve({output:e.output,metadata:e.metadata})}}normalize(e){let t=e,n=t.headers||{},r=n["x-session-id"]||n["X-Session-Id"]||t.sessionId||t.conversationId||this.generateSessionId();return{message:t.message||t.text||"",intent:t.intent,conversationId:r,data:t,context:{headers:t.headers,method:t.method,sessionId:r}}}handleRequest(e,t){if(e.url!==this.config.path){t.writeHead(404),t.end("Not found");return}if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(n),s=this.normalize(r),i=s.conversationId||this.generateSessionId(),a=new Promise((d,p)=>{this.pendingResponses.set(i,{resolve:d,reject:p}),setTimeout(()=>{this.pendingResponses.has(i)&&(this.pendingResponses.delete(i),p(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:i,context:{...s.context,sessionId:i}}),a.then(d=>{t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(d))}).catch(d=>{t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:d.message}))})}catch(r){console.error("[WebhookChannel] Error handling request:",r),t.writeHead(400,{"Content-Type":"application/json"}),t.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)})}};c();var Rt=require("cron-parser"),Ge=class extends R{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{Rt.CronExpressionParser.parse(e.cron)}catch(t){throw new Error(`ScheduledChannel: invalid cron expression '${e.cron}': ${t.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 t=e,n=new Date,r=`${n.getFullYear()}-${n.getMonth()+1}-${n.getDate()}`;return{intent:t?.intent??this.config.intent,message:t?.message??this.config.message??`Scheduled task triggered at ${n.toISOString()}`,conversationId:`scheduled:${this.name??"default"}:${r}`,data:{...t?.payload??{},scheduled:!0,jobId:t?.id,cron:t?.cron??this.config.cron,timestamp:n.toISOString()}}}_listenStatic(){this._scheduleNextStatic(this._generation)}_scheduleNextStatic(e){if(this._stopped||e!==this._generation)return;let t=this._nextRunFromCron(this.config.cron),n=t.getTime()-Date.now();if(n<=0){this.timer=setTimeout(()=>this._scheduleNextStatic(e),0);return}console.log(`[ScheduledChannel:${this.name??"default"}] Next run: ${t.toISOString()}`),this.timer=setTimeout(async()=>{this._stopped||e!==this._generation||(await this._triggerStatic(),this._scheduleNextStatic(e))},n)}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(t){console.error(`[ScheduledChannel:${this.name??"default"}] Error on trigger:`,t)}}_listenWithStore(){let e=this.config.store,t=this._generation;if(t===1){let r=e.resetStuck(this.name);r>0&&console.log(`[ScheduledChannel:${this.name??"default"}] Reset ${r} stuck 'running' job(s) to 'pending'.`)}if(this.config.cron){let{duplicate:r}=e.create({channelName:this.name,cron:this.config.cron,intent:this.config.intent,message:this.config.message});r||console.log(`[ScheduledChannel:${this.name??"default"}] Seeded static cron '${this.config.cron}' into store.`)}let n=e.getDue(Date.now(),this.name);n.length>0&&(console.log(`[ScheduledChannel:${this.name??"default"}] Recovering ${n.length} overdue job(s).`),Promise.allSettled(n.map(r=>this._triggerJob(r)))),this._scheduleNextFromStore(t)}_scheduleNextFromStore(e){if(this._stopped||e!==this._generation)return;let t=this.config.store,n=t.getNextPending(this.name);if(!n){let s=this.config.idlePollMs??3e4;this.timer=setTimeout(()=>this._scheduleNextFromStore(e),s);return}let r=Math.max(0,n.nextRunAt-Date.now());console.log(`[ScheduledChannel:${this.name??"default"}] Next store job at ${new Date(n.nextRunAt).toISOString()} (in ${Math.round(r/1e3)}s)`),this.timer=setTimeout(async()=>{if(this._stopped||e!==this._generation)return;let s=t.getDue(Date.now(),this.name);await Promise.allSettled(s.map(i=>this._triggerJob(i))),this._scheduleNextFromStore(e)},r)}async _triggerJob(e){let t=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.`),t.markFailed(e.id,"No message handler registered");return}t.markRunning(e.id);let n=this.normalize(e);try{await this.handleMessage(n),t.markCompleted(e.id)}catch(r){let s=r instanceof Error?r.message:String(r);console.error(`[ScheduledChannel:${this.name??"default"}] Job ${e.id} failed:`,r),t.markFailed(e.id,s)}}_nextRunFromCron(e){return Rt.CronExpressionParser.parse(e,{currentDate:new Date}).next().toDate()}};c();var Je=class extends R{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 t=await(await fetch(`https://api.telegram.org/bot${this.config.token}/getMe`)).json();if(t.ok&&t.result){let n=t.result;this.botUserId=n.id!=null?String(n.id):void 0,this.botUsername=n.username,console.log(`[TelegramChannel] Connected as @${n.username} (id: ${n.id}, name: ${n.first_name})`)}else console.warn(`[TelegramChannel] getMe failed: ${t.description??"unknown error"}. Check your bot token.`)}catch(e){console.warn("[TelegramChannel] Startup self-check failed (network error):",e)}}async send(e){let t=e.metadata?.chatId;if(!t)throw new Error("Telegram send requires chatId in metadata");let n=e.metadata?.replyMarkup,r=await fetch(`https://api.telegram.org/bot${this.config.token}/sendMessage`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_id:t,text:e.output,parse_mode:"Markdown",...n?{reply_markup:n}:{}})});if(!r.ok)throw new Error(`Failed to send Telegram message: ${r.statusText}`);let s=await r.json();if(!s.ok)throw new Error(`Telegram API error: ${s.description}`)}async answerCallbackQuery(e,t){let n=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,...t?{text:t}:{}})});if(!n.ok)throw new Error(`Failed to answer Telegram callback query: ${n.statusText}`);let r=await n.json();if(!r.ok)throw new Error(`Telegram API error: ${r.description}`)}normalize(e){let t=e,n=t.callback_query;if(n){let y=n.message||{},b=y.chat||{},w=n.from||{},A=w.id!=null?String(w.id):void 0,x=w.first_name||w.username||A,_=A?{kind:"user",id:A,displayName:x??A}:void 0,I=b.id!=null?String(b.id):"";return{message:n.data??"",conversationId:I,data:t,participant:_,context:{isCallback:!0,callbackQueryId:n.id,callbackData:n.data,chatId:b.id,userId:w.id,username:w.username,firstName:w.first_name,lastName:w.last_name,messageId:y.message_id,channelType:b.type,channelId:I,channelName:b.title}}}let r=t.message||t.edited_message||{},s=r.text||"",i=r.chat||{},a=r.from||{},d=a.id!=null?String(a.id):void 0,p=a.first_name||a.username||d,l=d?{kind:"user",id:d,displayName:p??d}:void 0,g=r.entities??[],u=[];for(let y of g)if(y.type==="text_mention"&&y.user){let b=y.user;b.id!=null&&u.push(String(b.id))}let m=i.type,v=i.id!=null?String(i.id):"";return{message:s,conversationId:v,data:t,participant:l,context:{chatId:i.id,userId:a.id,username:a.username,firstName:a.first_name,lastName:a.last_name,messageId:r.message_id,channelType:m,channelId:v,channelName:i.title,mentions:u.length>0?u:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,t=await fetch(e);if(!t.ok)throw new Error(`Telegram getUpdates failed: ${t.statusText}`);let n=await t.json();if(!n.ok)throw new Error("Telegram getUpdates returned not ok");for(let r of n.result){let s=r.update_id;s>=this.offset&&(this.offset=s+1);try{let i=this.normalize(r);await this.handleMessage(i)}catch(i){console.error("[TelegramChannel] Error processing update:",i)}}}startWebhook(){typeof process>"u"||(console.log("[TelegramChannel] Starting webhook mode"),import("http").then(e=>{this.server=e.createServer((r,s)=>{this.handleWebhookRequest(r,s)});let t=new URL(this.config.webhookUrl||"http://localhost:3000"),n=parseInt(t.port,10)||3e3;this.server.listen(n,()=>{console.log(`[TelegramChannel] Webhook server listening on port ${n}`)}),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 t=await e.json();t.ok?console.log("[TelegramChannel] Webhook set successfully"):console.error("[TelegramChannel] Failed to set webhook:",t.description)}handleWebhookRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end("Method not allowed");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=JSON.parse(n);this.handleMessage(this.normalize(r)).catch(s=>{console.error("[TelegramChannel] Error processing webhook:",s)}),t.writeHead(200),t.end("OK")}catch(r){console.error("[TelegramChannel] Error parsing webhook:",r),t.writeHead(400),t.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)}}};c();var Wn=new Set([1,3]),sn=/<@!?(\d+)>/g,Hn="https://discord.com/api/v10",ze=class extends R{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 t=e,n=t.channelId,r=(n??"")+(t.thread?.id?`:${t.thread.id}`:""),s=t.channel?.type,i=s!==void 0&&Wn.has(s),a=t.author?.id,d=t.author?.globalName??t.author?.username,p=[];if(t.content){sn.lastIndex=0;let l;for(;(l=sn.exec(t.content))!==null;)p.push(l[1])}return{message:t.content,conversationId:r,data:t,participant:a?{kind:"user",id:a,displayName:d??void 0}:void 0,context:{userId:a,username:t.author?.username,channelType:i?"dm":"channel",channelId:n,channelName:t.channel?.name,guildId:t.guildId,threadId:t.thread?.id,messageId:t.id,mentions:p.length>0?p:void 0,isMentioned:this.botUserId?p.includes(this.botUserId):void 0}}}async resolveParticipant(e){let t=e.participant?.id??e.context?.userId;if(!t)return;let n=this.participantCache.get(t);if(n)return n;try{let r=await fetch(`${Hn}/users/${t}`,{headers:{Authorization:`Bot ${this.config.token}`}});if(!r.ok)return console.warn(`[DiscordChannel] Failed to resolve user ${t}: HTTP ${r.status}`),{kind:"user",id:t};let s=await r.json(),i=s.global_name??s.username,a={kind:"user",id:s.id,displayName:i};return this.participantCache.set(t,a),a}catch(r){return console.warn(`[DiscordChannel] resolveParticipant error for ${t}:`,r),{kind:"user",id:t}}}invalidateParticipant(e){this.participantCache.delete(e)}async send(e){if(!this.client)throw new Error("[DiscordChannel] Client not initialized. Did you call listen()?");let t=e.metadata?.threadId;if(t){let s=await this.client.channels.fetch(t);if(s&&"send"in s)try{await s.send({content:e.output});return}catch(i){throw console.error("[DiscordChannel] Failed to send to thread:",i),new Error(`[DiscordChannel] Failed to send Discord message: ${i instanceof Error?i.message:String(i)}`)}console.warn(`[DiscordChannel] Thread ${t} not found or not sendable; falling back to channel send.`)}let n=e.metadata?.channelId??(this.allowedChannelIds.size>0?[...this.allowedChannelIds][0]:void 0);if(!n)throw new Error("[DiscordChannel] No channel ID available for sending. Configure channelId or pass output.metadata.channelId.");let r=await this.client.channels.fetch(n);if(!r||!("send"in r))throw new Error(`[DiscordChannel] Channel ${n} not found or is not a text channel`);try{await r.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:t,GatewayIntentBits:n}=e;this.client=new t({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]}),this.client.on("ready",()=>{let r=this.client.user;this.botUserId=r?.id;let s=this.allowedChannelIds.size===0?"all channels":[...this.allowedChannelIds].join(", "),i=this.config.guildId??"all guilds";console.log(`[DiscordChannel] Logged in as ${r?.tag??"unknown"} (botUserId=${this.botUserId??"unknown"}) | guild=${i} | channels=${s}`)}),this.client.on("messageCreate",r=>{let s=r;if(!this.shouldProcessEvent(s))return;let i=this.normalize(s);this.handleMessage(i)}),this.client.on("userUpdate",(r,s)=>{let i=s;i?.id&&this.invalidateParticipant(i.id)}),this.client.login(this.config.token).catch(r=>{console.error("[DiscordChannel] Failed to login to Discord:",r)})}).catch(e=>{console.error("[DiscordChannel] Failed to initialize Discord client:",e),console.error("[DiscordChannel] Make sure discord.js is installed: npm install discord.js")})}async stop(){this.client&&(await this.client.destroy(),this.client=void 0)}};c();var qe=class extends R{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 t=Array.isArray(this.config.to)?this.config.to:[this.config.to],n=this.config.subject||"Message from Agent",r={from:this.config.from,to:t.join(", "),subject:n,text:e.output,html:this.formatAsHtml(e.output)};try{await this.transporter.sendMail(r)}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(`
35
35
 
36
- `).map(t=>`<p>${t.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};c();var qe=class extends x{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 t=e.metadata?.from||this.config.to;if(!t)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:t})}catch(n){throw console.error("[SMSChannel] Failed to send SMS:",n),new Error(`Failed to send SMS: ${n instanceof Error?n.message:String(n)}`)}}normalize(e){let t=e,n=t.From,r=t.Body,s=t.MessageSid;return{message:r,conversationId:n,data:t,context:{from:n,to:t.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((t,n)=>{this.handleWebhookRequest(t,n)}),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,t){if(e.method!=="POST"||e.url!==this.config.webhookPath){t.writeHead(404),t.end("Not found");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=new URLSearchParams(n),s={};r.forEach((a,l)=>{s[l]=a});let i=this.normalize(s);this.handleMessage(i),t.writeHead(200,{"Content-Type":"text/xml"}),t.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(r){console.error("[SMSChannel] Error handling webhook:",r),t.writeHead(400),t.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};c();var ze=class extends x{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 t=e;return{message:typeof t.message=="string"?t.message:JSON.stringify(t),data:t,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let t=this.normalize(e);return new Promise((n,r)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,r(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=i=>{clearTimeout(s),n(i.output)},this.handleMessage(t).catch(i=>{clearTimeout(s),this._pendingResolve=void 0,r(i instanceof Error?i:new Error(String(i)))})})}asAgentDefinition(e,t){return{name:e.name,description:e.description,...t!==void 0&&{inputSchema:t},invoke:n=>this.trigger(n)}}};c();c();le();var ge=class{agentUrls;constructor(e){this.agentUrls=new Map(Object.entries(e.agents))}async invoke(e,t){let n=this.agentUrls.get(e);if(!n)throw new R(`Agent "${e}" not found in transport configuration. Available agents: ${Array.from(this.agentUrls.keys()).join(", ")}`);let r={jsonrpc:"2.0",method:`agent.invoke:${e}`,params:t,id:Date.now()};try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new R(`HTTP ${s.status}: ${s.statusText}`);let i=await s.json();if(i.error)throw new R(`JSON-RPC error (${i.error.code}): ${i.error.message}`+(i.error.data?` - ${JSON.stringify(i.error.data)}`:""));if(!i.result)throw new R("No result in JSON-RPC response");return i.result}catch(s){throw s instanceof R?s:new R(`Failed to invoke agent "${e}" at ${n}: ${s instanceof Error?s.message:String(s)}`)}}};c();var nn=j(require("http"),1),me=class{agents=new Map;server;port;constructor(e){this.port=e.port}registerAgent(e,t){this.agents.set(e,t)}listen(){this.server=nn.default.createServer(async(e,t)=>{if(e.method!=="POST"){t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Method not allowed"}));return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",async()=>{try{let r=JSON.parse(n),s=await this.handleRequest(r);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(s))}catch(r){let s={jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:r instanceof Error?r.message:String(r)},id:null};t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(s))}})}),this.server.listen(this.port,()=>{console.log(`[AgentJsonRpcServer] Listening on port ${this.port}`),console.log(`[AgentJsonRpcServer] Registered agents: ${Array.from(this.agents.keys()).join(", ")}`)})}async stop(){return new Promise((e,t)=>{if(!this.server){e();return}this.server.close(n=>{n?t(n):(console.log("[AgentJsonRpcServer] Server stopped"),e())})})}async handleRequest(e){if(e.jsonrpc!=="2.0")return{jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request",data:'jsonrpc must be "2.0"'},id:e.id||null};let[t,n]=e.method.split(":");if(t!=="agent.invoke")return{jsonrpc:"2.0",error:{code:-32601,message:"Method not found",data:`Unknown method: ${e.method}`},id:e.id||null};if(!n)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:'Agent name required in method (e.g., "agent.invoke:data-agent")'},id:e.id||null};let r=this.agents.get(n);if(!r)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:`Agent "${n}" not found. Available: ${Array.from(this.agents.keys()).join(", ")}`},id:e.id||null};if(!e.params)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:"params (AgentInput) required"},id:e.id||null};try{return{jsonrpc:"2.0",result:await r.invokeAgent(e.params),id:e.id||null}}catch(s){return{jsonrpc:"2.0",error:{code:-32603,message:"Internal error",data:s instanceof Error?s.message:String(s)},id:e.id||null}}}};c();c();F();var rn=require("toolpack-sdk"),zn={...rn.CHAT_MODE,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(`
37
- `)},he=class extends T{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=zn;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
+ `).map(t=>`<p>${t.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};c();var We=class extends R{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 t=e.metadata?.from||this.config.to;if(!t)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:t})}catch(n){throw console.error("[SMSChannel] Failed to send SMS:",n),new Error(`Failed to send SMS: ${n instanceof Error?n.message:String(n)}`)}}normalize(e){let t=e,n=t.From,r=t.Body,s=t.MessageSid;return{message:r,conversationId:n,data:t,context:{from:n,to:t.To,messageSid:s}}}startWebhookServer(){import("http").then(e=>{this.server=e.createServer((t,n)=>{this.handleWebhookRequest(t,n)}),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,t){if(e.method!=="POST"||e.url!==this.config.webhookPath){t.writeHead(404),t.end("Not found");return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",()=>{try{let r=new URLSearchParams(n),s={};r.forEach((a,d)=>{s[d]=a});let i=this.normalize(s);this.handleMessage(i),t.writeHead(200,{"Content-Type":"text/xml"}),t.end('<?xml version="1.0" encoding="UTF-8"?><Response></Response>')}catch(r){console.error("[SMSChannel] Error handling webhook:",r),t.writeHead(400),t.end("Bad request")}})}async stop(){if(this.server)return new Promise(e=>{this.server.close(e)})}};c();var He=class extends R{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 t=e;return{message:typeof t.message=="string"?t.message:JSON.stringify(t),data:t,conversationId:`mcp-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}}async trigger(e){let t=this.normalize(e);return new Promise((n,r)=>{let s=setTimeout(()=>{this._pendingResolve=void 0,r(new Error(`McpChannel: agent did not respond within ${this._timeout}ms`))},this._timeout);this._pendingResolve=i=>{clearTimeout(s),n(i.output)},this.handleMessage(t).catch(i=>{clearTimeout(s),this._pendingResolve=void 0,r(i instanceof Error?i:new Error(String(i)))})})}asAgentDefinition(e,t){return{name:e.name,description:e.description,...t!==void 0&&{inputSchema:t},invoke:n=>this.trigger(n)}}};c();var Ke=class extends R{isTriggerChannel=!1;constructor(e={}){super(),this.name=e.name}listen(){}async send(e){}normalize(e){let t=e,n=Array.isArray(t.attachments)?t.attachments:void 0;return this.validateAttachments(n),{message:t.message??"",attachments:n,conversationId:t.conversationId??void 0,participant:t.participant,context:{source:"chat"}}}};c();c();pe();var he=class{agentUrls;constructor(e){this.agentUrls=new Map(Object.entries(e.agents))}async invoke(e,t){let n=this.agentUrls.get(e);if(!n)throw new T(`Agent "${e}" not found in transport configuration. Available agents: ${Array.from(this.agentUrls.keys()).join(", ")}`);let r={jsonrpc:"2.0",method:`agent.invoke:${e}`,params:t,id:Date.now()};try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new T(`HTTP ${s.status}: ${s.statusText}`);let i=await s.json();if(i.error)throw new T(`JSON-RPC error (${i.error.code}): ${i.error.message}`+(i.error.data?` - ${JSON.stringify(i.error.data)}`:""));if(!i.result)throw new T("No result in JSON-RPC response");return i.result}catch(s){throw s instanceof T?s:new T(`Failed to invoke agent "${e}" at ${n}: ${s instanceof Error?s.message:String(s)}`)}}};c();var on=$(require("http"),1),fe=class{agents=new Map;server;port;constructor(e){this.port=e.port}registerAgent(e,t){this.agents.set(e,t)}listen(){this.server=on.default.createServer(async(e,t)=>{if(e.method!=="POST"){t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Method not allowed"}));return}let n="";e.on("data",r=>{n+=r.toString()}),e.on("end",async()=>{try{let r=JSON.parse(n),s=await this.handleRequest(r);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(s))}catch(r){let s={jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:r instanceof Error?r.message:String(r)},id:null};t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(s))}})}),this.server.listen(this.port,()=>{console.log(`[AgentJsonRpcServer] Listening on port ${this.port}`),console.log(`[AgentJsonRpcServer] Registered agents: ${Array.from(this.agents.keys()).join(", ")}`)})}async stop(){return new Promise((e,t)=>{if(!this.server){e();return}this.server.close(n=>{n?t(n):(console.log("[AgentJsonRpcServer] Server stopped"),e())})})}async handleRequest(e){if(e.jsonrpc!=="2.0")return{jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request",data:'jsonrpc must be "2.0"'},id:e.id||null};let[t,n]=e.method.split(":");if(t!=="agent.invoke")return{jsonrpc:"2.0",error:{code:-32601,message:"Method not found",data:`Unknown method: ${e.method}`},id:e.id||null};if(!n)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:'Agent name required in method (e.g., "agent.invoke:data-agent")'},id:e.id||null};let r=this.agents.get(n);if(!r)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:`Agent "${n}" not found. Available: ${Array.from(this.agents.keys()).join(", ")}`},id:e.id||null};if(!e.params)return{jsonrpc:"2.0",error:{code:-32602,message:"Invalid params",data:"params (AgentInput) required"},id:e.id||null};try{return{jsonrpc:"2.0",result:await r.invokeAgent(e.params),id:e.id||null}}catch(s){return{jsonrpc:"2.0",error:{code:-32603,message:"Internal error",data:s instanceof Error?s.message:String(s)},id:e.id||null}}}};c();c();L();var an=require("toolpack-sdk"),Kn={...an.CHAT_MODE,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(`
37
+ `)},ye=class extends E{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=Kn;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(`
38
38
  Recent conversation:`);for(let a of t.recentContext)n.push(` ${a.sender}: ${a.content.substring(0,100)}`)}n.push(`
39
39
  Message to classify: "${t.message}"`),t.includeExamples&&(n.push(`
40
40
  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(`
41
41
  Classification (start with direct, indirect, passive, or ignore):`);let r=n.join(`
42
- `),s=await this.run(r),i=this.normalizeClassification(s.output);return{output:i,metadata:{rawOutput:s.output,classification:i,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"}};c();F();var sn=require("toolpack-sdk"),Wn={...sn.CHAT_MODE,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(`
43
- `)},fe=class extends T{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=Wn;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,r=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${r?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let d of t.turns){let p=new Date(d.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),g=d.participant.displayName??d.participant.id,u=d.participant.kind==="agent"?`[BOT] ${g}`:g,m=`[${p}] ${u}: ${d.content.substring(0,200)}`;d.content.length>200&&(m+="..."),d.metadata?.isToolCall&&d.metadata.toolName&&(m+=` [tool: ${d.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let i=s.join(`
44
- `),a=await this.run(i),l=this.parseSummarizerOutput(a.output,t.turns.length);return{output:JSON.stringify(l),metadata:{turnsProcessed:t.turns.length,rawOutputLength:a.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),r=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);r&&(n=r[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)`}};c();c();var We=require("toolpack-sdk");lt();c();function Ct(o,e,t={}){let n=t.maxResults??10,r=t.tokenCap??2e3,s={limit:n,tokenCap:r};return{name:"search_conversation_history",description:["Search the conversation history for messages matching a query.","Use this when you need to recall something specific that was said earlier","in this conversation but is not in your immediate context.","Results are limited to this conversation only."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"The search query \u2014 keywords or phrases to look for in the conversation history."}},required:["query"]},execute:async({query:i})=>{if(!i||i.trim()==="")return"Error: query must not be empty.";let a=await o.search(e,i.trim(),s);if(a.length===0)return`No messages found matching "${i}".`;let l=a.map(d=>{let p=d.participant.displayName??d.participant.id,g=d.participant.kind==="agent"?`${p} (agent)`:p;return`[${new Date(d.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}] ${g}: ${d.content}`});return[`Found ${a.length} result(s) for "${i}":`,"",...l].join(`
45
- `)}}}wt();c();Q();at();c();c();var kt=class{constructor(e){this.maxSize=e}maxSize;cache=new Map;has(e){return this.cache.has(e)}set(e,t){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}size(){return this.cache.size}};function He(o={}){let e=o.maxCacheSize??1e3,t=o.getEventId??(r=>r.context?.eventId),n=new kt(e);return async(r,s,i)=>{let a=t(r);if(a){if(n.has(a))return o.onDuplicate?.(a,r),s.logger?.debug(`Event dedup: dropping duplicate event ${a}`,{eventId:a}),s.skip();n.set(a,!0)}return await i()}}c();function Ke(o){let e=o.getSubtype??(n=>n.context?.subtype),t=new Set(o.denySubtypes);return async(n,r,s)=>{let i=e(n);return i&&t.has(i)?(o.onFiltered?.(i,n),r.logger?.debug(`Noise filter: dropping message with subtype "${i}"`,{subtype:i}),r.skip()):await s()}}c();function Ve(o){return async(e,t,n)=>{let r=o.getSenderId(e),s=o.agentId??t.agent.name;return r&&r===s?(o.onSelfMessage?.(r,e),t.logger?.debug(`Self filter: dropping self-message from ${r}`,{senderId:r,agentId:s}),t.skip()):await n()}}c();var Rt=class{constructor(e){this.maxSize=e}maxSize;cache=new Map;get(e){let t=this.cache.get(e);return t!==void 0&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}size(){return this.cache.size}},xt=class{constructor(e,t,n){this.capacity=e;this.refillRate=t;this.refillInterval=n;this.tokens=e,this.lastRefill=Date.now()}capacity;refillRate;refillInterval;tokens;lastRefill;consume(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}refill(){let e=Date.now(),t=e-this.lastRefill,n=Math.floor(t/this.refillInterval*this.refillRate);n>0&&(this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefill=e)}getTokens(){return this.refill(),this.tokens}};function Ye(o){let e=o.tokensPerInterval??10,t=o.interval??6e4,n=o.maxBuckets??1e3,r=o.onExceeded??"skip",s=new Rt(n);return async(i,a,l)=>{let d=o.getKey(i),p=s.get(d);if(p||(p=new xt(e,e,t),s.set(d,p)),!p.consume()){if(o.onRateLimited?.(d,i),a.logger?.warn(`Rate limit exceeded for key: ${d}`,{key:d}),r==="reject")throw new Error("Rate limit exceeded. Please try again later.");return a.skip()}return await l()}}c();function Xe(o={}){return async(e,t,n)=>{let r;if(o.resolveParticipant)r=await o.resolveParticipant(e);else if(typeof t.channel.resolveParticipant=="function")try{r=await t.channel.resolveParticipant(e)}catch(i){t.logger?.warn("Channel resolveParticipant threw; falling back",{error:i instanceof Error?i.message:"Unknown error"})}let s=r??e.participant;if(s){let i={...e,participant:s,context:{...e.context,_participant:s}};return o.onResolved?.(i,s),t.logger?.debug("Resolved participant",{participantId:s.id,participantKind:s.kind}),await n(i)}return await n()}}dt();c();function Hn(o,e){let t=e.toLowerCase();if(!o.toLowerCase().includes(t))return!1;let r=[],s=/```[\s\S]*?```/g,i;for(;(i=s.exec(o))!==null;)r.push([i.index,i.index+i[0].length]);let a=/`[^`\n]*`/g;for(;(i=a.exec(o))!==null;){let u=i.index,m=u+i[0].length;r.some(([y,v])=>u>=y&&m<=v)||r.push([u,m])}if(r.length===0)return!1;r.sort((u,m)=>u[0]-m[0]);let l="",d=0;for(let[u,m]of r)u>d&&(l+=o.slice(d,u)),d=Math.max(d,m);return d<o.length&&(l+=o.slice(d)),l.toLowerCase().includes(t)?!1:r.some(([u,m])=>o.slice(u,m).toLowerCase().includes(t))}function Qe(o){return async(e,t,n)=>{let r=o.getMessageText(e)??"";if(o.isDirectMessage?.(e)){let m={...e,context:{...e.context,_addressCheck:"direct",_isDM:!0}};return o.onClassified?.("direct",e),await n(m)}let s="ambiguous",i=r.toLowerCase(),a=o.agentName.toLowerCase(),l=m=>m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=l(a),p=o.agentId?`|^@${l(o.agentId)}\\b`:"";if(new RegExp(`^(hey\\s+)?@?${d}\\b${p}`,"i").test(i))s="direct";else if(new RegExp(`\\b(my|our|the)\\s+${d}\\b`,"i").test(i))s="ambiguous";else if(Hn(r,o.agentName))s="ignore";else if(/^https?:\/\//.test(r))s="ignore";else if(o.getMentions){let m=o.getMentions(e),w=m.some(y=>y.toLowerCase()===a||y===o.agentId);w&&m.length>1?s="indirect":w&&(s="ambiguous")}else i.includes(a)?s="ambiguous":s="passive";let u={...e,context:{...e.context,_addressCheck:s}};return o.onClassified?.(s,e),t.logger?.debug(`Address check classified as: ${s}`,{result:s}),await n(u)}}c();function Ze(o){let e=o.classifierAgentName??"intent-classifier";return async(t,n,r)=>{let s=t.context?._addressCheck;if(s==="direct")return await r();if(s==="ignore"||s==="passive")return o.onClassified?.(s,t),n.skip();let i=o.getMessageText(t)??"";if(!i.trim())return await r();let a={message:i,agentName:o.agentName,agentId:o.agentId,senderName:o.getSenderName(t),channelName:o.getChannelName(t),isDirectMessage:o.isDirectMessage?.(t)??!1,recentContext:o.getRecentContext?.(t)};try{let d=(await n.delegateAndWait(e,{message:"classify",data:a,conversationId:t.conversationId})).output.trim();o.onClassified?.(d,t),n.logger?.debug(`Intent classified as: ${d}`,{classification:d});let p={...t,context:{...t.context,_intentClassification:d}};return d==="direct"?await r(p):n.skip()}catch(l){return n.logger?.error("Intent classification failed, allowing message",{error:l instanceof Error?l.message:"Unknown error"}),await r()}}}c();var V=class extends Error{constructor(t,n){super(`Maximum invocation depth exceeded: ${t} > ${n}`);this.currentDepth=t;this.maxDepth=n;this.name="DepthExceededError"}currentDepth;maxDepth};function et(o={}){let e=o.maxDepth??5;return async(t,n,r)=>{if(n.invocationDepth>e)throw o.onDepthExceeded?.(n.invocationDepth,e,t),n.logger?.error(`Depth guard: invocation depth ${n.invocationDepth} exceeds maximum ${e}`,{currentDepth:n.invocationDepth,maxDepth:e}),new V(n.invocationDepth,e);return await r()}}c();Q();function tt(o={}){let e=o.level??"debug",t=o.includeInputData??!1,n=o.includeResultOutput??!1;return async(r,s,i)=>{if(o.shouldTrace&&!o.shouldTrace(r))return await i();let a=e==="info"?s.logger?.info:s.logger?.debug;a?.("Interceptor entry",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,intent:r.intent,input:t?r:void 0});let l=performance.now();try{let d=await i(),p=performance.now()-l;return L(d)?a?.("Interceptor exit: skipped",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:p.toFixed(2)}):a?.("Interceptor exit: success",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:p.toFixed(2),outputLength:d.output.length,result:n?d:void 0}),d}catch(d){let p=performance.now()-l;throw s.logger?.error("Interceptor exit: error",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:p.toFixed(2),error:d instanceof Error?d.message:"Unknown error",errorType:d?.constructor?.name}),d}}}c();Q();var ye=(n=>(n[n.UNSET=0]="UNSET",n[n.OK=1]="OK",n[n.ERROR=2]="ERROR",n))(ye||{});function nt(o={}){let{tracerProvider:e,tracerName:t="toolpack-agents",tracerVersion:n,recordSteps:r=!0,shouldTrace:s}=o,i=e?.getTracer(t,n);return async(a,l,d)=>{if(!i)return await d();if(s&&!s(a))return await d();let p=i.startSpan("agent.invocation");p.setAttribute("agent.name",l.agent.name),p.setAttribute("channel.name",l.channel.name??"unknown"),p.setAttribute("invocation.depth",l.invocationDepth),a.conversationId&&p.setAttribute("conversation.id",a.conversationId),a.intent&&p.setAttribute("agent.intent",a.intent);let g=performance.now();try{let u=await d(),m=performance.now()-g;if(p.setAttribute("duration.ms",Math.round(m)),L(u))p.setAttribute("result.skipped",!0),p.setStatus({code:1});else{if(p.setAttribute("result.output.length",u.output.length),r&&u.steps&&u.steps.length>0){p.setAttribute("steps.total",u.steps.length);let w=u.steps.filter(y=>y.status==="failed");w.length>0&&p.setAttribute("steps.failed",w.length),u.steps.forEach((y,v)=>{let A=`step.${v}`;p.setAttribute(`${A}.description`,y.description),p.setAttribute(`${A}.status`,y.status),y.result?.duration!==void 0&&p.setAttribute(`${A}.duration.ms`,y.result.duration),y.result?.toolsUsed&&y.result.toolsUsed.length>0&&p.setAttribute(`${A}.tools`,y.result.toolsUsed.join(","))})}p.setStatus({code:1})}return u}catch(u){let m=performance.now()-g;p.setAttribute("duration.ms",Math.round(m));let w=u instanceof Error?u:String(u);throw p.recordException(w),p.setStatus({code:2,message:u instanceof Error?u.message:String(u)}),u}finally{p.end()}}}c();c();var on=j(require("better-sqlite3"),1),te=require("cron-parser"),we=class{db;constructor({dbPath:e=":memory:"}={}){this.db=new on.default(e),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this._migrate()}_migrate(){this.db.exec(`
42
+ `),s=await this.run(r),i=this.normalizeClassification(s.output);return{output:i,metadata:{rawOutput:s.output,classification:i,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"}};c();L();var cn=require("toolpack-sdk"),Vn={...cn.CHAT_MODE,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(`
43
+ `)},ve=class extends E{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=Vn;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,r=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${r?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let p of t.turns){let l=new Date(p.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),g=p.participant.displayName??p.participant.id,u=p.participant.kind==="agent"?`[BOT] ${g}`:g,m=`[${l}] ${u}: ${p.content.substring(0,200)}`;p.content.length>200&&(m+="..."),p.metadata?.isToolCall&&p.metadata.toolName&&(m+=` [tool: ${p.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let i=s.join(`
44
+ `),a=await this.run(i),d=this.parseSummarizerOutput(a.output,t.turns.length);return{output:JSON.stringify(d),metadata:{turnsProcessed:t.turns.length,rawOutputLength:a.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),r=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);r&&(n=r[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)`}};c();c();var Ve=require("toolpack-sdk");gt();c();function xt(o,e,t={}){let n=t.maxResults??10,r=t.tokenCap??2e3,s={limit:n,tokenCap:r};return{name:"search_conversation_history",description:["Search the conversation history for messages matching a query.","Use this when you need to recall something specific that was said earlier","in this conversation but is not in your immediate context.","Results are limited to this conversation only."].join(" "),input_schema:{type:"object",properties:{query:{type:"string",description:"The search query \u2014 keywords or phrases to look for in the conversation history."}},required:["query"]},execute:async({query:i})=>{if(!i||i.trim()==="")return"Error: query must not be empty.";let a=await o.search(e,i.trim(),s);if(a.length===0)return`No messages found matching "${i}".`;let d=a.map(p=>{let l=p.participant.displayName??p.participant.id,g=p.participant.kind==="agent"?`${l} (agent)`:l;return`[${new Date(p.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}] ${g}: ${p.content}`});return[`Found ${a.length} result(s) for "${i}":`,"",...d].join(`
45
+ `)}}}It();c();Z();lt();c();c();var St=class{constructor(e){this.maxSize=e}maxSize;cache=new Map;has(e){return this.cache.has(e)}set(e,t){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}size(){return this.cache.size}};function Ye(o={}){let e=o.maxCacheSize??1e3,t=o.getEventId??(r=>r.context?.eventId),n=new St(e);return async(r,s,i)=>{let a=t(r);if(a){if(n.has(a))return o.onDuplicate?.(a,r),s.logger?.debug(`Event dedup: dropping duplicate event ${a}`,{eventId:a}),s.skip();n.set(a,!0)}return await i()}}c();function Xe(o){let e=o.getSubtype??(n=>n.context?.subtype),t=new Set(o.denySubtypes);return async(n,r,s)=>{let i=e(n);return i&&t.has(i)?(o.onFiltered?.(i,n),r.logger?.debug(`Noise filter: dropping message with subtype "${i}"`,{subtype:i}),r.skip()):await s()}}c();function Qe(o){return async(e,t,n)=>{let r=o.getSenderId(e),s=o.agentId??t.agent.name;return r&&r===s?(o.onSelfMessage?.(r,e),t.logger?.debug(`Self filter: dropping self-message from ${r}`,{senderId:r,agentId:s}),t.skip()):await n()}}c();var Tt=class{constructor(e){this.maxSize=e}maxSize;cache=new Map;get(e){let t=this.cache.get(e);return t!==void 0&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}this.cache.set(e,t)}clear(){this.cache.clear()}size(){return this.cache.size}},_t=class{constructor(e,t,n){this.capacity=e;this.refillRate=t;this.refillInterval=n;this.tokens=e,this.lastRefill=Date.now()}capacity;refillRate;refillInterval;tokens;lastRefill;consume(e=1){return this.refill(),this.tokens>=e?(this.tokens-=e,!0):!1}refill(){let e=Date.now(),t=e-this.lastRefill,n=Math.floor(t/this.refillInterval*this.refillRate);n>0&&(this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefill=e)}getTokens(){return this.refill(),this.tokens}};function Ze(o){let e=o.tokensPerInterval??10,t=o.interval??6e4,n=o.maxBuckets??1e3,r=o.onExceeded??"skip",s=new Tt(n);return async(i,a,d)=>{let p=o.getKey(i),l=s.get(p);if(l||(l=new _t(e,e,t),s.set(p,l)),!l.consume()){if(o.onRateLimited?.(p,i),a.logger?.warn(`Rate limit exceeded for key: ${p}`,{key:p}),r==="reject")throw new Error("Rate limit exceeded. Please try again later.");return a.skip()}return await d()}}c();function et(o={}){return async(e,t,n)=>{let r;if(o.resolveParticipant)r=await o.resolveParticipant(e);else if(typeof t.channel.resolveParticipant=="function")try{r=await t.channel.resolveParticipant(e)}catch(i){t.logger?.warn("Channel resolveParticipant threw; falling back",{error:i instanceof Error?i.message:"Unknown error"})}let s=r??e.participant;if(s){let i={...e,participant:s,context:{...e.context,_participant:s}};return o.onResolved?.(i,s),t.logger?.debug("Resolved participant",{participantId:s.id,participantKind:s.kind}),await n(i)}return await n()}}ut();c();function Yn(o,e){let t=e.toLowerCase();if(!o.toLowerCase().includes(t))return!1;let r=[],s=/```[\s\S]*?```/g,i;for(;(i=s.exec(o))!==null;)r.push([i.index,i.index+i[0].length]);let a=/`[^`\n]*`/g;for(;(i=a.exec(o))!==null;){let u=i.index,m=u+i[0].length;r.some(([y,b])=>u>=y&&m<=b)||r.push([u,m])}if(r.length===0)return!1;r.sort((u,m)=>u[0]-m[0]);let d="",p=0;for(let[u,m]of r)u>p&&(d+=o.slice(p,u)),p=Math.max(p,m);return p<o.length&&(d+=o.slice(p)),d.toLowerCase().includes(t)?!1:r.some(([u,m])=>o.slice(u,m).toLowerCase().includes(t))}function tt(o){return async(e,t,n)=>{let r=o.getMessageText(e)??"";if(o.isDirectMessage?.(e)){let m={...e,context:{...e.context,_addressCheck:"direct",_isDM:!0}};return o.onClassified?.("direct",e),await n(m)}let s="ambiguous",i=r.toLowerCase(),a=o.agentName.toLowerCase(),d=m=>m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=d(a),l=o.agentId?`|^@${d(o.agentId)}\\b`:"";if(new RegExp(`^(hey\\s+)?@?${p}\\b${l}`,"i").test(i))s="direct";else if(new RegExp(`\\b(my|our|the)\\s+${p}\\b`,"i").test(i))s="ambiguous";else if(Yn(r,o.agentName))s="ignore";else if(/^https?:\/\//.test(r))s="ignore";else if(o.getMentions){let m=o.getMentions(e),v=m.some(y=>y.toLowerCase()===a||y===o.agentId);v&&m.length>1?s="indirect":v&&(s="ambiguous")}else i.includes(a)?s="ambiguous":s="passive";let u={...e,context:{...e.context,_addressCheck:s}};return o.onClassified?.(s,e),t.logger?.debug(`Address check classified as: ${s}`,{result:s}),await n(u)}}c();function nt(o){let e=o.classifierAgentName??"intent-classifier";return async(t,n,r)=>{let s=t.context?._addressCheck;if(s==="direct")return await r();if(s==="ignore"||s==="passive")return o.onClassified?.(s,t),n.skip();let i=o.getMessageText(t)??"";if(!i.trim())return await r();let a={message:i,agentName:o.agentName,agentId:o.agentId,senderName:o.getSenderName(t),channelName:o.getChannelName(t),isDirectMessage:o.isDirectMessage?.(t)??!1,recentContext:o.getRecentContext?.(t)};try{let p=(await n.delegateAndWait(e,{message:"classify",data:a,conversationId:t.conversationId})).output.trim();o.onClassified?.(p,t),n.logger?.debug(`Intent classified as: ${p}`,{classification:p});let l={...t,context:{...t.context,_intentClassification:p}};return p==="direct"?await r(l):n.skip()}catch(d){return n.logger?.error("Intent classification failed, allowing message",{error:d instanceof Error?d.message:"Unknown error"}),await r()}}}c();var V=class extends Error{constructor(t,n){super(`Maximum invocation depth exceeded: ${t} > ${n}`);this.currentDepth=t;this.maxDepth=n;this.name="DepthExceededError"}currentDepth;maxDepth};function rt(o={}){let e=o.maxDepth??5;return async(t,n,r)=>{if(n.invocationDepth>e)throw o.onDepthExceeded?.(n.invocationDepth,e,t),n.logger?.error(`Depth guard: invocation depth ${n.invocationDepth} exceeds maximum ${e}`,{currentDepth:n.invocationDepth,maxDepth:e}),new V(n.invocationDepth,e);return await r()}}c();Z();function st(o={}){let e=o.level??"debug",t=o.includeInputData??!1,n=o.includeResultOutput??!1;return async(r,s,i)=>{if(o.shouldTrace&&!o.shouldTrace(r))return await i();let a=e==="info"?s.logger?.info:s.logger?.debug;a?.("Interceptor entry",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,intent:r.intent,input:t?r:void 0});let d=performance.now();try{let p=await i(),l=performance.now()-d;return B(p)?a?.("Interceptor exit: skipped",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:l.toFixed(2)}):a?.("Interceptor exit: success",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:l.toFixed(2),outputLength:p.output.length,result:n?p:void 0}),p}catch(p){let l=performance.now()-d;throw s.logger?.error("Interceptor exit: error",{agent:s.agent.name,channel:s.channel.name,depth:s.invocationDepth,conversationId:r.conversationId,durationMs:l.toFixed(2),error:p instanceof Error?p.message:"Unknown error",errorType:p?.constructor?.name}),p}}}c();Z();var we=(n=>(n[n.UNSET=0]="UNSET",n[n.OK=1]="OK",n[n.ERROR=2]="ERROR",n))(we||{});function ot(o={}){let{tracerProvider:e,tracerName:t="toolpack-agents",tracerVersion:n,recordSteps:r=!0,shouldTrace:s}=o,i=e?.getTracer(t,n);return async(a,d,p)=>{if(!i)return await p();if(s&&!s(a))return await p();let l=i.startSpan("agent.invocation");l.setAttribute("agent.name",d.agent.name),l.setAttribute("channel.name",d.channel.name??"unknown"),l.setAttribute("invocation.depth",d.invocationDepth),a.conversationId&&l.setAttribute("conversation.id",a.conversationId),a.intent&&l.setAttribute("agent.intent",a.intent);let g=performance.now();try{let u=await p(),m=performance.now()-g;if(l.setAttribute("duration.ms",Math.round(m)),B(u))l.setAttribute("result.skipped",!0),l.setStatus({code:1});else{if(l.setAttribute("result.output.length",u.output.length),r&&u.steps&&u.steps.length>0){l.setAttribute("steps.total",u.steps.length);let v=u.steps.filter(y=>y.status==="failed");v.length>0&&l.setAttribute("steps.failed",v.length),u.steps.forEach((y,b)=>{let w=`step.${b}`;l.setAttribute(`${w}.description`,y.description),l.setAttribute(`${w}.status`,y.status),y.result?.duration!==void 0&&l.setAttribute(`${w}.duration.ms`,y.result.duration),y.result?.toolsUsed&&y.result.toolsUsed.length>0&&l.setAttribute(`${w}.tools`,y.result.toolsUsed.join(","))})}l.setStatus({code:1})}return u}catch(u){let m=performance.now()-g;l.setAttribute("duration.ms",Math.round(m));let v=u instanceof Error?u:String(u);throw l.recordException(v),l.setStatus({code:2,message:u instanceof Error?u.message:String(u)}),u}finally{l.end()}}}c();c();var dn=$(require("better-sqlite3"),1),ne=require("cron-parser"),be=class{db;constructor({dbPath:e=":memory:"}={}){this.db=new dn.default(e),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this._migrate()}_migrate(){this.db.exec(`
46
46
  CREATE TABLE IF NOT EXISTS scheduled_jobs (
47
47
  id TEXT PRIMARY KEY,
48
48
  channel_name TEXT,
@@ -74,7 +74,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
74
74
 
75
75
  CREATE INDEX IF NOT EXISTS idx_job_runs_job_id
76
76
  ON job_runs (job_id, ran_at DESC);
77
- `)}create(e){if(!e.cron&&!e.runAt)throw new Error("SchedulerStore.create: either cron or runAt must be provided.");if(e.cron&&e.runAt)throw new Error("SchedulerStore.create: provide cron OR runAt, not both.");let t;if(e.cron)try{t=te.CronExpressionParser.parse(e.cron,{currentDate:new Date}).next().toDate().getTime()}catch{throw new Error(`SchedulerStore.create: invalid cron expression '${e.cron}'`)}else if(t=e.runAt instanceof Date?e.runAt.getTime():e.runAt,isNaN(t))throw new Error(`SchedulerStore.create: invalid runAt value '${e.runAt}'`);let n=this._findDuplicate(e,t);if(n)return{job:n,duplicate:!0};let r=crypto.randomUUID(),s=Date.now();return this.db.prepare(`
77
+ `)}create(e){if(!e.cron&&!e.runAt)throw new Error("SchedulerStore.create: either cron or runAt must be provided.");if(e.cron&&e.runAt)throw new Error("SchedulerStore.create: provide cron OR runAt, not both.");let t;if(e.cron)try{t=ne.CronExpressionParser.parse(e.cron,{currentDate:new Date}).next().toDate().getTime()}catch{throw new Error(`SchedulerStore.create: invalid cron expression '${e.cron}'`)}else if(t=e.runAt instanceof Date?e.runAt.getTime():e.runAt,isNaN(t))throw new Error(`SchedulerStore.create: invalid runAt value '${e.runAt}'`);let n=this._findDuplicate(e,t);if(n)return{job:n,duplicate:!0};let r=crypto.randomUUID(),s=Date.now();return this.db.prepare(`
78
78
  INSERT INTO scheduled_jobs
79
79
  (id, channel_name, next_run_at, cron, intent, message, payload, status, created_at)
80
80
  VALUES
@@ -84,7 +84,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
84
84
  ${a}
85
85
  ORDER BY next_run_at ASC
86
86
  LIMIT @limit
87
- `).all(i).map(ve)}getDue(e=Date.now(),t){return(t?this.db.prepare(`
87
+ `).all(i).map(Ae)}getDue(e=Date.now(),t){return(t?this.db.prepare(`
88
88
  SELECT * FROM scheduled_jobs
89
89
  WHERE status = 'pending' AND next_run_at <= @now AND channel_name = @channelName
90
90
  ORDER BY next_run_at ASC
@@ -92,7 +92,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
92
92
  SELECT * FROM scheduled_jobs
93
93
  WHERE status = 'pending' AND next_run_at <= @now
94
94
  ORDER BY next_run_at ASC
95
- `).all({now:e})).map(ve)}getNextPending(e){let t=e?this.db.prepare(`
95
+ `).all({now:e})).map(Ae)}getNextPending(e){let t=e?this.db.prepare(`
96
96
  SELECT * FROM scheduled_jobs
97
97
  WHERE status = 'pending' AND channel_name = @channelName
98
98
  ORDER BY next_run_at ASC LIMIT 1
@@ -100,7 +100,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
100
100
  SELECT * FROM scheduled_jobs
101
101
  WHERE status = 'pending'
102
102
  ORDER BY next_run_at ASC LIMIT 1
103
- `).get();return t?ve(t):void 0}update(e,t){let n=this._getById(e);if(!n)return;if(n.status!=="pending")throw new Error(`Cannot update job ${e}: status is '${n.status}', expected 'pending'.`);if(t.cron!==void 0&&t.runAt!==void 0)throw new Error(`Cannot update job ${e}: provide cron OR runAt, not both.`);let r=[],s={id:e};if(t.cron!==void 0){try{te.CronExpressionParser.parse(t.cron)}catch{throw new Error(`Invalid cron expression '${t.cron}'`)}r.push("cron = @cron"),s.cron=t.cron;let i=te.CronExpressionParser.parse(t.cron,{currentDate:new Date});s.nextRunAt=i.next().toDate().getTime(),r.push("next_run_at = @nextRunAt")}if(t.runAt!==void 0){let i=t.runAt instanceof Date?t.runAt.getTime():t.runAt;if(isNaN(i))throw new Error(`Cannot update job ${e}: invalid runAt value '${t.runAt}'`);s.nextRunAt=i,r.push("next_run_at = @nextRunAt"),r.push("cron = NULL")}return t.message!==void 0&&(r.push("message = @message"),s.message=t.message),t.intent!==void 0&&(r.push("intent = @intent"),s.intent=t.intent),t.payload!==void 0&&(r.push("payload = @payload"),s.payload=JSON.stringify(t.payload)),r.length===0?n:(this.db.prepare(`
103
+ `).get();return t?Ae(t):void 0}update(e,t){let n=this._getById(e);if(!n)return;if(n.status!=="pending")throw new Error(`Cannot update job ${e}: status is '${n.status}', expected 'pending'.`);if(t.cron!==void 0&&t.runAt!==void 0)throw new Error(`Cannot update job ${e}: provide cron OR runAt, not both.`);let r=[],s={id:e};if(t.cron!==void 0){try{ne.CronExpressionParser.parse(t.cron)}catch{throw new Error(`Invalid cron expression '${t.cron}'`)}r.push("cron = @cron"),s.cron=t.cron;let i=ne.CronExpressionParser.parse(t.cron,{currentDate:new Date});s.nextRunAt=i.next().toDate().getTime(),r.push("next_run_at = @nextRunAt")}if(t.runAt!==void 0){let i=t.runAt instanceof Date?t.runAt.getTime():t.runAt;if(isNaN(i))throw new Error(`Cannot update job ${e}: invalid runAt value '${t.runAt}'`);s.nextRunAt=i,r.push("next_run_at = @nextRunAt"),r.push("cron = NULL")}return t.message!==void 0&&(r.push("message = @message"),s.message=t.message),t.intent!==void 0&&(r.push("intent = @intent"),s.intent=t.intent),t.payload!==void 0&&(r.push("payload = @payload"),s.payload=JSON.stringify(t.payload)),r.length===0?n:(this.db.prepare(`
104
104
  UPDATE scheduled_jobs SET ${r.join(", ")} WHERE id = @id
105
105
  `).run(s),this._getById(e))}cancel(e){return this.db.prepare(`
106
106
  UPDATE scheduled_jobs SET status = 'cancelled'
@@ -114,7 +114,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
114
114
  UPDATE scheduled_jobs SET status = 'running' WHERE id = @id
115
115
  `).run({id:e})}markCompleted(e,t){let n=this._getById(e);if(!n)return;let r=Date.now(),s=t??r;if(this.db.prepare(`
116
116
  INSERT INTO job_runs (job_id, outcome, ran_at, duration_ms) VALUES (@id, 'completed', @ranAt, @duration)
117
- `).run({id:e,ranAt:s,duration:r-s}),n.cron){let i;try{i=te.CronExpressionParser.parse(n.cron,{currentDate:new Date}).next().toDate().getTime()}catch{this.markFailed(e,`markCompleted: corrupt cron expression '${n.cron}'`);return}this.db.prepare(`
117
+ `).run({id:e,ranAt:s,duration:r-s}),n.cron){let i;try{i=ne.CronExpressionParser.parse(n.cron,{currentDate:new Date}).next().toDate().getTime()}catch{this.markFailed(e,`markCompleted: corrupt cron expression '${n.cron}'`);return}this.db.prepare(`
118
118
  UPDATE scheduled_jobs
119
119
  SET status = 'pending', last_run_at = @now, next_run_at = @nextRunAt, last_error = NULL
120
120
  WHERE id = @id
@@ -124,7 +124,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
124
124
  WHERE id = @id
125
125
  `).run({id:e,now:r})}markFailed(e,t,n){let r=this._getById(e);if(!r)return;let s=Date.now(),i=n??s;if(this.db.prepare(`
126
126
  INSERT INTO job_runs (job_id, outcome, ran_at, duration_ms, error) VALUES (@id, 'failed', @ranAt, @duration, @error)
127
- `).run({id:e,ranAt:i,duration:s-i,error:t}),r.cron){let a;try{a=te.CronExpressionParser.parse(r.cron,{currentDate:new Date}).next().toDate().getTime()}catch{this.db.prepare(`
127
+ `).run({id:e,ranAt:i,duration:s-i,error:t}),r.cron){let a;try{a=ne.CronExpressionParser.parse(r.cron,{currentDate:new Date}).next().toDate().getTime()}catch{this.db.prepare(`
128
128
  UPDATE scheduled_jobs
129
129
  SET status = 'failed', last_run_at = @now,
130
130
  last_error = @compositeError
@@ -139,7 +139,7 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
139
139
  WHERE id = @id
140
140
  `).run({id:e,now:s,error:t})}getHistory(e,t=20){return this.db.prepare(`
141
141
  SELECT * FROM job_runs WHERE job_id = @id ORDER BY ran_at DESC LIMIT @limit
142
- `).all({id:e,limit:t}).map(r=>({id:r.id,jobId:r.job_id,outcome:r.outcome,ranAt:r.ran_at,durationMs:r.duration_ms??void 0,error:r.error??void 0}))}_getById(e){let t=this.db.prepare("SELECT * FROM scheduled_jobs WHERE id = @id").get({id:e});return t?ve(t):null}_findDuplicate(e,t){let n;return e.cron?n=this.db.prepare(`
142
+ `).all({id:e,limit:t}).map(r=>({id:r.id,jobId:r.job_id,outcome:r.outcome,ranAt:r.ran_at,durationMs:r.duration_ms??void 0,error:r.error??void 0}))}_getById(e){let t=this.db.prepare("SELECT * FROM scheduled_jobs WHERE id = @id").get({id:e});return t?Ae(t):null}_findDuplicate(e,t){let n;return e.cron?n=this.db.prepare(`
143
143
  SELECT * FROM scheduled_jobs
144
144
  WHERE status = 'pending'
145
145
  AND cron = @cron
@@ -153,8 +153,8 @@ Classification (start with direct, indirect, passive, or ignore):`);let r=n.join
153
153
  AND (intent IS @intent OR (intent IS NULL AND @intent IS NULL))
154
154
  AND (channel_name IS @channelName OR (channel_name IS NULL AND @channelName IS NULL))
155
155
  LIMIT 1
156
- `).get({nextRunAt:t,intent:e.intent??null,channelName:e.channelName??null}),n?ve(n):null}close(){this.db.close()}};function ve(o){return{id:o.id,channelName:o.channel_name??void 0,nextRunAt:o.next_run_at,cron:o.cron??void 0,intent:o.intent??void 0,message:o.message??void 0,payload:o.payload?JSON.parse(o.payload):void 0,status:o.status,lastRunAt:o.last_run_at??void 0,lastError:o.last_error??void 0,createdAt:o.created_at}}c();function St(o){return{manifest:{key:"scheduler",name:"scheduler",displayName:"Scheduler",version:"1.0.0",description:"Tools for the agent to manage its own scheduled invocations.",category:"scheduler",tools:["scheduler.create","scheduler.list","scheduler.cancel","scheduler.update"]},tools:[{name:"scheduler.create",displayName:"Schedule Job",category:"scheduler",description:["Schedule a future agent invocation.","Provide `cron` for a recurring job or `run_at` (ISO timestamp) for a one-shot job.","The scheduler deduplicates: if a pending job with the same intent + cron (or run_at) + channel already exists, it returns the existing job without creating a duplicate."].join(" "),parameters:{type:"object",properties:{intent:{type:"string",description:'Intent hint forwarded to the agent on trigger (e.g. "weekly_report").'},message:{type:"string",description:"Message forwarded to the agent on trigger."},cron:{type:"string",description:'Cron expression for recurring jobs. E.g. "0 9 * * 1" = 9am every Monday.'},run_at:{type:"string",description:'ISO 8601 timestamp for a one-shot job. E.g. "2026-07-01T09:00:00Z".'},channel_name:{type:"string",description:"Optional channel name to scope this job."},payload:{type:"object",description:"Optional extra data merged into AgentInput.data on trigger."}},required:[]},execute:async e=>{if(!e.cron&&!e.run_at)return"Error: provide either `cron` (recurring) or `run_at` (one-shot).";if(e.cron&&e.run_at)return"Error: provide `cron` OR `run_at`, not both.";if(e.run_at){let t=new Date(e.run_at);if(isNaN(t.getTime()))return`Error: invalid run_at value "${e.run_at}". Provide an ISO 8601 timestamp, e.g. "2026-07-01T09:00:00Z".`}try{let{job:t,duplicate:n}=o.create({intent:e.intent,message:e.message,cron:e.cron,runAt:e.run_at?new Date(e.run_at):void 0,channelName:e.channel_name,payload:e.payload});return n?[`A pending job with the same schedule already exists (id: ${t.id}).`,`Next run: ${new Date(t.nextRunAt).toISOString()}`,"No new job was created."].join(" "):[`Job scheduled (id: ${t.id}).`,t.cron?`Recurring \u2014 cron: "${t.cron}". Next run: ${new Date(t.nextRunAt).toISOString()}.`:`One-shot \u2014 runs at: ${new Date(t.nextRunAt).toISOString()}.`].join(" ")}catch(t){return`Error: ${t.message}`}}},{name:"scheduler.list",displayName:"List Scheduled Jobs",category:"scheduler",description:'List scheduled jobs. Defaults to pending jobs only. Use status="all" to include completed/failed/cancelled.',parameters:{type:"object",properties:{status:{type:"string",enum:["pending","running","completed","failed","cancelled","all"],description:'Filter by job status. Default: "pending".'},channel_name:{type:"string",description:"Filter by channel name."},limit:{type:"number",description:"Maximum number of jobs to return (default: 10, max: 50)."}},required:[]},execute:async e=>{let t=Math.min(e.limit??10,50),n=o.list({status:e.status??"pending",channelName:e.channel_name,limit:t});if(n.length===0)return"No scheduled jobs found.";let r=n.map(s=>{let i=new Date(s.nextRunAt).toISOString(),a=s.cron?`recurring (${s.cron})`:"one-shot",l=s.intent?` intent="${s.intent}"`:"",d=s.lastError?` [last_error: ${s.lastError}]`:"";return`- id=${s.id} status=${s.status} type=${a}${l} next_run=${i}${d}`});return[`${n.length} job(s):`,...r].join(`
157
- `)}},{name:"scheduler.cancel",displayName:"Cancel Scheduled Job",category:"scheduler",description:"Cancel a pending scheduled job by its ID.",parameters:{type:"object",properties:{job_id:{type:"string",description:"The ID of the job to cancel."}},required:["job_id"]},execute:async e=>e.job_id?o.cancel(e.job_id)?`Job ${e.job_id} has been cancelled.`:`Job ${e.job_id} not found or is not in pending state.`:"Error: job_id is required."},{name:"scheduler.update",displayName:"Update Scheduled Job",category:"scheduler",description:"Modify an existing pending job \u2014 change its cron expression, run time, intent, message, or payload.",parameters:{type:"object",properties:{job_id:{type:"string",description:"The ID of the job to update."},cron:{type:"string",description:"New cron expression (updates nextRunAt automatically)."},run_at:{type:"string",description:"Override the next run time (ISO 8601). Also clears the cron expression, converting the job to a one-shot. Use `cron` if you want the job to remain recurring."},intent:{type:"string",description:"New intent."},message:{type:"string",description:"New message."},payload:{type:"object",description:"New payload (replaces existing)."}},required:["job_id"]},execute:async e=>{if(!e.job_id)return"Error: job_id is required.";if(e.cron&&e.run_at)return"Error: provide `cron` OR `run_at`, not both.";if(e.run_at){let t=new Date(e.run_at);if(isNaN(t.getTime()))return`Error: invalid run_at value "${e.run_at}". Provide an ISO 8601 timestamp, e.g. "2026-07-01T09:00:00Z".`}try{let t=o.update(e.job_id,{cron:e.cron,runAt:e.run_at?new Date(e.run_at):void 0,intent:e.intent,message:e.message,payload:e.payload});return t?[`Job ${t.id} updated.`,`Next run: ${new Date(t.nextRunAt).toISOString()}.`].join(" "):`Job ${e.job_id} not found.`}catch(t){return`Error: ${t.message}`}}}]}}c();c();c();c();c();var rt=require("fs"),Ae=class o{_cases;constructor(e=[]){this._cases=[...e]}get cases(){return[...this._cases]}get size(){return this._cases.length}get(e){return this._cases.find(t=>t.id===e)}add(...e){let t=new Set(this._cases.map(n=>n.id));for(let n of e){if(t.has(n.id))throw new Error(`EvalDataset: case with id "${n.id}" already exists.`);t.add(n.id)}return this._cases.push(...e),this}remove(e){let t=this._cases.length;return this._cases=this._cases.filter(n=>n.id!==e),this._cases.length<t}filter(e){return new o(this._cases.filter(e))}toJSON(){return[...this._cases]}save(e){(0,rt.writeFileSync)(e,JSON.stringify(this._cases,null,2),"utf-8")}static load(e){let t=(0,rt.readFileSync)(e,"utf-8"),n=JSON.parse(t);return new o(n)}static from(e){return new o(e)}};c();var be=class{agent;constructor(e){this.agent=e}async run(e,t={}){let n=t.runId??new Date().toISOString(),r=Math.max(1,t.concurrency??1),s=new Date().toISOString(),i=Date.now(),a=e.cases,l=[];for(let d=0;d<a.length;d+=r){let p=a.slice(d,d+r),g=await Promise.all(p.map(async u=>{let m=Date.now();try{let w=await this.agent.invokeAgent({message:u.input.message,intent:u.input.intent,conversationId:u.input.conversationId,context:u.input.context});return{evalCase:u,actualOutput:w.output,durationMs:Date.now()-m}}catch(w){return{evalCase:u,actualOutput:"",durationMs:Date.now()-m,error:w instanceof Error?w.message:String(w)}}}));l.push(...g)}return{runId:n,startedAt:s,completedAt:new Date().toISOString(),totalDurationMs:Date.now()-i,results:l}}};c();function st(o,e){let t=e.filter(r=>r.verdict==="pass").length,n=e.length-t;return{run:o,scoredResults:e,passCount:t,failCount:n,passRate:e.length===0?0:t/e.length}}function B(o,e,t){let n={caseResult:o,verdict:e};return t!==void 0&&(n.explanation=t),n}var Ie=class{trim;caseInsensitive;constructor(e={}){this.trim=e.trim??!0,this.caseInsensitive=e.caseInsensitive??!1}async score(e){let t=e.results.map(n=>{if(n.error)return B(n,"fail",`Agent threw: ${n.error}`);let r=n.actualOutput,s=n.evalCase.expectedOutput;return this.trim&&(r=r.trim(),s=s.trim()),this.caseInsensitive&&(r=r.toLowerCase(),s=s.toLowerCase()),B(n,r===s?"pass":"fail")});return st(e,t)}},Ce=class{caseInsensitive;constructor(e={}){this.caseInsensitive=e.caseInsensitive??!0}async score(e){let t=e.results.map(n=>{if(n.error)return B(n,"fail",`Agent threw: ${n.error}`);let r=n.actualOutput,s=n.evalCase.expectedOutput;this.caseInsensitive&&(r=r.toLowerCase(),s=s.toLowerCase());let i=r.includes(s);return B(n,i?"pass":"fail")});return st(e,t)}},Vn=`You are an impartial evaluator assessing whether an AI agent's answer is correct.
156
+ `).get({nextRunAt:t,intent:e.intent??null,channelName:e.channelName??null}),n?Ae(n):null}close(){this.db.close()}};function Ae(o){return{id:o.id,channelName:o.channel_name??void 0,nextRunAt:o.next_run_at,cron:o.cron??void 0,intent:o.intent??void 0,message:o.message??void 0,payload:o.payload?JSON.parse(o.payload):void 0,status:o.status,lastRunAt:o.last_run_at??void 0,lastError:o.last_error??void 0,createdAt:o.created_at}}c();function Et(o){return{manifest:{key:"scheduler",name:"scheduler",displayName:"Scheduler",version:"1.0.0",description:"Tools for the agent to manage its own scheduled invocations.",category:"scheduler",tools:["scheduler.create","scheduler.list","scheduler.cancel","scheduler.update"]},tools:[{name:"scheduler.create",displayName:"Schedule Job",category:"scheduler",description:["Schedule a future agent invocation.","Provide `cron` for a recurring job or `run_at` (ISO timestamp) for a one-shot job.","The scheduler deduplicates: if a pending job with the same intent + cron (or run_at) + channel already exists, it returns the existing job without creating a duplicate."].join(" "),parameters:{type:"object",properties:{intent:{type:"string",description:'Intent hint forwarded to the agent on trigger (e.g. "weekly_report").'},message:{type:"string",description:"Message forwarded to the agent on trigger."},cron:{type:"string",description:'Cron expression for recurring jobs. E.g. "0 9 * * 1" = 9am every Monday.'},run_at:{type:"string",description:'ISO 8601 timestamp for a one-shot job. E.g. "2026-07-01T09:00:00Z".'},channel_name:{type:"string",description:"Optional channel name to scope this job."},payload:{type:"object",description:"Optional extra data merged into AgentInput.data on trigger."}},required:[]},execute:async e=>{if(!e.cron&&!e.run_at)return"Error: provide either `cron` (recurring) or `run_at` (one-shot).";if(e.cron&&e.run_at)return"Error: provide `cron` OR `run_at`, not both.";if(e.run_at){let t=new Date(e.run_at);if(isNaN(t.getTime()))return`Error: invalid run_at value "${e.run_at}". Provide an ISO 8601 timestamp, e.g. "2026-07-01T09:00:00Z".`}try{let{job:t,duplicate:n}=o.create({intent:e.intent,message:e.message,cron:e.cron,runAt:e.run_at?new Date(e.run_at):void 0,channelName:e.channel_name,payload:e.payload});return n?[`A pending job with the same schedule already exists (id: ${t.id}).`,`Next run: ${new Date(t.nextRunAt).toISOString()}`,"No new job was created."].join(" "):[`Job scheduled (id: ${t.id}).`,t.cron?`Recurring \u2014 cron: "${t.cron}". Next run: ${new Date(t.nextRunAt).toISOString()}.`:`One-shot \u2014 runs at: ${new Date(t.nextRunAt).toISOString()}.`].join(" ")}catch(t){return`Error: ${t.message}`}}},{name:"scheduler.list",displayName:"List Scheduled Jobs",category:"scheduler",description:'List scheduled jobs. Defaults to pending jobs only. Use status="all" to include completed/failed/cancelled.',parameters:{type:"object",properties:{status:{type:"string",enum:["pending","running","completed","failed","cancelled","all"],description:'Filter by job status. Default: "pending".'},channel_name:{type:"string",description:"Filter by channel name."},limit:{type:"number",description:"Maximum number of jobs to return (default: 10, max: 50)."}},required:[]},execute:async e=>{let t=Math.min(e.limit??10,50),n=o.list({status:e.status??"pending",channelName:e.channel_name,limit:t});if(n.length===0)return"No scheduled jobs found.";let r=n.map(s=>{let i=new Date(s.nextRunAt).toISOString(),a=s.cron?`recurring (${s.cron})`:"one-shot",d=s.intent?` intent="${s.intent}"`:"",p=s.lastError?` [last_error: ${s.lastError}]`:"";return`- id=${s.id} status=${s.status} type=${a}${d} next_run=${i}${p}`});return[`${n.length} job(s):`,...r].join(`
157
+ `)}},{name:"scheduler.cancel",displayName:"Cancel Scheduled Job",category:"scheduler",description:"Cancel a pending scheduled job by its ID.",parameters:{type:"object",properties:{job_id:{type:"string",description:"The ID of the job to cancel."}},required:["job_id"]},execute:async e=>e.job_id?o.cancel(e.job_id)?`Job ${e.job_id} has been cancelled.`:`Job ${e.job_id} not found or is not in pending state.`:"Error: job_id is required."},{name:"scheduler.update",displayName:"Update Scheduled Job",category:"scheduler",description:"Modify an existing pending job \u2014 change its cron expression, run time, intent, message, or payload.",parameters:{type:"object",properties:{job_id:{type:"string",description:"The ID of the job to update."},cron:{type:"string",description:"New cron expression (updates nextRunAt automatically)."},run_at:{type:"string",description:"Override the next run time (ISO 8601). Also clears the cron expression, converting the job to a one-shot. Use `cron` if you want the job to remain recurring."},intent:{type:"string",description:"New intent."},message:{type:"string",description:"New message."},payload:{type:"object",description:"New payload (replaces existing)."}},required:["job_id"]},execute:async e=>{if(!e.job_id)return"Error: job_id is required.";if(e.cron&&e.run_at)return"Error: provide `cron` OR `run_at`, not both.";if(e.run_at){let t=new Date(e.run_at);if(isNaN(t.getTime()))return`Error: invalid run_at value "${e.run_at}". Provide an ISO 8601 timestamp, e.g. "2026-07-01T09:00:00Z".`}try{let t=o.update(e.job_id,{cron:e.cron,runAt:e.run_at?new Date(e.run_at):void 0,intent:e.intent,message:e.message,payload:e.payload});return t?[`Job ${t.id} updated.`,`Next run: ${new Date(t.nextRunAt).toISOString()}.`].join(" "):`Job ${e.job_id} not found.`}catch(t){return`Error: ${t.message}`}}}]}}c();c();c();c();c();var it=require("fs"),Ie=class o{_cases;constructor(e=[]){this._cases=[...e]}get cases(){return[...this._cases]}get size(){return this._cases.length}get(e){return this._cases.find(t=>t.id===e)}add(...e){let t=new Set(this._cases.map(n=>n.id));for(let n of e){if(t.has(n.id))throw new Error(`EvalDataset: case with id "${n.id}" already exists.`);t.add(n.id)}return this._cases.push(...e),this}remove(e){let t=this._cases.length;return this._cases=this._cases.filter(n=>n.id!==e),this._cases.length<t}filter(e){return new o(this._cases.filter(e))}toJSON(){return[...this._cases]}save(e){(0,it.writeFileSync)(e,JSON.stringify(this._cases,null,2),"utf-8")}static load(e){let t=(0,it.readFileSync)(e,"utf-8"),n=JSON.parse(t);return new o(n)}static from(e){return new o(e)}};c();var Ce=class{agent;constructor(e){this.agent=e}async run(e,t={}){let n=t.runId??new Date().toISOString(),r=Math.max(1,t.concurrency??1),s=new Date().toISOString(),i=Date.now(),a=e.cases,d=[];for(let p=0;p<a.length;p+=r){let l=a.slice(p,p+r),g=await Promise.all(l.map(async u=>{let m=Date.now();try{let v=await this.agent.invokeAgent({message:u.input.message,intent:u.input.intent,conversationId:u.input.conversationId,context:u.input.context});return{evalCase:u,actualOutput:v.output,durationMs:Date.now()-m}}catch(v){return{evalCase:u,actualOutput:"",durationMs:Date.now()-m,error:v instanceof Error?v.message:String(v)}}}));d.push(...g)}return{runId:n,startedAt:s,completedAt:new Date().toISOString(),totalDurationMs:Date.now()-i,results:d}}};c();function at(o,e){let t=e.filter(r=>r.verdict==="pass").length,n=e.length-t;return{run:o,scoredResults:e,passCount:t,failCount:n,passRate:e.length===0?0:t/e.length}}function j(o,e,t){let n={caseResult:o,verdict:e};return t!==void 0&&(n.explanation=t),n}var ke=class{trim;caseInsensitive;constructor(e={}){this.trim=e.trim??!0,this.caseInsensitive=e.caseInsensitive??!1}async score(e){let t=e.results.map(n=>{if(n.error)return j(n,"fail",`Agent threw: ${n.error}`);let r=n.actualOutput,s=n.evalCase.expectedOutput;return this.trim&&(r=r.trim(),s=s.trim()),this.caseInsensitive&&(r=r.toLowerCase(),s=s.toLowerCase()),j(n,r===s?"pass":"fail")});return at(e,t)}},Re=class{caseInsensitive;constructor(e={}){this.caseInsensitive=e.caseInsensitive??!0}async score(e){let t=e.results.map(n=>{if(n.error)return j(n,"fail",`Agent threw: ${n.error}`);let r=n.actualOutput,s=n.evalCase.expectedOutput;this.caseInsensitive&&(r=r.toLowerCase(),s=s.toLowerCase());let i=r.includes(s);return j(n,i?"pass":"fail")});return at(e,t)}},Qn=`You are an impartial evaluator assessing whether an AI agent's answer is correct.
158
158
 
159
159
  Question / Task:
160
160
  {{question}}
@@ -166,6 +166,6 @@ Actual answer:
166
166
  {{actual}}
167
167
 
168
168
  Is the actual answer correct or equivalent to the expected answer?
169
- Respond with ONLY "pass" or "fail" on the first line, then optionally a one-sentence explanation.`,ke=class{judgeAgent;promptTemplate;constructor(e,t={}){this.judgeAgent=e,this.promptTemplate=t.promptTemplate??Vn}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(B(n,"fail",`Agent threw: ${n.error}`));continue}let r=this.promptTemplate.replace("{{question}}",n.evalCase.input.message).replace("{{expected}}",n.evalCase.expectedOutput).replace("{{actual}}",n.actualOutput);try{let i=(await this.judgeAgent.invokeAgent({message:r})).output.trim().split(`
170
- `),a=i[0].toLowerCase().startsWith("pass")?"pass":"fail",l=i.slice(1).join(" ").trim()||void 0;t.push(B(n,a,l))}catch(s){t.push(B(n,"fail",`Judge threw: ${s instanceof Error?s.message:String(s)}`))}}return st(e,t)}},Re=class{fn;constructor(e){this.fn=e}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(B(n,"fail",`Agent threw: ${n.error}`));continue}try{let{verdict:r,explanation:s}=await this.fn(n);t.push(B(n,r,s))}catch(r){t.push(B(n,"fail",`Scorer threw: ${r instanceof Error?r.message:String(r)}`))}}return st(e,t)}};c();function Tt(o,e){let t=new Map(o.scoredResults.map(p=>[p.caseResult.evalCase.id,p])),n=new Map(e.scoredResults.map(p=>[p.caseResult.evalCase.id,p])),r=[],s=[],i=[],a=[],l=new Set([...t.keys(),...n.keys()]);for(let p of l){let g=t.get(p),u=n.get(p);!g||!u||(g.verdict==="pass"&&u.verdict==="fail"?r.push({caseId:p,baselineOutput:g.caseResult.actualOutput,candidateOutput:u.caseResult.actualOutput}):g.verdict==="fail"&&u.verdict==="pass"?s.push({caseId:p,baselineOutput:g.caseResult.actualOutput,candidateOutput:u.caseResult.actualOutput}):g.verdict==="pass"&&u.verdict==="pass"?i.push(p):a.push(p))}let d=e.passRate-o.passRate;return{baselineRunId:o.run.runId,candidateRunId:e.run.runId,baselinePassRate:o.passRate,candidatePassRate:e.passRate,delta:d,regressions:r,improvements:s,stablePasses:i,stableFails:a}}function _t(o){let e=[],t=o.delta>=0?"+":"",n=r=>`${(r*100).toFixed(1)}%`;if(e.push(`Eval Report: ${o.baselineRunId} \u2192 ${o.candidateRunId}`),e.push(`Pass rate: ${n(o.baselinePassRate)} \u2192 ${n(o.candidatePassRate)} (\u0394${t}${n(o.delta)})`),e.push(""),o.regressions.length>0){e.push(`Regressions (${o.regressions.length}):`);for(let r of o.regressions)e.push(` \u2717 ${r.caseId}`),e.push(` baseline: ${ot(r.baselineOutput)}`),e.push(` candidate: ${ot(r.candidateOutput)}`);e.push("")}if(o.improvements.length>0){e.push(`Improvements (${o.improvements.length}):`);for(let r of o.improvements)e.push(` \u2713 ${r.caseId}`),e.push(` baseline: ${ot(r.baselineOutput)}`),e.push(` candidate: ${ot(r.candidateOutput)}`);e.push("")}return e.push(`Stable passes: ${o.stablePasses.length} | Stable fails: ${o.stableFails.length}`),e.join(`
171
- `)}function ot(o,e=80){let t=o.replace(/\n/g," ");return t.length>e?`${t.slice(0,e)}\u2026`:t}c();0&&(module.exports={AgentError,AgentJsonRpcServer,AgentMind,AgentRegistry,BaseAgent,BaseChannel,BrowserAgent,CodingAgent,ContainsScorer,CustomScorer,DataAgent,DepthExceededError,DiscordChannel,EmailChannel,EphemeralAgent,EvalDataset,EvalRunner,ExactMatchScorer,HotReloadWatcher,InMemoryConversationStore,IntentClassifierAgent,InvocationDepthExceededError,JsonRpcTransport,LLMJudgeScorer,LocalTransport,McpChannel,OTelSpanStatusCode,ResearchAgent,SKIP_SENTINEL,SMSChannel,ScheduledChannel,SchedulerStore,SlackChannel,SummarizerAgent,TelegramChannel,WebhookChannel,assemblePrompt,compareEvalRuns,composeChain,createAddressCheckInterceptor,createCaptureInterceptor,createConversationSearchTool,createDepthGuardInterceptor,createEventDedupInterceptor,createIntentClassifierInterceptor,createNoiseFilterInterceptor,createOTelTracerInterceptor,createParticipantResolverInterceptor,createRateLimitInterceptor,createSchedulerTools,createSelfFilterInterceptor,createTracerInterceptor,executeChain,formatEvalReport,isSkipSentinel,skip});
169
+ Respond with ONLY "pass" or "fail" on the first line, then optionally a one-sentence explanation.`,xe=class{judgeAgent;promptTemplate;constructor(e,t={}){this.judgeAgent=e,this.promptTemplate=t.promptTemplate??Qn}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(j(n,"fail",`Agent threw: ${n.error}`));continue}let r=this.promptTemplate.replace("{{question}}",n.evalCase.input.message).replace("{{expected}}",n.evalCase.expectedOutput).replace("{{actual}}",n.actualOutput);try{let i=(await this.judgeAgent.invokeAgent({message:r})).output.trim().split(`
170
+ `),a=i[0].toLowerCase().startsWith("pass")?"pass":"fail",d=i.slice(1).join(" ").trim()||void 0;t.push(j(n,a,d))}catch(s){t.push(j(n,"fail",`Judge threw: ${s instanceof Error?s.message:String(s)}`))}}return at(e,t)}},Se=class{fn;constructor(e){this.fn=e}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(j(n,"fail",`Agent threw: ${n.error}`));continue}try{let{verdict:r,explanation:s}=await this.fn(n);t.push(j(n,r,s))}catch(r){t.push(j(n,"fail",`Scorer threw: ${r instanceof Error?r.message:String(r)}`))}}return at(e,t)}};c();function Pt(o,e){let t=new Map(o.scoredResults.map(l=>[l.caseResult.evalCase.id,l])),n=new Map(e.scoredResults.map(l=>[l.caseResult.evalCase.id,l])),r=[],s=[],i=[],a=[],d=new Set([...t.keys(),...n.keys()]);for(let l of d){let g=t.get(l),u=n.get(l);!g||!u||(g.verdict==="pass"&&u.verdict==="fail"?r.push({caseId:l,baselineOutput:g.caseResult.actualOutput,candidateOutput:u.caseResult.actualOutput}):g.verdict==="fail"&&u.verdict==="pass"?s.push({caseId:l,baselineOutput:g.caseResult.actualOutput,candidateOutput:u.caseResult.actualOutput}):g.verdict==="pass"&&u.verdict==="pass"?i.push(l):a.push(l))}let p=e.passRate-o.passRate;return{baselineRunId:o.run.runId,candidateRunId:e.run.runId,baselinePassRate:o.passRate,candidatePassRate:e.passRate,delta:p,regressions:r,improvements:s,stablePasses:i,stableFails:a}}function Mt(o){let e=[],t=o.delta>=0?"+":"",n=r=>`${(r*100).toFixed(1)}%`;if(e.push(`Eval Report: ${o.baselineRunId} \u2192 ${o.candidateRunId}`),e.push(`Pass rate: ${n(o.baselinePassRate)} \u2192 ${n(o.candidatePassRate)} (\u0394${t}${n(o.delta)})`),e.push(""),o.regressions.length>0){e.push(`Regressions (${o.regressions.length}):`);for(let r of o.regressions)e.push(` \u2717 ${r.caseId}`),e.push(` baseline: ${ct(r.baselineOutput)}`),e.push(` candidate: ${ct(r.candidateOutput)}`);e.push("")}if(o.improvements.length>0){e.push(`Improvements (${o.improvements.length}):`);for(let r of o.improvements)e.push(` \u2713 ${r.caseId}`),e.push(` baseline: ${ct(r.baselineOutput)}`),e.push(` candidate: ${ct(r.candidateOutput)}`);e.push("")}return e.push(`Stable passes: ${o.stablePasses.length} | Stable fails: ${o.stableFails.length}`),e.join(`
171
+ `)}function ct(o,e=80){let t=o.replace(/\n/g," ");return t.length>e?`${t.slice(0,e)}\u2026`:t}c();0&&(module.exports={AgentError,AgentJsonRpcServer,AgentMind,AgentRegistry,BaseAgent,BaseChannel,BrowserAgent,ChatChannel,CodingAgent,ContainsScorer,CustomScorer,DataAgent,DepthExceededError,DiscordChannel,EmailChannel,EphemeralAgent,EvalDataset,EvalRunner,ExactMatchScorer,HotReloadWatcher,InMemoryConversationStore,IntentClassifierAgent,InvocationDepthExceededError,JsonRpcTransport,LLMJudgeScorer,LocalTransport,McpChannel,OTelSpanStatusCode,ResearchAgent,SKIP_SENTINEL,SMSChannel,ScheduledChannel,SchedulerStore,SlackChannel,SummarizerAgent,TelegramChannel,WebhookChannel,assemblePrompt,compareEvalRuns,composeChain,createAddressCheckInterceptor,createCaptureInterceptor,createConversationSearchTool,createDepthGuardInterceptor,createEventDedupInterceptor,createIntentClassifierInterceptor,createNoiseFilterInterceptor,createOTelTracerInterceptor,createParticipantResolverInterceptor,createRateLimitInterceptor,createSchedulerTools,createSelfFilterInterceptor,createTracerInterceptor,executeChain,formatEvalReport,isSkipSentinel,skip});