@toolpack-sdk/agents 2.2.0 → 2.3.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.js CHANGED
@@ -1,17 +1,17 @@
1
- var ft=Object.defineProperty;var M=(o,e)=>()=>(o&&(e=o(o=0)),e);var yt=(o,e)=>{for(var t in e)ft(o,t,{get:e[t],enumerable:!0})};import bn from"path";import{fileURLToPath as kn}from"url";var d=M(()=>{"use strict"});import{randomUUID as ue}from"crypto";var pe,ge,me,he,fe,h,W,Qe=M(()=>{"use strict";d();pe=.6,ge=.2,me=.2,he={low:.3,medium:.6,high:1},fe=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"},W=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,u=Math.exp(-i/fe)*ge+he.high*me+pe;return{...s,score:u}}).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(u=>this.chunkToGoal(u.chunk));else{let a=r;if(i=(await this._getAllByMeta(c=>c[h.type]==="goal"&&c[h.status]===a)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();i=i.filter(l=>l.description.toLowerCase().includes(c))}}return s?.length&&(i=i.filter(a=>s.every(u=>a.tags.includes(u)))),i.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:r=0,tags:s,includeExpired:i=!1}=t,a=Date.now(),u=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[h.type]:"belief"}}),c=[];for(let l of u){let g=this.chunkToBelief(l.chunk);if(!i&&g.expiresAt&&g.expiresAt<a||s?.length&&!s.every(A=>g.tags.includes(A)))continue;let p=(a-g.createdAt)/864e5,m=Math.exp(-p/fe),w=g.error?.3:he[g.confidence],v=l.score*pe+m*ge+w*me;v<r||c.push({...g,score:v})}return c.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(),u={[h.type]:"reflection"};i===!0&&(u[h.pinned]=!0);let c=await this.provider.query(e,{limit:n*4,threshold:0,filter:u}),l=[];for(let g of c){let p=this.chunkToReflection(g.chunk);if(i===!1&&p.pinned||s?.length&&!s.every(A=>p.tags.includes(A)))continue;let m=(a-p.createdAt)/864e5,w=Math.exp(-m/fe),v=g.score*pe+w*ge+he.medium*me;v<r||l.push({...p,score:v})}return l.sort((g,p)=>p.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=ue();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=ue();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=ue();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 ye(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 Ze(o){if(/^\d{4}-\d{2}-\d{2}/.test(o))return o;let e=ye(o);return new Date(Date.now()+e).toISOString().slice(0,10)}function et(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 ve(o){return Math.ceil(o.length/4)}var we=M(()=>{"use strict";d()});import{randomUUID as Ct}from"crypto";var K,tt=M(()=>{"use strict";d();we();K=class{constructor(e,t,n,r,s,i){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=r;this.committedGoalCount=s;this.committedPinnedReflectionCount=i}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),r,s=e.expiresIn??e.ttlDefault;s&&(r=t+ye(s));let i=this._findSimilarInDraft(n);if(i!==null){let c=this.ops[i],l=e.confidence,g=c.confidence,p={low:0,medium:1,high:2},m=p[l]>p[g]||e.allowDowngrade&&p[l]<p[g];return this.ops[i]={...c,content:e.content,confidence:m?l:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:c.existingId??`draft-${i}`}}let a=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(a){let c=a.belief,l=e.confidence,g=c.confidence,p={low:0,medium:1,high:2},m=p[l]>p[g]||e.allowDowngrade&&p[l]<p[g],w={op:"believe",content:e.content,confidence:m?l:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:a.id};return this.ops.push(w),{action:"updated_store",id:a.id}}let u={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(u),{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?Ze(e.dueBy):void 0,n={op:"set_goal",tempId:Ct(),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;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;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){let r=n;await this.store.addGoal({type:"goal",description:r.description,priority:r.priority,status:"active",tags:r.tags,dueBy:r.dueBy,progress:[],createdAt:r.createdAt,updatedAt:r.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(et(e,s.vector)>=this.deduplicationThreshold)return r}return null}}});function nt(o,e,t){return[kt(o,t),Rt(o,e,t),xt(e,t),St(e),Et(e,t),Tt(o,e),_t(o)]}function kt(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,u=t.includeExpired===!0,c=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 w=await o.keywordSearchGoals(n,{limit:l,status:s,tags:i});for(let v of w)g.push(Mt(v))}if(m&&(r==="belief"||r==="all")){let w=await o.queryBeliefs(m,{limit:l,threshold:c,tags:i,includeExpired:u});for(let v of w)g.push(Pt(v))}if(m&&(r==="reflection"||r==="all")){let w=await o.queryReflections(m,{limit:l,threshold:c,tags:i,pinned:a});for(let v of w)g.push(Dt(v))}return g}}}function Rt(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 xt(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 St(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 Et(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 Tt(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 _t(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 Mt(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 Pt(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 Dt(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 rt=M(()=>{"use strict";d()});async function st(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=>Ot(g)),a=n.map(g=>`- ${g.content}`),{beliefLines:u,reflectionLines:c}=Nt(r,s,e.tokenBudget);if(i.length===0&&a.length===0&&u.length===0&&c.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("")),u.length>0&&(l.push("## Beliefs"),l.push(...u),l.push("")),c.length>0&&(l.push("## Recent Reflections"),l.push(...c),l.push("")),l.push("---"),l.join(`
2
- `)}function Ot(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 Nt(o,e,t){let n=t,r=[],s=[];for(let i of o){let a=`- ${i.content} (${i.confidence} confidence)`,u=ve(a);if(u>n)break;r.push(a),n-=u}for(let i of e){let u=`- [${new Date(i.createdAt).toISOString().slice(0,10)}] ${i.content}`,c=ve(u);if(c>n)break;s.push(u),n-=c}return{beliefLines:r,reflectionLines:s}}var ot=M(()=>{"use strict";d();we()});var it={};yt(it,{AgentMind:()=>V});function qt(o,e){let t=Math.min(e.maxGoals??Bt,Jt),n=Math.min(e.maxPinnedReflections??Lt,zt);return{tokenBudget:e.tokenBudget??$t,recencyWindowDays:e.recencyWindowDays??jt,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??Ut,retrievalThreshold:e.retrievalThreshold??Ft,ttlDefaults:{belief:e.ttlDefaults?.belief??Gt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${o}`}}var $t,jt,Bt,Lt,Ut,Ft,Gt,Jt,zt,V,Ae=M(()=>{"use strict";d();Qe();tt();rt();ot();$t=300,jt=7,Bt=10,Lt=10,Ut=.85,Ft=.35,Gt="30d",Jt=10,zt=10,V=class o{constructor(e,t){this.store=e;this.config=t}store;config;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=qt(e,t),s=new W(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(),st(this.store,this.config)]),r=new K(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),s=nt(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()}}});d();d();d();import{EventEmitter as Ht}from"events";import{Toolpack as Wt,InMemoryConversationStore as Kt}from"toolpack-sdk";d();d();var D=Symbol("interceptor-skip-sentinel");function _(o){return o===D}function J(){return D}var j=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function z(o,e,t,n,r={}){let s=r.maxInvocationDepth??5;return{async execute(i){let u=(l=>({agent:e,channel:t,registry:n,invocationDepth:l,delegateAndWait:async(g,p)=>{let m=l+1;if(m>s)throw new j(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 v={message:p.message??"",intent:p.intent,data:p.data,context:p.context,conversationId:p.conversationId??i.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(v)},skip:J}))(0),c=async l=>{let g=l??i;return await e.invokeAgent(g)};for(let l=o.length-1;l>=0;l--){let g=o[l],p=c;c=async m=>await g(m??i,u,p)}return await c()}}}async function q(o,e){let t=await o.execute(e);return t===D?null:t}d();import{randomUUID as Ye}from"crypto";function vt(o){let e=o.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var B=Symbol.for("toolpack:capture-history");function L(o){let e=o.captureAgentReplies??!0,t=o.getScope??vt,n=o.getMessageId??(i=>i.context?.messageId??i.context?.eventId??Ye()),r=o.getMentions??(i=>i.context?.mentions??[]),s=async(i,a,u)=>{let c=i.conversationId;if(!c)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await u();let l=i.participant;if(l){let p={id:n(i),conversationId:c,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(p),o.onCaptured?.(p),a.logger?.debug("[capture-history] Captured inbound message",{messageId:p.id,participantId:l.id,conversationId:c})}catch(m){a.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let g=await u();if(e&&!_(g)&&g.output!=null){let p={kind:"agent",id:a.agent.name,displayName:a.agent.name},m={id:Ye(),conversationId:c,participant:p,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:c})}catch(w){a.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return g};return s[B]=!0,s}d();import{randomUUID as wt}from"crypto";function Xe(o){return Math.ceil(o.length/4)}function At(o){return{id:o.id,participant:o.participant,content:o.content,timestamp:o.timestamp}}function It(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 bt(o,e,t){return!!(o.participant.id===e||o.metadata?.mentions?.some(n=>t.has(n)))}async function H(o,e,t,n,r={},s){let{scope:i,addressedOnlyMode:a=!0,tokenBudget:u=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:l,maxTurnsToLoad:g=100,agentAliases:p}=r,m=new Set([t,...p??[]]),w=l!==void 0?new Date(Date.now()-l*60*1e3).toISOString():void 0,v=await o.get(e,{scope:i,sinceTimestamp:w,limit:g}),A=v.length;if(a){let R=new Set;for(let x=0;x<v.length;x++){let $=v[x];if(bt($,t,m)&&R.add($.id),x<v.length-1){let P=v[x+1];P.participant.kind==="agent"&&P.participant.id===t&&R.add($.id)}}let T=v[v.length-1];T&&R.add(T.id),v=v.filter(x=>R.has(x.id))}let k=!1;if(v.length>c&&s){let R=Math.floor(v.length/2),T=v.slice(0,R),x=v.slice(R),$=T.filter(P=>!P.metadata?.isSummary);try{let P=await s.invokeAgent({message:"summarize",data:{turns:$.map(At),agentName:n,agentId:t,maxTokens:Math.floor(u*.25),extractDecisions:!0}}),Ke=JSON.parse(P.output),Ve={id:`summary-${wt()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${Ke.turnsSummarized} earlier turns]: ${Ke.summary}`,timestamp:T[0].timestamp,scope:i??"channel",metadata:{isSummary:!0}};v=[Ve,...x],k=!0;try{await o.append(Ve),await o.deleteMessages(e,T.map(ht=>ht.id))}catch{}}catch{v=v.slice(-c)}}else v.length>c&&(v=v.slice(-c));let E=v.map(R=>It(R,t));if(E.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:A,hasSummary:k};let G=E[E.length-1],We=[G],le=Xe(G.content);for(let R=E.length-2;R>=0;R--){let T=E[R],x=Xe(T.content);if(le+x>u)break;We.unshift(T),le+=x}return{messages:We,estimatedTokens:le,turnsLoaded:A,hasSummary:k}}d();var I=class extends Error{constructor(e){super(e),this.name="AgentError"}};var C=class extends Ht{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Kt,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Wt.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(Ae(),it));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,n){let r=n?.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 u=await this._mind.createRunContext();i=u.mindHeader,a=u.tools,s=u.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let u=[];if(i&&u.push({role:"system",content:i}),r)try{let p=await H(this.conversationHistory,r,this.name,this.name,this._resolveAssemblerOptions()),m=p.messages[p.messages.length-1],w=e.trim(),A=w!==""&&m?.role==="user"&&typeof m.content=="string"&&(m.content===w||m.content.endsWith(`: ${w}`))?p.messages.slice(0,-1):p.messages;u.push(...A)}catch{}e.trim()&&u.push({role:"user",content:e});let c=[...a];if(r){let p=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async m=>{let w=await p.search(r,String(m.query??""),{limit:typeof m.limit=="number"?m.limit:5});return{results:w.map(v=>({role:v.participant.kind==="agent"?"assistant":"user",content:v.content,timestamp:v.timestamp})),count:w.length}}})}if(this.delegation?.enabled&&this._registry){let p=this.delegation.allowedAgents,m=this._registry.getAllAgents().filter(w=>w.name!==this.name&&(p===void 0||p.includes(w.name)));if(m.length>0){let w=m.map(A=>A.name),v=m.map(A=>`- ${A.name}: ${A.description}`).join(`
1
+ var ft=Object.defineProperty;var M=(o,e)=>()=>(o&&(e=o(o=0)),e);var yt=(o,e)=>{for(var t in e)ft(o,t,{get:e[t],enumerable:!0})};import bn from"path";import{fileURLToPath as kn}from"url";var d=M(()=>{"use strict"});import{randomUUID as ue}from"crypto";var pe,ge,me,he,fe,h,W,Qe=M(()=>{"use strict";d();pe=.6,ge=.2,me=.2,he={low:.3,medium:.6,high:1},fe=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"},W=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,u=Math.exp(-i/fe)*ge+he.high*me+pe;return{...s,score:u}}).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(u=>this.chunkToGoal(u.chunk));else{let a=r;if(i=(await this._getAllByMeta(c=>c[h.type]==="goal"&&c[h.status]===a)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();i=i.filter(l=>l.description.toLowerCase().includes(c))}}return s?.length&&(i=i.filter(a=>s.every(u=>a.tags.includes(u)))),i.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:r=0,tags:s,includeExpired:i=!1}=t,a=Date.now(),u=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[h.type]:"belief"}}),c=[];for(let l of u){let g=this.chunkToBelief(l.chunk);if(!i&&g.expiresAt&&g.expiresAt<a||s?.length&&!s.every(A=>g.tags.includes(A)))continue;let p=(a-g.createdAt)/864e5,m=Math.exp(-p/fe),w=g.error?.3:he[g.confidence],v=l.score*pe+m*ge+w*me;v<r||c.push({...g,score:v})}return c.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(),u={[h.type]:"reflection"};i===!0&&(u[h.pinned]=!0);let c=await this.provider.query(e,{limit:n*4,threshold:0,filter:u}),l=[];for(let g of c){let p=this.chunkToReflection(g.chunk);if(i===!1&&p.pinned||s?.length&&!s.every(A=>p.tags.includes(A)))continue;let m=(a-p.createdAt)/864e5,w=Math.exp(-m/fe),v=g.score*pe+w*ge+he.medium*me;v<r||l.push({...p,score:v})}return l.sort((g,p)=>p.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=ue();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=ue();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=ue();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 ye(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 Ze(o){if(/^\d{4}-\d{2}-\d{2}/.test(o))return o;let e=ye(o);return new Date(Date.now()+e).toISOString().slice(0,10)}function et(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 ve(o){return Math.ceil(o.length/4)}var we=M(()=>{"use strict";d()});import{randomUUID as Ct}from"crypto";var K,tt=M(()=>{"use strict";d();we();K=class{constructor(e,t,n,r,s,i){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=r;this.committedGoalCount=s;this.committedPinnedReflectionCount=i}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),r,s=e.expiresIn??e.ttlDefault;s&&(r=t+ye(s));let i=this._findSimilarInDraft(n);if(i!==null){let c=this.ops[i],l=e.confidence,g=c.confidence,p={low:0,medium:1,high:2},m=p[l]>p[g]||e.allowDowngrade&&p[l]<p[g];return this.ops[i]={...c,content:e.content,confidence:m?l:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:c.existingId??`draft-${i}`}}let a=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(a){let c=a.belief,l=e.confidence,g=c.confidence,p={low:0,medium:1,high:2},m=p[l]>p[g]||e.allowDowngrade&&p[l]<p[g],w={op:"believe",content:e.content,confidence:m?l:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:a.id};return this.ops.push(w),{action:"updated_store",id:a.id}}let u={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:r,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(u),{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?Ze(e.dueBy):void 0,n={op:"set_goal",tempId:Ct(),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;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;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){let r=n;await this.store.addGoal({type:"goal",description:r.description,priority:r.priority,status:"active",tags:r.tags,dueBy:r.dueBy,progress:[],createdAt:r.createdAt,updatedAt:r.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(et(e,s.vector)>=this.deduplicationThreshold)return r}return null}}});function nt(o,e,t){return[kt(o,t),Rt(o,e,t),xt(e,t),St(e),Tt(e,t),Et(o,e),_t(o)]}function kt(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,u=t.includeExpired===!0,c=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 w=await o.keywordSearchGoals(n,{limit:l,status:s,tags:i});for(let v of w)g.push(Mt(v))}if(m&&(r==="belief"||r==="all")){let w=await o.queryBeliefs(m,{limit:l,threshold:c,tags:i,includeExpired:u});for(let v of w)g.push(Pt(v))}if(m&&(r==="reflection"||r==="all")){let w=await o.queryReflections(m,{limit:l,threshold:c,tags:i,pinned:a});for(let v of w)g.push(Dt(v))}return g}}}function Rt(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 xt(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 St(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 Tt(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 Et(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 _t(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 Mt(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 Pt(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 Dt(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 rt=M(()=>{"use strict";d()});async function st(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=>Ot(g)),a=n.map(g=>`- ${g.content}`),{beliefLines:u,reflectionLines:c}=Nt(r,s,e.tokenBudget);if(i.length===0&&a.length===0&&u.length===0&&c.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("")),u.length>0&&(l.push("## Beliefs"),l.push(...u),l.push("")),c.length>0&&(l.push("## Recent Reflections"),l.push(...c),l.push("")),l.push("---"),l.join(`
2
+ `)}function Ot(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 Nt(o,e,t){let n=t,r=[],s=[];for(let i of o){let a=`- ${i.content} (${i.confidence} confidence)`,u=ve(a);if(u>n)break;r.push(a),n-=u}for(let i of e){let u=`- [${new Date(i.createdAt).toISOString().slice(0,10)}] ${i.content}`,c=ve(u);if(c>n)break;s.push(u),n-=c}return{beliefLines:r,reflectionLines:s}}var ot=M(()=>{"use strict";d();we()});var it={};yt(it,{AgentMind:()=>V});function qt(o,e){let t=Math.min(e.maxGoals??Bt,Jt),n=Math.min(e.maxPinnedReflections??Lt,zt);return{tokenBudget:e.tokenBudget??$t,recencyWindowDays:e.recencyWindowDays??jt,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??Ut,retrievalThreshold:e.retrievalThreshold??Ft,ttlDefaults:{belief:e.ttlDefaults?.belief??Gt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${o}`}}var $t,jt,Bt,Lt,Ut,Ft,Gt,Jt,zt,V,Ae=M(()=>{"use strict";d();Qe();tt();rt();ot();$t=300,jt=7,Bt=10,Lt=10,Ut=.85,Ft=.35,Gt="30d",Jt=10,zt=10,V=class o{constructor(e,t){this.store=e;this.config=t}store;config;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=qt(e,t),s=new W(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(),st(this.store,this.config)]),r=new K(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),s=nt(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()}}});d();d();d();import{EventEmitter as Ht}from"events";import{Toolpack as Wt,InMemoryConversationStore as Kt}from"toolpack-sdk";d();d();var D=Symbol("interceptor-skip-sentinel");function _(o){return o===D}function J(){return D}var j=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function z(o,e,t,n,r={}){let s=r.maxInvocationDepth??5;return{async execute(i){let u=(l=>({agent:e,channel:t,registry:n,invocationDepth:l,delegateAndWait:async(g,p)=>{let m=l+1;if(m>s)throw new j(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 v={message:p.message??"",intent:p.intent,data:p.data,context:p.context,conversationId:p.conversationId??i.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(v)},skip:J}))(0),c=async l=>{let g=l??i;return await e.invokeAgent(g)};for(let l=o.length-1;l>=0;l--){let g=o[l],p=c;c=async m=>await g(m??i,u,p)}return await c()}}}async function q(o,e){let t=await o.execute(e);return t===D?null:t}d();import{randomUUID as Ye}from"crypto";function vt(o){let e=o.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var B=Symbol.for("toolpack:capture-history");function L(o){let e=o.captureAgentReplies??!0,t=o.getScope??vt,n=o.getMessageId??(i=>i.context?.messageId??i.context?.eventId??Ye()),r=o.getMentions??(i=>i.context?.mentions??[]),s=async(i,a,u)=>{let c=i.conversationId;if(!c)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await u();let l=i.participant;if(l){let p={id:n(i),conversationId:c,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(p),o.onCaptured?.(p),a.logger?.debug("[capture-history] Captured inbound message",{messageId:p.id,participantId:l.id,conversationId:c})}catch(m){a.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let g=await u();if(e&&!_(g)&&g.output!=null){let p={kind:"agent",id:a.agent.name,displayName:a.agent.name},m={id:Ye(),conversationId:c,participant:p,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:c})}catch(w){a.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return g};return s[B]=!0,s}d();import{randomUUID as wt}from"crypto";function Xe(o){return Math.ceil(o.length/4)}function At(o){return{id:o.id,participant:o.participant,content:o.content,timestamp:o.timestamp}}function It(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 bt(o,e,t){return!!(o.participant.id===e||o.metadata?.mentions?.some(n=>t.has(n)))}async function H(o,e,t,n,r={},s){let{scope:i,addressedOnlyMode:a=!0,tokenBudget:u=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:l,maxTurnsToLoad:g=100,agentAliases:p}=r,m=new Set([t,...p??[]]),w=l!==void 0?new Date(Date.now()-l*60*1e3).toISOString():void 0,v=await o.get(e,{scope:i,sinceTimestamp:w,limit:g}),A=v.length;if(a){let R=new Set;for(let x=0;x<v.length;x++){let $=v[x];if(bt($,t,m)&&R.add($.id),x<v.length-1){let P=v[x+1];P.participant.kind==="agent"&&P.participant.id===t&&R.add($.id)}}let E=v[v.length-1];E&&R.add(E.id),v=v.filter(x=>R.has(x.id))}let k=!1;if(v.length>c&&s){let R=Math.floor(v.length/2),E=v.slice(0,R),x=v.slice(R),$=E.filter(P=>!P.metadata?.isSummary);try{let P=await s.invokeAgent({message:"summarize",data:{turns:$.map(At),agentName:n,agentId:t,maxTokens:Math.floor(u*.25),extractDecisions:!0}}),Ke=JSON.parse(P.output),Ve={id:`summary-${wt()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${Ke.turnsSummarized} earlier turns]: ${Ke.summary}`,timestamp:E[0].timestamp,scope:i??"channel",metadata:{isSummary:!0}};v=[Ve,...x],k=!0;try{await o.append(Ve),await o.deleteMessages(e,E.map(ht=>ht.id))}catch{}}catch{v=v.slice(-c)}}else v.length>c&&(v=v.slice(-c));let T=v.map(R=>It(R,t));if(T.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:A,hasSummary:k};let G=T[T.length-1],We=[G],le=Xe(G.content);for(let R=T.length-2;R>=0;R--){let E=T[R],x=Xe(E.content);if(le+x>u)break;We.unshift(E),le+=x}return{messages:We,estimatedTokens:le,turnsLoaded:A,hasSummary:k}}d();var I=class extends Error{constructor(e){super(e),this.name="AgentError"}};var C=class extends Ht{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Kt,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Wt.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(Ae(),it));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,n){let r=n?.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 u=await this._mind.createRunContext();i=u.mindHeader,a=u.tools,s=u.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let u=[];if(i&&u.push({role:"system",content:i}),r)try{let p=await H(this.conversationHistory,r,this.name,this.name,this._resolveAssemblerOptions()),m=p.messages[p.messages.length-1],w=e.trim(),A=w!==""&&m?.role==="user"&&typeof m.content=="string"&&(m.content===w||m.content.endsWith(`: ${w}`))?p.messages.slice(0,-1):p.messages;u.push(...A)}catch{}e.trim()&&u.push({role:"user",content:e});let c=[...a];if(r){let p=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async m=>{let w=await p.search(r,String(m.query??""),{limit:typeof m.limit=="number"?m.limit:5});return{results:w.map(v=>({role:v.participant.kind==="agent"?"assistant":"user",content:v.content,timestamp:v.timestamp})),count:w.length}}})}if(this.delegation?.enabled&&this._registry){let p=this.delegation.allowedAgents,m=this._registry.getAllAgents().filter(w=>w.name!==this.name&&(p===void 0||p.includes(w.name)));if(m.length>0){let w=m.map(A=>A.name),v=m.map(A=>`- ${A.name}: ${A.description}`).join(`
3
3
  `);this.delegation.mode==="forget"?c.push({name:"delegate_and_forget",displayName:"Delegate and Forget",description:`Hand off the current task to a peer agent. The agent will handle its own delivery (e.g. posting to Slack or GitHub) \u2014 you do not need to relay its response. Call this ONCE, then output an empty string.
4
4
 
5
5
  Available agents:
6
- ${v}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:w,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 A=>{let k=String(A.agent),E=String(A.message??"");return this._registry.invoke(k,{message:E,conversationId:r,context:{delegatedBy:this.name}}).catch(G=>{console.error(`[${this.name}] delegate_and_forget to ${k} failed:`,G)}),{status:"delegated",agent:k}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
6
+ ${v}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:w,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 A=>{let k=String(A.agent),T=String(A.message??"");return this._registry.invoke(k,{message:T,conversationId:r,context:{delegatedBy:this.name}}).catch(G=>{console.error(`[${this.name}] delegate_and_forget to ${k} failed:`,G)}),{status:"delegated",agent:k}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
7
7
 
8
8
  Available agents:
9
- ${v}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:w,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 A=>{let k=String(A.agent),E=String(A.message??"");return this._registry.invoke(k,{message:E,conversationId:r,context:{delegatedBy:this.name}})}})}}let l=await this.toolpack.generate({messages:u,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds},this.provider),g={output:l.content||"",steps:this.extractSteps(l),metadata:l.usage?{usage:l.usage}:void 0};return await this.onComplete(g),s&&await s(!1),this.emit("agent:complete",g),g}catch(u){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(u),this.emit("agent:error",u),u}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new I("Agent not registered - cannot use ask()");if(!this._conversationId)throw new I("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new I("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new I("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let n=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:n.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new I("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){return n?.simpleValidation?n.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
9
+ ${v}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:w,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 A=>{let k=String(A.agent),T=String(A.message??"");return this._registry.invoke(k,{message:T,conversationId:r,context:{delegatedBy:this.name}})}})}}let l=await this.toolpack.generate({messages:u,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode},this.provider),g={output:l.content||"",steps:this.extractSteps(l),metadata:l.usage?{usage:l.usage}:void 0};return await this.onComplete(g),s&&await s(!1),this.emit("agent:complete",g),g}catch(u){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(u),this.emit("agent:error",u),u}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new I("Agent not registered - cannot use ask()");if(!this._conversationId)throw new I("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new I("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new I("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let n=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:n.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new I("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){return n?.simpleValidation?n.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
10
10
 
11
11
  Question: "${e}"
12
12
  Answer: "${t}"
13
13
 
14
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,r){return await this.evaluateAnswer(e.question,t,{simpleValidation:i=>i.trim().length>3})?(await this.resolvePendingAsk(e.id,t),n(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),r?r():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new I("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._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[B]===!0)?this.interceptors:[L({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);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let r=z(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await q(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}};d();import{randomUUID as Vt}from"crypto";d();import{randomUUID as at}from"crypto";var O=class{constructor(e){this.registry=e}registry;async invoke(e,t){let n=this.registry.getAgent(e);if(!n)throw new I(`Agent "${e}" not found in registry. Available agents: ${this.registry.getAllAgents().map(u=>u.name).join(", ")}`);let r=n.conversationHistory,s=t.conversationId,i=t.context?.delegatedBy;if(r&&s&&i){let u={id:t.context?.messageId??at(),conversationId:s,participant:{kind:"agent",id:i,displayName:i},content:t.message??"",timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(u)}catch{}}let a=await n.invokeAgent(t);if(r&&s){let u={id:at(),conversationId:s,participant:{kind:"agent",id:e,displayName:e},content:a.output,timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(u)}catch{}}return a}};var Ie=class{agentList;instances=new Map;channels=new Map;_transport;pendingAsks=new Map;constructor(e,t){this.agentList=e,this._transport=t?.transport||new O(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()}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:Vt(),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(u){console.error(`[AgentRegistry] Failed to auto-send next ask: ${u instanceof Error?u.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`)}};d();import{AGENT_MODE as Yt}from"toolpack-sdk";var Xt={...Yt,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(" ")},be=class extends C{name="research-agent";description="Web research agent for summarization, fact-finding, competitive analysis, and trend monitoring";mode=Xt;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}};d();import{CODING_MODE as Qt}from"toolpack-sdk";var Zt={...Qt,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(" ")},Ce=class extends C{name="coding-agent";description="Coding agent for code generation, refactoring, debugging, test writing, and code review";mode=Zt;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}};d();import{AGENT_MODE as en}from"toolpack-sdk";var tn={...en,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(" ")},ke=class extends C{name="data-agent";description="Data agent for database queries, CSV generation, data analysis, reporting, and aggregation";mode=tn;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}};d();import{CHAT_MODE as nn}from"toolpack-sdk";var rn={...nn,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(" ")},Re=class extends C{name="browser-agent";description="Browser agent for web browsing, form interaction, page extraction, and link following";mode=rn;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}};d();var b=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};d();import{createHmac as sn,timingSafeEqual as on}from"crypto";var xe=class extends b{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;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,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}`,c=`v0=${sn("sha256",this.config.signingSecret).update(a).digest("hex")}`;if(c.length!==r.length)return!1;try{return on(Buffer.from(c),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,u=t.user,c=u?{kind:"user",id:u}:void 0,l=/<@([A-Z0-9]+)>/g,g=[],p;for(;(p=l.exec(r))!==null;)g.push(p[1]);let m=t.channel;return{message:r,conversationId:a?i:m||s||"",data:t,participant:c,context:{user:u,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 u={kind:"user",id:t};return this.participantCache.set(t,u),u}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 u=e.channel;if(!u||!this.allowedChannels.includes(u))return!1}}let n=e.user;if(this.botUserId&&n===this.botUserId)return!1;let r=e.bot_id;if(!r)return!0;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)})}};d();var Se=class extends b{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((u,c)=>{this.pendingResponses.set(i,{resolve:u,reject:c}),setTimeout(()=>{this.pendingResponses.has(i)&&(this.pendingResponses.delete(i),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:i,context:{...s.context,sessionId:i}}),a.then(u=>{t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(u))}).catch(u=>{t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:u.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)})}};d();import{CronExpressionParser as ct}from"cron-parser";var Ee=class extends b{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{ct.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 ct.parse(e,{currentDate:new Date}).next().toDate()}};d();var Te=class extends b{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=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"})});if(!n.ok)throw new Error(`Failed to send Telegram message: ${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.message||t.edited_message||{},r=n.text||"",s=n.chat||{},i=n.from||{},a=i.id!=null?String(i.id):void 0,u=i.first_name||i.username||a,c=a?{kind:"user",id:a,displayName:u??a}:void 0,l=n.entities??[],g=[];for(let w of l)if(w.type==="text_mention"&&w.user){let v=w.user;v.id!=null&&g.push(String(v.id))}let p=s.type,m=s.id!=null?String(s.id):"";return{message:r,conversationId:m,data:t,participant:c,context:{chatId:s.id,userId:i.id,username:i.username,firstName:i.first_name,lastName:i.last_name,messageId:n.message_id,channelType:p,channelId:m,channelName:s.title,mentions:g.length>0?g:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,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)}}};d();var an=new Set([1,3]),dt=/<@!?(\d+)>/g,cn="https://discord.com/api/v10",_e=class extends b{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&&an.has(s),a=t.author?.id,u=t.author?.globalName??t.author?.username,c=[];if(t.content){dt.lastIndex=0;let l;for(;(l=dt.exec(t.content))!==null;)c.push(l[1])}return{message:t.content,conversationId:r,data:t,participant:a?{kind:"user",id:a,displayName:u??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:c.length>0?c:void 0,isMentioned:this.botUserId?c.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(`${cn}/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)}};d();var Me=class extends b{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(`
14
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,r){return await this.evaluateAnswer(e.question,t,{simpleValidation:i=>i.trim().length>3})?(await this.resolvePendingAsk(e.id,t),n(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),r?r():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new I("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._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[B]===!0)?this.interceptors:[L({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);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let r=z(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await q(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}};d();import{randomUUID as Vt}from"crypto";d();import{randomUUID as at}from"crypto";var O=class{constructor(e){this.registry=e}registry;async invoke(e,t){let n=this.registry.getAgent(e);if(!n)throw new I(`Agent "${e}" not found in registry. Available agents: ${this.registry.getAllAgents().map(u=>u.name).join(", ")}`);let r=n.conversationHistory,s=t.conversationId,i=t.context?.delegatedBy;if(r&&s&&i){let u={id:t.context?.messageId??at(),conversationId:s,participant:{kind:"agent",id:i,displayName:i},content:t.message??"",timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(u)}catch{}}let a=await n.invokeAgent(t);if(r&&s){let u={id:at(),conversationId:s,participant:{kind:"agent",id:e,displayName:e},content:a.output,timestamp:new Date().toISOString(),scope:"channel",metadata:{}};try{await r.append(u)}catch{}}return a}};var Ie=class{agentList;instances=new Map;channels=new Map;_transport;pendingAsks=new Map;constructor(e,t){this.agentList=e,this._transport=t?.transport||new O(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()}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:Vt(),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(u){console.error(`[AgentRegistry] Failed to auto-send next ask: ${u instanceof Error?u.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`)}};d();import{AGENT_MODE as Yt}from"toolpack-sdk";var Xt={...Yt,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(" ")},be=class extends C{name="research-agent";description="Web research agent for summarization, fact-finding, competitive analysis, and trend monitoring";mode=Xt;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}};d();import{CODING_MODE as Qt}from"toolpack-sdk";var Zt={...Qt,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(" ")},Ce=class extends C{name="coding-agent";description="Coding agent for code generation, refactoring, debugging, test writing, and code review";mode=Zt;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}};d();import{AGENT_MODE as en}from"toolpack-sdk";var tn={...en,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(" ")},ke=class extends C{name="data-agent";description="Data agent for database queries, CSV generation, data analysis, reporting, and aggregation";mode=tn;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}};d();import{CHAT_MODE as nn}from"toolpack-sdk";var rn={...nn,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(" ")},Re=class extends C{name="browser-agent";description="Browser agent for web browsing, form interaction, page extraction, and link following";mode=rn;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}};d();var b=class{name;_handler;onMessage(e){this._handler=e}async handleMessage(e){this._handler&&await this._handler(e)}};d();import{createHmac as sn,timingSafeEqual as on}from"crypto";var xe=class extends b{isTriggerChannel=!1;config;server;participantCache=new Map;botUserId;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,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}`,c=`v0=${sn("sha256",this.config.signingSecret).update(a).digest("hex")}`;if(c.length!==r.length)return!1;try{return on(Buffer.from(c),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,u=t.user,c=u?{kind:"user",id:u}:void 0,l=/<@([A-Z0-9]+)>/g,g=[],p;for(;(p=l.exec(r))!==null;)g.push(p[1]);let m=t.channel;return{message:r,conversationId:a?i:m||s||"",data:t,participant:c,context:{user:u,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 u={kind:"user",id:t};return this.participantCache.set(t,u),u}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 u=e.channel;if(!u||!this.allowedChannels.includes(u))return!1}}let n=e.user;if(this.botUserId&&n===this.botUserId)return!1;let r=e.bot_id;if(!r)return!0;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)})}};d();var Se=class extends b{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((u,c)=>{this.pendingResponses.set(i,{resolve:u,reject:c}),setTimeout(()=>{this.pendingResponses.has(i)&&(this.pendingResponses.delete(i),c(new Error("Agent response timeout")))},3e4)});this.handleMessage({...s,conversationId:i,context:{...s.context,sessionId:i}}),a.then(u=>{t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(u))}).catch(u=>{t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:u.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)})}};d();import{CronExpressionParser as ct}from"cron-parser";var Te=class extends b{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{ct.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 ct.parse(e,{currentDate:new Date}).next().toDate()}};d();var Ee=class extends b{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=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"})});if(!n.ok)throw new Error(`Failed to send Telegram message: ${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.message||t.edited_message||{},r=n.text||"",s=n.chat||{},i=n.from||{},a=i.id!=null?String(i.id):void 0,u=i.first_name||i.username||a,c=a?{kind:"user",id:a,displayName:u??a}:void 0,l=n.entities??[],g=[];for(let w of l)if(w.type==="text_mention"&&w.user){let v=w.user;v.id!=null&&g.push(String(v.id))}let p=s.type,m=s.id!=null?String(s.id):"";return{message:r,conversationId:m,data:t,participant:c,context:{chatId:s.id,userId:i.id,username:i.username,firstName:i.first_name,lastName:i.last_name,messageId:n.message_id,channelType:p,channelId:m,channelName:s.title,mentions:g.length>0?g:void 0}}}startPolling(){console.log("[TelegramChannel] Starting polling mode"),this.pollingInterval=setInterval(async()=>{try{await this.pollUpdates()}catch(e){console.error("[TelegramChannel] Polling error:",e)}},5e3)}async pollUpdates(){let e=`https://api.telegram.org/bot${this.config.token}/getUpdates?offset=${this.offset}&limit=100`,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)}}};d();var an=new Set([1,3]),dt=/<@!?(\d+)>/g,cn="https://discord.com/api/v10",_e=class extends b{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&&an.has(s),a=t.author?.id,u=t.author?.globalName??t.author?.username,c=[];if(t.content){dt.lastIndex=0;let l;for(;(l=dt.exec(t.content))!==null;)c.push(l[1])}return{message:t.content,conversationId:r,data:t,participant:a?{kind:"user",id:a,displayName:u??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:c.length>0?c:void 0,isMentioned:this.botUserId?c.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(`${cn}/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)}};d();var Me=class extends b{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(`
15
15
 
16
16
  `).map(t=>`<p>${t.replace(/\n/g,"<br>")}</p>`).join("")}async stop(){this.transporter&&(this.transporter.close(),this.transporter=void 0)}};d();var Pe=class extends b{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,u)=>{s[u]=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)})}};d();var De=class extends b{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)}}};d();d();var Y=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 I(`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 I(`HTTP ${s.status}: ${s.statusText}`);let i=await s.json();if(i.error)throw new I(`JSON-RPC error (${i.error.code}): ${i.error.message}`+(i.error.data?` - ${JSON.stringify(i.error.data)}`:""));if(!i.result)throw new I("No result in JSON-RPC response");return i.result}catch(s){throw s instanceof I?s:new I(`Failed to invoke agent "${e}" at ${n}: ${s instanceof Error?s.message:String(s)}`)}}};d();import dn from"http";var X=class{agents=new Map;server;port;constructor(e){this.port=e.port}registerAgent(e,t){this.agents.set(e,t)}listen(){this.server=dn.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}}}};d();d();import{CHAT_MODE as ln}from"toolpack-sdk";var un={...ln,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(`
17
17
  `)},Q=class extends C{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=un;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(`
@@ -130,4 +130,4 @@ Actual answer:
130
130
  Is the actual answer correct or equivalent to the expected answer?
131
131
  Respond with ONLY "pass" or "fail" on the first line, then optionally a one-sentence explanation.`,ie=class{judgeAgent;promptTemplate;constructor(e,t={}){this.judgeAgent=e,this.promptTemplate=t.promptTemplate??wn}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(S(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(`
132
132
  `),a=i[0].toLowerCase().startsWith("pass")?"pass":"fail",u=i.slice(1).join(" ").trim()||void 0;t.push(S(n,a,u))}catch(s){t.push(S(n,"fail",`Judge threw: ${s instanceof Error?s.message:String(s)}`))}}return ce(e,t)}},ae=class{fn;constructor(e){this.fn=e}async score(e){let t=[];for(let n of e.results){if(n.error){t.push(S(n,"fail",`Agent threw: ${n.error}`));continue}try{let{verdict:r,explanation:s}=await this.fn(n);t.push(S(n,r,s))}catch(r){t.push(S(n,"fail",`Scorer threw: ${r instanceof Error?r.message:String(r)}`))}}return ce(e,t)}};d();function gt(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=[],u=new Set([...t.keys(),...n.keys()]);for(let l of u){let g=t.get(l),p=n.get(l);!g||!p||(g.verdict==="pass"&&p.verdict==="fail"?r.push({caseId:l,baselineOutput:g.caseResult.actualOutput,candidateOutput:p.caseResult.actualOutput}):g.verdict==="fail"&&p.verdict==="pass"?s.push({caseId:l,baselineOutput:g.caseResult.actualOutput,candidateOutput:p.caseResult.actualOutput}):g.verdict==="pass"&&p.verdict==="pass"?i.push(l):a.push(l))}let c=e.passRate-o.passRate;return{baselineRunId:o.run.runId,candidateRunId:e.run.runId,baselinePassRate:o.passRate,candidatePassRate:e.passRate,delta:c,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: ${de(r.baselineOutput)}`),e.push(` candidate: ${de(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: ${de(r.baselineOutput)}`),e.push(` candidate: ${de(r.candidateOutput)}`);e.push("")}return e.push(`Stable passes: ${o.stablePasses.length} | Stable fails: ${o.stableFails.length}`),e.join(`
133
- `)}function de(o,e=80){let t=o.replace(/\n/g," ");return t.length>e?`${t.slice(0,e)}\u2026`:t}d();export{I as AgentError,X as AgentJsonRpcServer,V as AgentMind,Ie as AgentRegistry,C as BaseAgent,b as BaseChannel,Re as BrowserAgent,Ce as CodingAgent,oe as ContainsScorer,ae as CustomScorer,ke as DataAgent,N as DepthExceededError,_e as DiscordChannel,Me as EmailChannel,ne as EvalDataset,re as EvalRunner,se as ExactMatchScorer,lt as InMemoryConversationStore,Q as IntentClassifierAgent,j as InvocationDepthExceededError,Y as JsonRpcTransport,ie as LLMJudgeScorer,O as LocalTransport,De as McpChannel,ee as OTelSpanStatusCode,be as ResearchAgent,D as SKIP_SENTINEL,Pe as SMSChannel,Ee as ScheduledChannel,te as SchedulerStore,xe as SlackChannel,Z as SummarizerAgent,Te as TelegramChannel,Se as WebhookChannel,H as assemblePrompt,gt as compareEvalRuns,z as composeChain,Ge as createAddressCheckInterceptor,L as createCaptureInterceptor,ut as createConversationSearchTool,ze as createDepthGuardInterceptor,Ne as createEventDedupInterceptor,Je as createIntentClassifierInterceptor,$e as createNoiseFilterInterceptor,He as createOTelTracerInterceptor,Fe as createParticipantResolverInterceptor,Ue as createRateLimitInterceptor,pt as createSchedulerTools,je as createSelfFilterInterceptor,qe as createTracerInterceptor,q as executeChain,mt as formatEvalReport,_ as isSkipSentinel,J as skip};
133
+ `)}function de(o,e=80){let t=o.replace(/\n/g," ");return t.length>e?`${t.slice(0,e)}\u2026`:t}d();export{I as AgentError,X as AgentJsonRpcServer,V as AgentMind,Ie as AgentRegistry,C as BaseAgent,b as BaseChannel,Re as BrowserAgent,Ce as CodingAgent,oe as ContainsScorer,ae as CustomScorer,ke as DataAgent,N as DepthExceededError,_e as DiscordChannel,Me as EmailChannel,ne as EvalDataset,re as EvalRunner,se as ExactMatchScorer,lt as InMemoryConversationStore,Q as IntentClassifierAgent,j as InvocationDepthExceededError,Y as JsonRpcTransport,ie as LLMJudgeScorer,O as LocalTransport,De as McpChannel,ee as OTelSpanStatusCode,be as ResearchAgent,D as SKIP_SENTINEL,Pe as SMSChannel,Te as ScheduledChannel,te as SchedulerStore,xe as SlackChannel,Z as SummarizerAgent,Ee as TelegramChannel,Se as WebhookChannel,H as assemblePrompt,gt as compareEvalRuns,z as composeChain,Ge as createAddressCheckInterceptor,L as createCaptureInterceptor,ut as createConversationSearchTool,ze as createDepthGuardInterceptor,Ne as createEventDedupInterceptor,Je as createIntentClassifierInterceptor,$e as createNoiseFilterInterceptor,He as createOTelTracerInterceptor,Fe as createParticipantResolverInterceptor,Ue as createRateLimitInterceptor,pt as createSchedulerTools,je as createSelfFilterInterceptor,qe as createTracerInterceptor,q as executeChain,mt as formatEvalReport,_ as isSkipSentinel,J as skip};
@@ -1,5 +1,5 @@
1
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from './types-TB6yypig.cjs';
2
- import { B as BaseAgent } from './base-agent-DPdK4Pnl.cjs';
1
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from './types-C3eW-auY.cjs';
2
+ import { B as BaseAgent } from './base-agent-65162dq7.cjs';
3
3
  import { ModeConfig } from 'toolpack-sdk';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from './types-TB6yypig.js';
2
- import { B as BaseAgent } from './base-agent-nU8pr4nu.js';
1
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from './types-C3eW-auY.js';
2
+ import { B as BaseAgent } from './base-agent-DzspMyaG.js';
3
3
  import { ModeConfig } from 'toolpack-sdk';
4
4
 
5
5
  /**
@@ -1,9 +1,9 @@
1
- import { A as AgentInput, i as InterceptorResult, I as Interceptor, f as AgentInstance, C as ChannelInterface, c as IAgentRegistry, g as InterceptorChainConfig, a as AgentResult } from '../types-TB6yypig.cjs';
2
- export { h as InterceptorContext, N as NextFunction, S as SKIP_SENTINEL, j as isSkipSentinel, s as skip } from '../types-TB6yypig.cjs';
1
+ import { A as AgentInput, i as InterceptorResult, I as Interceptor, f as AgentInstance, C as ChannelInterface, c as IAgentRegistry, g as InterceptorChainConfig, a as AgentResult } from '../types-C3eW-auY.cjs';
2
+ export { h as InterceptorContext, N as NextFunction, S as SKIP_SENTINEL, j as isSkipSentinel, s as skip } from '../types-C3eW-auY.cjs';
3
3
  import { Participant, ConversationStore, ConversationScope, StoredMessage } from 'toolpack-sdk';
4
- import { I as IntentClassification } from '../intent-classifier-agent-DxyfJWcm.cjs';
4
+ import { I as IntentClassification } from '../intent-classifier-agent-D0rWtviD.cjs';
5
5
  import 'events';
6
- import '../base-agent-DPdK4Pnl.cjs';
6
+ import '../base-agent-65162dq7.cjs';
7
7
  import '@toolpack-sdk/knowledge';
8
8
 
9
9
  /**
@@ -1,9 +1,9 @@
1
- import { A as AgentInput, i as InterceptorResult, I as Interceptor, f as AgentInstance, C as ChannelInterface, c as IAgentRegistry, g as InterceptorChainConfig, a as AgentResult } from '../types-TB6yypig.js';
2
- export { h as InterceptorContext, N as NextFunction, S as SKIP_SENTINEL, j as isSkipSentinel, s as skip } from '../types-TB6yypig.js';
1
+ import { A as AgentInput, i as InterceptorResult, I as Interceptor, f as AgentInstance, C as ChannelInterface, c as IAgentRegistry, g as InterceptorChainConfig, a as AgentResult } from '../types-C3eW-auY.js';
2
+ export { h as InterceptorContext, N as NextFunction, S as SKIP_SENTINEL, j as isSkipSentinel, s as skip } from '../types-C3eW-auY.js';
3
3
  import { Participant, ConversationStore, ConversationScope, StoredMessage } from 'toolpack-sdk';
4
- import { I as IntentClassification } from '../intent-classifier-agent-0JZDlhpk.js';
4
+ import { I as IntentClassification } from '../intent-classifier-agent-mmNoAozf.js';
5
5
  import 'events';
6
- import '../base-agent-nU8pr4nu.js';
6
+ import '../base-agent-DzspMyaG.js';
7
7
  import '@toolpack-sdk/knowledge';
8
8
 
9
9
  /**
@@ -1,8 +1,8 @@
1
- import { C as ChannelInterface, e as AgentOutput, A as AgentInput, B as BaseAgentOptions } from '../types-TB6yypig.cjs';
1
+ import { C as ChannelInterface, e as AgentOutput, A as AgentInput, B as BaseAgentOptions } from '../types-C3eW-auY.cjs';
2
2
  import { Chunk, QueryOptions, QueryResult, Knowledge } from '@toolpack-sdk/knowledge';
3
3
  import { Toolpack } from 'toolpack-sdk';
4
- import { B as BaseAgent } from '../base-agent-DPdK4Pnl.cjs';
5
- export { C as ContainsScorer, a as CustomScorer, E as EvalCase, b as EvalCaseResult, c as EvalDataset, d as EvalImprovement, e as EvalRegression, f as EvalReport, g as EvalRun, h as EvalRunner, i as EvalRunnerOptions, j as EvalScoredResult, k as EvalScoredRun, l as EvalScorer, m as EvalVerdict, n as ExactMatchScorer, L as LLMJudgeScorer, o as LLMJudgeScorerOptions, p as compareEvalRuns, q as formatEvalReport } from '../eval-report-BCGixIYd.cjs';
4
+ import { B as BaseAgent } from '../base-agent-65162dq7.cjs';
5
+ export { C as ContainsScorer, a as CustomScorer, E as EvalCase, b as EvalCaseResult, c as EvalDataset, d as EvalImprovement, e as EvalRegression, f as EvalReport, g as EvalRun, h as EvalRunner, i as EvalRunnerOptions, j as EvalScoredResult, k as EvalScoredRun, l as EvalScorer, m as EvalVerdict, n as ExactMatchScorer, L as LLMJudgeScorer, o as LLMJudgeScorerOptions, p as compareEvalRuns, q as formatEvalReport } from '../eval-report-BUD6NRiP.cjs';
6
6
  import 'events';
7
7
 
8
8
  /**
@@ -1,8 +1,8 @@
1
- import { C as ChannelInterface, e as AgentOutput, A as AgentInput, B as BaseAgentOptions } from '../types-TB6yypig.js';
1
+ import { C as ChannelInterface, e as AgentOutput, A as AgentInput, B as BaseAgentOptions } from '../types-C3eW-auY.js';
2
2
  import { Chunk, QueryOptions, QueryResult, Knowledge } from '@toolpack-sdk/knowledge';
3
3
  import { Toolpack } from 'toolpack-sdk';
4
- import { B as BaseAgent } from '../base-agent-nU8pr4nu.js';
5
- export { C as ContainsScorer, a as CustomScorer, E as EvalCase, b as EvalCaseResult, c as EvalDataset, d as EvalImprovement, e as EvalRegression, f as EvalReport, g as EvalRun, h as EvalRunner, i as EvalRunnerOptions, j as EvalScoredResult, k as EvalScoredRun, l as EvalScorer, m as EvalVerdict, n as ExactMatchScorer, L as LLMJudgeScorer, o as LLMJudgeScorerOptions, p as compareEvalRuns, q as formatEvalReport } from '../eval-report-CpdAMa2b.js';
4
+ import { B as BaseAgent } from '../base-agent-DzspMyaG.js';
5
+ export { C as ContainsScorer, a as CustomScorer, E as EvalCase, b as EvalCaseResult, c as EvalDataset, d as EvalImprovement, e as EvalRegression, f as EvalReport, g as EvalRun, h as EvalRunner, i as EvalRunnerOptions, j as EvalScoredResult, k as EvalScoredRun, l as EvalScorer, m as EvalVerdict, n as ExactMatchScorer, L as LLMJudgeScorer, o as LLMJudgeScorerOptions, p as compareEvalRuns, q as formatEvalReport } from '../eval-report-C6dSvR3Y.js';
6
6
  import 'events';
7
7
 
8
8
  /**
@@ -1,4 +1,4 @@
1
- import { Participant, ModeConfig, Toolpack } from 'toolpack-sdk';
1
+ import { Participant, ModeConfig, ToolpackInitConfig, Toolpack } from 'toolpack-sdk';
2
2
  import { EventEmitter } from 'events';
3
3
 
4
4
  /**
@@ -110,16 +110,14 @@ interface InterceptorChainConfig {
110
110
  /**
111
111
  * Options for constructing a BaseAgent.
112
112
  *
113
- * - `{ apiKey, provider?, model? }` — agent creates and owns its own Toolpack instance.
113
+ * - `ToolpackInitConfig` — agent creates and owns its own Toolpack instance using
114
+ * the supplied config. Accepts everything `Toolpack.init()` accepts: `apiKey`,
115
+ * `provider`, `model`, `customTools`, `tools`, `knowledge`, `customModes`, etc.
114
116
  * The instance is initialised lazily in `start()`.
115
117
  * - `{ toolpack }` — agent uses a shared Toolpack instance (e.g. passed from AgentRegistry
116
- * for multi-agent setups where API client and config are shared).
118
+ * for multi-agent setups where the API client and config are shared).
117
119
  */
118
- type BaseAgentOptions = {
119
- apiKey: string;
120
- provider?: string;
121
- model?: string;
122
- } | {
120
+ type BaseAgentOptions = ToolpackInitConfig | {
123
121
  toolpack: Toolpack;
124
122
  };
125
123
  /**
@@ -1,4 +1,4 @@
1
- import { Participant, ModeConfig, Toolpack } from 'toolpack-sdk';
1
+ import { Participant, ModeConfig, ToolpackInitConfig, Toolpack } from 'toolpack-sdk';
2
2
  import { EventEmitter } from 'events';
3
3
 
4
4
  /**
@@ -110,16 +110,14 @@ interface InterceptorChainConfig {
110
110
  /**
111
111
  * Options for constructing a BaseAgent.
112
112
  *
113
- * - `{ apiKey, provider?, model? }` — agent creates and owns its own Toolpack instance.
113
+ * - `ToolpackInitConfig` — agent creates and owns its own Toolpack instance using
114
+ * the supplied config. Accepts everything `Toolpack.init()` accepts: `apiKey`,
115
+ * `provider`, `model`, `customTools`, `tools`, `knowledge`, `customModes`, etc.
114
116
  * The instance is initialised lazily in `start()`.
115
117
  * - `{ toolpack }` — agent uses a shared Toolpack instance (e.g. passed from AgentRegistry
116
- * for multi-agent setups where API client and config are shared).
118
+ * for multi-agent setups where the API client and config are shared).
117
119
  */
118
- type BaseAgentOptions = {
119
- apiKey: string;
120
- provider?: string;
121
- model?: string;
122
- } | {
120
+ type BaseAgentOptions = ToolpackInitConfig | {
123
121
  toolpack: Toolpack;
124
122
  };
125
123
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toolpack-sdk/agents",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "Production AI agents for Toolpack SDK — 8 channel integrations (Slack, Discord, Telegram, SMS, Email, Webhook, Scheduled, MCP), AgentMind persistent cognitive layer (goals, beliefs, reflections), interceptors, evals, and multi-agent coordination",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -89,11 +89,11 @@
89
89
  },
90
90
  "peerDependencies": {
91
91
  "@opentelemetry/api": "^1.x",
92
- "@toolpack-sdk/knowledge": "^2.2.0",
92
+ "@toolpack-sdk/knowledge": "^2.3.0",
93
93
  "better-sqlite3": "^12.6.2",
94
94
  "discord.js": "^14.x",
95
95
  "nodemailer": "^6.x",
96
- "toolpack-sdk": "^2.2.0",
96
+ "toolpack-sdk": "^2.3.0",
97
97
  "twilio": "^5.x"
98
98
  },
99
99
  "peerDependenciesMeta": {