@toolpack-sdk/agents 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,40 @@
1
- var we=Object.defineProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var ve=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})};import it from"path";import{fileURLToPath as ot}from"url";var y=_(()=>{"use strict"});import{randomUUID as $}from"crypto";var L,U,q,j,z,a,B,ae=_(()=>{"use strict";y();L=.6,U=.2,q=.2,j={low:.3,medium:.6,high:1},z=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},B=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},o=n[t.priority]-n[i.priority];return o!==0?o:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let o=this.chunkToBelief(n),s=(t-o.createdAt)/864e5,p=Math.exp(-s/z)*U+j.high*q+L;return{...o,score:p}}).sort((n,o)=>o.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(o=>o[a.type]==="reflection"&&!o[a.pinned]&&!o[a.error]&&o[a.createdAt]>=i)).map(o=>this.chunkToReflection(o)).sort((o,s)=>s.createdAt-o.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:o}=t,s;if(e.trim()&&typeof this.provider.keywordQuery=="function")s=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(p=>this.chunkToGoal(p.chunk));else{let u=n;if(s=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();s=s.filter(d=>d.description.toLowerCase().includes(c))}}return o?.length&&(s=s.filter(u=>o.every(p=>u.tags.includes(p)))),s.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:o,includeExpired:s=!1}=t,u=Date.now(),p=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of p){let l=this.chunkToBelief(d.chunk);if(!s&&l.expiresAt&&l.expiresAt<u||o?.length&&!o.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,g=Math.exp(-m/z),h=l.error?.3:j[l.confidence],f=d.score*L+g*U+h*q;f<n||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:o,pinned:s}=t,u=Date.now(),p={[a.type]:"reflection"};s===!0&&(p[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:p}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(s===!1&&m.pinned||o?.length&&!o.every(w=>m.tags.includes(w)))continue;let g=(u-m.createdAt)/864e5,h=Math.exp(-g/z),f=l.score*L+h*U+j.medium*q;f<n||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let o of n){let s=this.chunkToBelief(o.chunk);if(!(s.expiresAt&&s.expiresAt<i))return{id:o.chunk.id,score:o.score,belief:s}}return null}async addGoal(e){let t=$();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),o={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(o)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=$();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let o=this.chunkToBelief(n),s={...o,content:t.content??o.content,confidence:t.confidence??o.confidence,tags:t.tags??o.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:o.expiresAt,error:t.error??o.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(s,u)])}async addReflection(e,t){let i=$();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),o={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(o,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function F(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function ce(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=F(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function de(r,e){let t=0,i=0,n=0;for(let s=0;s<r.length;s++)t+=r[s]*e[s],i+=r[s]*r[s],n+=e[s]*e[s];let o=Math.sqrt(i)*Math.sqrt(n);return o===0?0:t/o}function H(r){return Math.ceil(r.length/4)}var W=_(()=>{"use strict";y()});import{randomUUID as Ce}from"crypto";var E,le=_(()=>{"use strict";y();W();E=class{constructor(e,t,i,n,o,s){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=o;this.committedPinnedReflectionCount=s}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,o=e.expiresIn??e.ttlDefault;o&&(n=t+F(o));let s=this._findSimilarInDraft(i);if(s!==null){let c=this.ops[s],d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l];return this.ops[s]={...c,content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${s}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l],h={op:"believe",content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let s=this.totalPinnedReflectionCount;if(s>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);s>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${s+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},o=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:o,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?ce(e.dueBy):void 0,i={op:"set_goal",tempId:Ce(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let o=i;if(o.vector.length===0)continue;if(de(e,o.vector)>=this.deduplicationThreshold)return n}return null}}});function ue(r,e,t){return[xe(r,t),_e(r,e,t),Me(e,t),Se(e),Te(e,t),De(r,e),Pe(r)]}function xe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",o=t.status??"active",s=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,p=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:o,tags:s});for(let f of h)l.push(Be(f))}if(g&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(g,{limit:d,threshold:c,tags:s,includeExpired:p});for(let f of h)l.push(Ee(f))}if(g&&(n==="reflection"||n==="all")){let h=await r.queryReflections(g,{limit:d,threshold:c,tags:s,pinned:u});for(let f of h)l.push(Ne(f))}return l}}}function _e(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Me(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function Se(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function Te(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function De(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function Pe(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Be(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function Ee(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function Ne(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var pe=_(()=>{"use strict";y()});async function me(r,e){let[t,i,n,o]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),s=t.map(l=>Ge(l)),u=i.map(l=>`- ${l.content}`),{beliefLines:p,reflectionLines:c}=Oe(n,o,e.tokenBudget);if(s.length===0&&u.length===0&&p.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return s.length>0&&(d.push("## Goals"),d.push(...s),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),p.length>0&&(d.push("## Beliefs"),d.push(...p),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
- `)}function Ge(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function Oe(r,e,t){let i=t,n=[],o=[];for(let s of r){let u=`- ${s.content} (${s.confidence} confidence)`,p=H(u);if(p>i)break;n.push(u),i-=p}for(let s of e){let p=`- [${new Date(s.createdAt).toISOString().slice(0,10)}] ${s.content}`,c=H(p);if(c>i)break;o.push(p),i-=c}return{beliefLines:n,reflectionLines:o}}var ge=_(()=>{"use strict";y();W()});var fe={};ve(fe,{AgentMind:()=>K});function Ke(r,e){let t=Math.min(e.maxGoals??Ue,He),i=Math.min(e.maxPinnedReflections??qe,We);return{tokenBudget:e.tokenBudget??$e,recencyWindowDays:e.recencyWindowDays??Le,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??je,retrievalThreshold:e.retrievalThreshold??ze,ttlDefaults:{belief:e.ttlDefaults?.belief??Fe,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var $e,Le,Ue,qe,je,ze,Fe,He,We,K,he=_(()=>{"use strict";y();ae();le();pe();ge();$e=300,Le=7,Ue=10,qe=10,je=.85,ze=.35,Fe="30d",He=10,We=10,K=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:s}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new s({namespace:u})}let n=Ke(e,t),o=new B(i,t.embedder);return await o.initialize(),new r(o,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),me(this.store,this.config)]),n=new E(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),o=ue(this.store,n,this.config);return{mindHeader:i,tools:o,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});y();y();y();import{EventEmitter as Ve}from"events";import{Toolpack as Je,InMemoryConversationStore as Ye}from"toolpack-sdk";y();y();var P=Symbol("interceptor-skip-sentinel");function Z(r){return r===P}function ee(){return P}var G=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function te(r,e,t,i,n={}){let o=n.maxInvocationDepth??5;return{async execute(s){let p=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>o)throw new G(g,o);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let h=i.getAgent(l);if(!h)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:ee}))(0),c=async d=>{let l=d??s;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??s,p,m)}return await c()}}}async function ne(r,e){let t=await r.execute(e);return t===P?null:t}y();import{randomUUID as ie}from"crypto";function Ae(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var O=Symbol.for("toolpack:capture-history");function re(r){let e=r.captureAgentReplies??!0,t=r.getScope??Ae,i=r.getMessageId??(s=>s.context?.messageId??s.context?.eventId??ie()),n=r.getMentions??(s=>s.context?.mentions??[]),o=async(s,u,p)=>{let c=s.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await p();let d=s.participant;if(d){let m={id:i(s),conversationId:c,participant:d,content:s.message??"",timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:n(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){u.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await p();if(e&&!Z(l)&&l.output!=null){let m={kind:"agent",id:u.agent.name,displayName:u.agent.name},g={id:ie(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return l};return o[O]=!0,o}y();import{randomUUID as be}from"crypto";function oe(r){return Math.ceil(r.length/4)}function ke(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Ie(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Re(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function se(r,e,t,i,n={},o){let{scope:s,addressedOnlyMode:u=!0,tokenBudget:p=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:s,sinceTimestamp:h,limit:l}),w=f.length;if(u){let b=new Set;for(let k=0;k<f.length;k++){let T=f[k];if(Re(T,t,g)&&b.add(T.id),k<f.length-1){let M=f[k+1];M.participant.kind==="agent"&&M.participant.id===t&&b.add(T.id)}}let C=f[f.length-1];C&&b.add(C.id),f=f.filter(k=>b.has(k.id))}let I=!1;if(f.length>c&&o){let b=Math.floor(f.length/2),C=f.slice(0,b),k=f.slice(b),T=C.filter(M=>!M.metadata?.isSummary);try{let M=await o.invokeAgent({message:"summarize",data:{turns:T.map(ke),agentName:i,agentId:t,maxTokens:Math.floor(p*.25),extractDecisions:!0}}),X=JSON.parse(M.output),Q={id:`summary-${be()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${X.turnsSummarized} earlier turns]: ${X.summary}`,timestamp:C[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};f=[Q,...k],I=!0;try{await r.append(Q),await r.deleteMessages(e,C.map(ye=>ye.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let R=f.map(b=>Ie(b,t));if(R.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:I};let D=R[R.length-1],Y=[D],N=oe(D.content);for(let b=R.length-2;b>=0;b--){let C=R[b],k=oe(C.content);if(N+k>p)break;Y.unshift(C),N+=k}return{messages:Y,estimatedTokens:N,turnsLoaded:w,hasSummary:I}}y();var x=class extends Error{constructor(e){super(e),this.name="AgentError"}};var S=class extends Ve{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Ye,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Je.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(he(),fe));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await se(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
1
+ var Ge=Object.defineProperty;var S=(r,e)=>()=>(r&&(e=r(r=0)),e);var ge=(r,e)=>{for(var t in e)Ge(r,t,{get:e[t],enumerable:!0})};import kt from"path";import{fileURLToPath as It}from"url";var y=S(()=>{"use strict"});function fe(r){return r===z}function he(){return z}var z,V=S(()=>{"use strict";y();z=Symbol("interceptor-skip-sentinel")});function ye(r,e,t,i,n={}){let s=n.maxInvocationDepth??5;return{async execute(o){let g=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(p,l)=>{let m=d+1;if(m>s)throw new J(m,s);if(!i)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let h=i.getAgent(p);if(!h)throw new Error(`Agent "${p}" not found for delegation`);let f={message:l.message??"",intent:l.intent,data:l.data,context:l.context,conversationId:l.conversationId??o.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:he}))(0),c=async d=>{let p=d??o;return await e.invokeAgent(p)};for(let d=r.length-1;d>=0;d--){let p=r[d],l=c;c=async m=>await p(m??o,g,l)}return await c()}}}async function we(r,e){let t=await r.execute(e);return t===z?null:t}var J,Ae=S(()=>{"use strict";y();V();J=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});import{randomUUID as ve}from"crypto";function Oe(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function ke(r){let e=r.captureAgentReplies??!0,t=r.getScope??Oe,i=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??ve()),n=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,u,g)=>{let c=o.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await g();let d=o.participant;if(d){let l={id:i(o),conversationId:c,participant:d,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:n(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(l),r.onCaptured?.(l),u.logger?.debug("[capture-history] Captured inbound message",{messageId:l.id,participantId:d.id,conversationId:c})}catch(m){u.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let p=await g();if(e&&!fe(p)&&p.output!=null){let l={kind:"agent",id:u.agent.name,displayName:u.agent.name},m={id:ve(),conversationId:c,participant:l,content:p.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return p};return s[Y]=!0,s}var Y,be=S(()=>{"use strict";y();V();Y=Symbol.for("toolpack:capture-history")});import{randomUUID as Le}from"crypto";function Ie(r){return Math.ceil(r.length/4)}function Ue(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function qe(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function je(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function Re(r,e,t,i,n={},s){let{scope:o,addressedOnlyMode:u=!0,tokenBudget:g=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:p=100,agentAliases:l}=n,m=new Set([t,...l??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:h,limit:p}),w=f.length;if(u){let A=new Set;for(let b=0;b<f.length;b++){let _=f[b];if(je(_,t,m)&&A.add(_.id),b<f.length-1){let R=f[b+1];R.participant.kind==="agent"&&R.participant.id===t&&A.add(_.id)}}let I=f[f.length-1];I&&A.add(I.id),f=f.filter(b=>A.has(b.id))}let M=!1;if(f.length>c&&s){let A=Math.floor(f.length/2),I=f.slice(0,A),b=f.slice(A),_=I.filter(R=>!R.metadata?.isSummary);try{let R=await s.invokeAgent({message:"summarize",data:{turns:_.map(Ue),agentName:i,agentId:t,maxTokens:Math.floor(g*.25),extractDecisions:!0}}),D=JSON.parse(R.output),v={id:`summary-${Le()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${D.turnsSummarized} earlier turns]: ${D.summary}`,timestamp:I[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[v,...b],M=!0;try{await r.append(v),await r.deleteMessages(e,I.map($=>$.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let T=f.map(A=>qe(A,t));if(T.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:M};let N=T[T.length-1],j=[N],k=Ie(N.content);for(let A=T.length-2;A>=0;A--){let I=T[A],b=Ie(I.content);if(k+b>g)break;j.unshift(I),k+=b}return{messages:j,estimatedTokens:k,turnsLoaded:w,hasSummary:M}}var xe=S(()=>{"use strict";y()});var B,Ce=S(()=>{"use strict";y();B=class extends Error{constructor(e){super(e),this.name="AgentError"}}});import{randomUUID as X}from"crypto";var Q,Z,ee,te,ne,a,F,_e=S(()=>{"use strict";y();Q=.6,Z=.2,ee=.2,te={low:.3,medium:.6,high:1},ne=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},F=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},s=n[t.priority]-n[i.priority];return s!==0?s:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let s=this.chunkToBelief(n),o=(t-s.createdAt)/864e5,g=Math.exp(-o/ne)*Z+te.high*ee+Q;return{...s,score:g}}).sort((n,s)=>s.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=i)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(g=>this.chunkToGoal(g.chunk));else{let u=n;if(o=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();o=o.filter(d=>d.description.toLowerCase().includes(c))}}return s?.length&&(o=o.filter(u=>s.every(g=>u.tags.includes(g)))),o.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:s,includeExpired:o=!1}=t,u=Date.now(),g=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of g){let p=this.chunkToBelief(d.chunk);if(!o&&p.expiresAt&&p.expiresAt<u||s?.length&&!s.every(w=>p.tags.includes(w)))continue;let l=(u-p.createdAt)/864e5,m=Math.exp(-l/ne),h=p.error?.3:te[p.confidence],f=d.score*Q+m*Z+h*ee;f<n||c.push({...p,score:f})}return c.sort((d,p)=>p.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:s,pinned:o}=t,u=Date.now(),g={[a.type]:"reflection"};o===!0&&(g[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:g}),d=[];for(let p of c){let l=this.chunkToReflection(p.chunk);if(o===!1&&l.pinned||s?.length&&!s.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,h=Math.exp(-m/ne),f=p.score*Q+h*Z+te.medium*ee;f<n||d.push({...l,score:f})}return d.sort((p,l)=>l.score-p.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of n){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<i))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=X();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),s={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=X();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(n),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,u)])}async addReflection(e,t){let i=X();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),s={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function ie(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function Se(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=ie(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Me(r,e){let t=0,i=0,n=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],i+=r[o]*r[o],n+=e[o]*e[o];let s=Math.sqrt(i)*Math.sqrt(n);return s===0?0:t/s}function re(r){return Math.ceil(r.length/4)}var se=S(()=>{"use strict";y()});import{randomUUID as ze}from"crypto";var H,Te=S(()=>{"use strict";y();se();H=class{constructor(e,t,i,n,s,o){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=s;this.committedPinnedReflectionCount=o}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,s=e.expiresIn??e.ttlDefault;s&&(n=t+ie(s));let o=this._findSimilarInDraft(i);if(o!==null){let c=this.ops[o],d=e.confidence,p=c.confidence,l={low:0,medium:1,high:2},m=l[d]>l[p]||e.allowDowngrade&&l[d]<l[p];return this.ops[o]={...c,content:e.content,confidence:m?d:p,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${o}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,p=c.confidence,l={low:0,medium:1,high:2},m=l[d]>l[p]||e.allowDowngrade&&l[d]<l[p],h={op:"believe",content:e.content,confidence:m?d:p,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let g={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(g),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},s=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{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?Se(e.dueBy):void 0,i={op:"set_goal",tempId:ze(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let s=i;if(s.vector.length===0)continue;if(Me(e,s.vector)>=this.deduplicationThreshold)return n}return null}}});function De(r,e,t){return[Fe(r,t),He(r,e,t),We(e,t),Ke(e),Ve(e,t),Je(r,e),Ye(r)]}function Fe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,g=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,p=[],m=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:s,tags:o});for(let f of h)p.push(Xe(f))}if(m&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(m,{limit:d,threshold:c,tags:o,includeExpired:g});for(let f of h)p.push(Qe(f))}if(m&&(n==="reflection"||n==="all")){let h=await r.queryReflections(m,{limit:d,threshold:c,tags:o,pinned:u});for(let f of h)p.push(Ze(f))}return p}}}function He(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function We(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function Ke(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function Ve(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function Je(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function Ye(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Xe(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function Qe(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function Ze(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var Pe=S(()=>{"use strict";y()});async function Be(r,e){let[t,i,n,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(p=>et(p)),u=i.map(p=>`- ${p.content}`),{beliefLines:g,reflectionLines:c}=tt(n,s,e.tokenBudget);if(o.length===0&&u.length===0&&g.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return o.length>0&&(d.push("## Goals"),d.push(...o),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),g.length>0&&(d.push("## Beliefs"),d.push(...g),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
+ `)}function et(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function tt(r,e,t){let i=t,n=[],s=[];for(let o of r){let u=`- ${o.content} (${o.confidence} confidence)`,g=re(u);if(g>i)break;n.push(u),i-=g}for(let o of e){let g=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,c=re(g);if(c>i)break;s.push(g),i-=c}return{beliefLines:n,reflectionLines:s}}var Ee=S(()=>{"use strict";y();se()});var Ne={};ge(Ne,{AgentMind:()=>oe});function pt(r,e){let t=Math.min(e.maxGoals??rt,dt),i=Math.min(e.maxPinnedReflections??st,lt);return{tokenBudget:e.tokenBudget??nt,recencyWindowDays:e.recencyWindowDays??it,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??ot,retrievalThreshold:e.retrievalThreshold??at,ttlDefaults:{belief:e.ttlDefaults?.belief??ct,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var nt,it,rt,st,ot,at,ct,dt,lt,oe,$e=S(()=>{"use strict";y();_e();Te();Pe();Ee();nt=300,it=7,rt=10,st=10,ot=.85,at=.35,ct="30d",dt=10,lt=10,oe=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new o({namespace:u})}let n=pt(e,t),s=new F(i,t.embedder);return await s.initialize(),new r(s,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),Be(this.store,this.config)]),n=new H(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),s=De(this.store,n,this.config);return{mindHeader:i,tools:s,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var ce={};ge(ce,{EphemeralAgent:()=>ae});var ae,de=S(()=>{"use strict";y();W();ae=class extends E{name;description;mode;constructor(e,t,i,n){super(n),this.name=e,this.description=t,this.mode=i}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0})}}});import{EventEmitter as ut}from"events";import{Toolpack as mt,InMemoryConversationStore as gt,AGENT_MODE as K}from"toolpack-sdk";var E,W=S(()=>{"use strict";y();Ae();be();xe();Ce();E=class extends ut{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new gt,"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 mt.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(()=>($e(),Ne));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let s,o="",u=[];if(this._mind){let g=await this._mind.createRunContext();o=g.mindHeader,u=g.tools,s=g.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let g=[];if(o&&g.push({role:"system",content:o}),n)try{let l=await Re(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),m=l.messages[l.messages.length-1],h=e.trim(),w=h!==""&&m?.role==="user"&&typeof m.content=="string"&&(m.content===h||m.content.endsWith(`: ${h}`))?l.messages.slice(0,-1):l.messages;g.push(...w)}catch{}e.trim()&&g.push({role:"user",content:e});let c=[...u];if(n){let l=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 h=await l.search(n,String(m.query??""),{limit:typeof m.limit=="number"?m.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let l=this.delegation.allowedAgents,m=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(l===void 0||l.includes(h.name)));if(m.length>0){let h=m.map(w=>w.name),f=m.map(w=>`- ${w.name}: ${w.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
- ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}}).catch(D=>{console.error(`[${this.name}] delegate_and_forget to ${I} failed:`,D)}),{status:"delegated",agent:I}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
6
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let M=String(w.agent),T=String(w.message??"");return this._registry.invoke(M,{message:T,conversationId:n,context:{delegatedBy:this.name}}).catch(N=>{console.error(`[${this.name}] delegate_and_forget to ${M} failed:`,N)}),{status:"delegated",agent:M}}}):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
- ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}})}})}}let d=await this.toolpack.generate({messages:p,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds},this.provider),l={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(l),o&&await o(!1),this.emit("agent:complete",l),l}catch(p){throw o&&o(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(p),this.emit("agent:error",p),p}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new x("Agent not registered - cannot use ask()");if(!this._conversationId)throw new x("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new x("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new x("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new x("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
9
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let M=String(w.agent),T=String(w.message??"");return this._registry.invoke(M,{message:T,conversationId:n,context:{delegatedBy:this.name}})}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let l=i?.spawnDepth??0,m=this.spawn,h=m.maxDepth??3;if(l<h){let f=m.templates,w=f.some(k=>k.name==="self"),M=f.some(k=>k.allowPromptAddition),T=f.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
10
+ `),N=w?`Use template name "self" to spawn a replica of the current agent.
11
+ `:"",j=M?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
12
+
13
+ Available templates:
14
+ ${T}
15
+ `+N+`Spawn depth: ${l}/${h}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:w?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...j},required:["template","task"]},execute:async k=>{let A=String(k.template),I=String(k.task??""),b,_,R,D,v=f.find(P=>P.name===A);if(!v)throw new Error(`Unknown spawn template: "${A}"`);let $=v.allowPromptAddition&&k.systemPromptAddition?`
16
+
17
+ ${String(k.systemPromptAddition)}`:"";if(A==="self"){let P=typeof this.mode=="string"?{...K,name:this.mode}:this.mode,L=v.systemPrompt(I);b={...P,name:`${P.name}-replica-${Date.now()}`,systemPrompt:(P.systemPrompt??"")+(L?`
18
+
19
+ ${L}`:"")+$},_=`${this.name}-replica`,R=this.description,D=this.model}else b={...K,name:`ephemeral-${v.name}-${Date.now()}`,systemPrompt:v.systemPrompt(I)+$},_=v.name,R=v.description,D=v.model;let{EphemeralAgent:U}=await Promise.resolve().then(()=>(de(),ce)),G=new U(_,R,b,{toolpack:this.toolpack});D&&(G.model=D),G.spawn={...m};let O=await G.invokeAgent({message:I,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:l+1}});return{output:O.output,spawnedTemplate:A,depth:l+1,metadata:O.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
20
+
21
+ Available templates:
22
+ ${T}
23
+ `+N+`Spawn depth: ${l}/${h}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:w?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...M?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let A=k.tasks;if(!Array.isArray(A)||A.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:I}=await Promise.resolve().then(()=>(de(),ce));return{results:await Promise.all(A.map(async _=>{let R=String(_.template),D=String(_.task??""),v=f.find(q=>q.name===R);if(!v)throw new Error(`Unknown spawn template: "${R}"`);let $=v.allowPromptAddition&&_.systemPromptAddition?`
24
+
25
+ ${String(_.systemPromptAddition)}`:"",U,G,O,P;if(R==="self"){let q=typeof this.mode=="string"?{...K,name:this.mode}:this.mode,me=v.systemPrompt(D);U={...q,name:`${q.name}-replica-${Date.now()}`,systemPrompt:(q.systemPrompt??"")+(me?`
26
+
27
+ ${me}`:"")+$},G=`${this.name}-replica`,O=this.description,P=this.model}else U={...K,name:`ephemeral-${v.name}-${Date.now()}`,systemPrompt:v.systemPrompt(D)+$},G=v.name,O=v.description,P=v.model;let L=new I(G,O,U,{toolpack:this.toolpack});P&&(L.model=P),L.spawn={...m};let ue=await L.invokeAgent({message:D,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:l+1}});return{output:ue.output,spawnedTemplate:R,depth:l+1,metadata:ue.metadata}}))}}})}}let d=await this.toolpack.generate({messages:g,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode},this.provider),p={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(p),s&&await s(!1),this.emit("agent:complete",p),p}catch(g){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(g),this.emit("agent:error",g),g}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new B("Agent not registered - cannot use ask()");if(!this._conversationId)throw new B("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new B("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 B("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new B("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
10
28
 
11
29
  Question: "${e}"
12
30
  Answer: "${t}"
13
31
 
14
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:s=>s.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new x("Agent not registered - cannot use delegateAndWait()");let i={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,i)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(n=>n.botUserId).filter(n=>typeof n=="string"&&n.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let i=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:i}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[O]===!0)?this.interceptors:[re({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let i=await this._acquireConversationLock(t.conversationId);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let n=te(this._getEffectiveInterceptors(),this,e,this._registry??null),o=await ne(n,t);if(o===null)return;let s={output:o.output,metadata:o.metadata};await e.send({output:s.output,metadata:{...s.metadata,conversationId:t.conversationId,...t.context}})}catch(n){let o=n instanceof Error?n.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${o}`);try{await e.send({output:`Error: ${o}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(s){console.error(`[${this.name}] Failed to send error to channel: ${s}`)}}finally{i()}})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,i=new Promise(n=>{t=n});return this._conversationLocks.set(e,i),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let i=t.plan;if(Array.isArray(i.steps))return i.steps.map(n=>({number:n.number||0,description:n.description||"",status:n.status||"completed",result:n.result}))}if(Array.isArray(t.steps))return t.steps}};import{CHAT_MODE as Xe}from"toolpack-sdk";var Qe={...Xe,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
15
- `)},V=class extends S{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=Qe;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let i=[];if(i.push(`Context: Public channel #${t.channelName}`),i.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),i.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){i.push(`
32
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new B("Agent not registered - cannot use delegateAndWait()");let i={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,i)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(n=>n.botUserId).filter(n=>typeof n=="string"&&n.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let i=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:i}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[Y]===!0)?this.interceptors:[ke({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let i=await this._acquireConversationLock(t.conversationId);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let n=ye(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await we(n,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(n){let s=n instanceof Error?n.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{i()}})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,i=new Promise(n=>{t=n});return this._conversationLocks.set(e,i),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let i=t.plan;if(Array.isArray(i.steps))return i.steps.map(n=>({number:n.number||0,description:n.description||"",status:n.status||"completed",result:n.result}))}if(Array.isArray(t.steps))return t.steps}}});y();y();W();import{CHAT_MODE as ft}from"toolpack-sdk";var ht={...ft,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(`
33
+ `)},le=class extends E{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=ht;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let i=[];if(i.push(`Context: Public channel #${t.channelName}`),i.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),i.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){i.push(`
16
34
  Recent conversation:`);for(let u of t.recentContext)i.push(` ${u.sender}: ${u.content.substring(0,100)}`)}i.push(`
17
35
  Message to classify: "${t.message}"`),t.includeExamples&&(i.push(`
18
36
  Examples of classifications:`),i.push(` "@${t.agentName} help me" \u2192 direct`),i.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),i.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),i.push(' "Check the logs" \u2192 ignore')),i.push(`
19
37
  Classification (start with direct, indirect, passive, or ignore):`);let n=i.join(`
20
- `),o=await this.run(n),s=this.normalizeClassification(o.output);return{output:s,metadata:{rawOutput:o.output,classification:s,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();import{CHAT_MODE as Ze}from"toolpack-sdk";var et={...Ze,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
21
- `)},J=class extends S{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=et;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let i=t.maxTokens??800,n=t.extractDecisions??!0,o=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${i} tokens`,`Extract decisions/action items: ${n?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let c of t.turns){let d=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),l=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${l}`:l,g=`[${d}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(g+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(g+=` [tool: ${c.metadata.toolName}]`),o.push(g)}o.push("","Generate a JSON summary object:");let s=o.join(`
22
- `),u=await this.run(s),p=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(p),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let i=e.trim(),n=i.match(/```(?:json)?\s*([\s\S]*?)\s*```/);n&&(i=n[1].trim());try{let o=JSON.parse(i);return{summary:typeof o.summary=="string"&&o.summary.length>0?o.summary:this.generateFallbackSummary(t),turnsSummarized:typeof o.turnsSummarized=="number"?o.turnsSummarized:t,hasDecisions:typeof o.hasDecisions=="boolean"?o.hasDecisions:!1,estimatedTokens:typeof o.estimatedTokens=="number"&&o.estimatedTokens>0?o.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};export{V as IntentClassifierAgent,J as SummarizerAgent};
38
+ `),s=await this.run(n),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();W();import{CHAT_MODE as yt}from"toolpack-sdk";var wt={...yt,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
39
+ `)},pe=class extends E{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=wt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let i=t.maxTokens??800,n=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${i} tokens`,`Extract decisions/action items: ${n?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let c of t.turns){let d=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=c.participant.displayName??c.participant.id,l=c.participant.kind==="agent"?`[BOT] ${p}`:p,m=`[${d}] ${l}: ${c.content.substring(0,200)}`;c.content.length>200&&(m+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(m+=` [tool: ${c.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let o=s.join(`
40
+ `),u=await this.run(o),g=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(g),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let i=e.trim(),n=i.match(/```(?:json)?\s*([\s\S]*?)\s*```/);n&&(i=n[1].trim());try{let s=JSON.parse(i);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};export{le as IntentClassifierAgent,pe as SummarizerAgent};
@@ -1,4 +1,4 @@
1
- export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-DVhRtkNq.cjs';
2
- import '../types-TB6yypig.cjs';
1
+ export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-Cg5gWiPj.cjs';
2
+ import '../types-C3EZvpe0.cjs';
3
3
  import 'toolpack-sdk';
4
4
  import 'events';
@@ -1,4 +1,4 @@
1
- export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-dhKoHWTy.js';
2
- import '../types-TB6yypig.js';
1
+ export { B as BaseChannel, D as DiscordChannel, b as DiscordChannelConfig, E as EmailChannel, c as EmailChannelConfig, M as McpChannel, d as McpChannelConfig, e as SMSChannel, f as SMSChannelConfig, g as ScheduledChannel, h as ScheduledChannelConfig, j as SlackChannel, k as SlackChannelConfig, T as TelegramChannel, l as TelegramChannelConfig, W as WebhookChannel, m as WebhookChannelConfig } from '../index-C0OlSL3f.js';
2
+ import '../types-C3EZvpe0.js';
3
3
  import 'toolpack-sdk';
4
4
  import 'events';
@@ -1,4 +1,4 @@
1
- import { B as BaseAgent } from './base-agent-nU8pr4nu.js';
1
+ import { B as BaseAgent } from './base-agent-C4fYjHPu.js';
2
2
 
3
3
  /**
4
4
  * Eval primitives — shared types across EvalDataset, EvalRunner, EvalScorer, and EvalReport.
@@ -1,4 +1,4 @@
1
- import { B as BaseAgent } from './base-agent-DPdK4Pnl.cjs';
1
+ import { B as BaseAgent } from './base-agent-Dqca3WLY.cjs';
2
2
 
3
3
  /**
4
4
  * Eval primitives — shared types across EvalDataset, EvalRunner, EvalScorer, and EvalReport.
@@ -1,4 +1,4 @@
1
- import { A as AgentInput, e as AgentOutput } from './types-TB6yypig.js';
1
+ import { A as AgentInput, f as AgentOutput } from './types-C3EZvpe0.js';
2
2
  import { Participant } from 'toolpack-sdk';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { A as AgentInput, e as AgentOutput } from './types-TB6yypig.cjs';
1
+ import { A as AgentInput, f as AgentOutput } from './types-C3EZvpe0.cjs';
2
2
  import { Participant } from 'toolpack-sdk';
3
3
 
4
4
  /**