@toolpack-sdk/agents 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Build production-ready AI agents with channels, workflows, and event-driven arch
8
8
  ## Features
9
9
 
10
10
  - **4 Built-in Agents** — Research, Coding, Data, Browser
11
- - **8 Channel Types** — Slack, Telegram, Discord, Email, SMS, Webhook, Scheduled, MCP
11
+ - **9 Channel Types** — Slack, Telegram, Discord, Email, SMS, Webhook, Scheduled, MCP, Chat
12
12
  - **Event-Driven** — Full lifecycle hooks and events
13
13
  - **Human-in-the-Loop** — `ask()` support for two-way channels
14
14
  - **Knowledge Integration** — Built-in RAG support with knowledge bases
@@ -22,7 +22,7 @@ Build production-ready AI agents with channels, workflows, and event-driven arch
22
22
  ## Installation
23
23
 
24
24
  ```bash
25
- npm install @toolpack-sdk/agents
25
+ npm install toolpack-sdk @toolpack-sdk/agents
26
26
  ```
27
27
 
28
28
  ## Stable API (Phase 4)
@@ -266,6 +266,41 @@ await sdk.startMcpServer({
266
266
 
267
267
  `ch.asAgentDefinition(agent)` produces the entry that `startMcpServer` registers in `tools/list`. Each MCP `tools/call` for `agent.<name>` is routed through the channel to `agent.invokeAgent()` and the output is returned as the tool result.
268
268
 
269
+ ### ChatChannel (Externally-driven)
270
+
271
+ `ChatChannel` is a non-trigger channel intended for use cases where your own HTTP server or framework receives requests and drives the agent directly. `listen()` and `send()` are no-ops — the caller invokes `agent.invokeAgent()` manually.
272
+
273
+ ```typescript
274
+ import { BaseAgent, ChatChannel } from '@toolpack-sdk/agents';
275
+
276
+ const chat = new ChatChannel({ name: 'chat' });
277
+
278
+ class MyAgent extends BaseAgent {
279
+ name = 'my-agent';
280
+ channels = [chat];
281
+
282
+ async invokeAgent(input) {
283
+ const result = await this.run(input.message, undefined, {
284
+ conversationId: input.conversationId,
285
+ }, input.attachments);
286
+ return result;
287
+ }
288
+ }
289
+
290
+ const agent = new MyAgent({ toolpack });
291
+ await agent.start();
292
+
293
+ // In your HTTP handler:
294
+ const result = await agent.invokeAgent({
295
+ message: req.body.message,
296
+ attachments: req.body.attachments, // optional FilePart / ImagePart array
297
+ conversationId: req.body.conversationId,
298
+ participant: { id: req.body.userId },
299
+ });
300
+ ```
301
+
302
+ `normalize()` parses the incoming body and populates `message`, `attachments`, `conversationId`, and `participant`. Attachment size limits are validated inside `normalize()` via `validateAttachments()` — `FilePart` size is only checked when the `size` field is supplied.
303
+
269
304
  ## Creating Custom Agents
270
305
 
271
306
  Extend `BaseAgent` to create custom agents:
@@ -561,9 +596,12 @@ const toolpack = await Toolpack.init({
561
596
 
562
597
  ## Peer Dependencies
563
598
 
564
- The following are optional peer dependencies. Install only what you need:
599
+ Requires `toolpack-sdk` (`^3.1.0`). Optional peers install only what you need:
565
600
 
566
601
  ```bash
602
+ # Knowledge / RAG (optional)
603
+ npm install @toolpack-sdk/knowledge
604
+
567
605
  # For DiscordChannel
568
606
  npm install discord.js
569
607
 
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
- import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack } from 'toolpack-sdk';
3
- import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-CJinv165.cjs';
2
+ import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack, ImagePart, FilePart } from 'toolpack-sdk';
3
+ import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-D5dxhUX8.cjs';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -206,7 +206,7 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
206
206
  protected run(message: string, _options?: AgentRunOptions, context?: {
207
207
  conversationId?: string;
208
208
  spawnDepth?: number;
209
- }): Promise<AgentResult>;
209
+ }, attachments?: Array<ImagePart | FilePart>): Promise<AgentResult>;
210
210
  /**
211
211
  * Returns extra identity strings (platform user ids, bot ids) that should
212
212
  * be treated as this agent for the purposes of `addressed-only` mode in
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
- import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack } from 'toolpack-sdk';
3
- import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-CJinv165.js';
2
+ import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack, ImagePart, FilePart } from 'toolpack-sdk';
3
+ import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-D5dxhUX8.js';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -206,7 +206,7 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
206
206
  protected run(message: string, _options?: AgentRunOptions, context?: {
207
207
  conversationId?: string;
208
208
  spawnDepth?: number;
209
- }): Promise<AgentResult>;
209
+ }, attachments?: Array<ImagePart | FilePart>): Promise<AgentResult>;
210
210
  /**
211
211
  * Returns extra identity strings (platform user ids, bot ids) that should
212
212
  * be treated as this agent for the purposes of `addressed-only` mode in
@@ -1,42 +1,42 @@
1
- "use strict";var Ve=Object.create;var K=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Xe=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty;var T=(r,e)=>()=>(r&&(e=r(r=0)),e);var te=(r,e)=>{for(var t in e)K(r,t,{get:e[t],enumerable:!0})},ve=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ye(e))!Qe.call(r,n)&&n!==t&&K(r,n,{get:()=>e[n],enumerable:!(i=Je(e,n))||i.enumerable});return r};var Ze=(r,e,t)=>(t=r!=null?Ve(Xe(r)):{},ve(e||!r||!r.__esModule?K(t,"default",{value:r,enumerable:!0}):t,r)),et=r=>ve(K({},"__esModule",{value:!0}),r);var h=T(()=>{"use strict"});function ke(r){return r===V}function be(){return V}var V,ne=T(()=>{"use strict";h();V=Symbol("interceptor-skip-sentinel")});function Ie(r,e,t,i,n={}){let s=n.maxInvocationDepth??5;return{async execute(o){let u=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>s)throw new ie(g,s);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let A=i.getAgent(l);if(!A)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??o.conversationId??`delegation-${Date.now()}`};return await A.invokeAgent(f)},skip:be}))(0),c=async d=>{let l=d??o;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??o,u,m)}return await c()}}}async function Ce(r,e){let t=await r.execute(e);return t===V?null:t}var ie,xe=T(()=>{"use strict";h();ne();ie=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function tt(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function Re(r){let e=r.captureAgentReplies??!0,t=r.getScope??tt,i=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,re.randomUUID)()),n=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,p,u)=>{let c=o.conversationId;if(!c)return p.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await u();let d=o.participant;if(d){let m={id: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(m),r.onCaptured?.(m),p.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){p.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await u();if(e&&!ke(l)&&l.output!=null){let m={kind:"agent",id:p.agent.name,displayName:p.agent.name},g={id:(0,re.randomUUID)(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),p.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:p.agent.name,conversationId:c})}catch(A){p.logger?.warn("[capture-history] Failed to store agent reply",{error:A instanceof Error?A.message:String(A)})}}return l};return s[se]=!0,s}var re,se,_e=T(()=>{"use strict";h();re=require("crypto");ne();se=Symbol.for("toolpack:capture-history")});function Se(r){return Math.ceil(r.length/4)}function nt(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function it(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 rt(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function Te(r,e,t,i,n={},s){let{scope:o,addressedOnlyMode:p=!0,tokenBudget:u=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),A=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:A,limit:l}),y=f.length;if(p){let b=new Set;for(let M=0;M<f.length;M++){let k=f[M];if(rt(k,t,g)&&b.add(k.id),M<f.length-1){let _=f[M+1];_.participant.kind==="agent"&&_.participant.id===t&&b.add(k.id)}}let C=f[f.length-1];C&&b.add(C.id),f=f.filter(M=>b.has(M.id))}let w=!1;if(f.length>c&&s){let b=Math.floor(f.length/2),C=f.slice(0,b),M=f.slice(b),k=C.filter(_=>!_.metadata?.isSummary);try{let _=await s.invokeAgent({message:"summarize",data:{turns:k.map(nt),agentName:i,agentId:t,maxTokens:Math.floor(u*.25),extractDecisions:!0}}),$=JSON.parse(_.output),U={id:`summary-${(0,Me.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${$.turnsSummarized} earlier turns]: ${$.summary}`,timestamp:C[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[U,...M],w=!0;try{await r.append(U),await r.deleteMessages(e,C.map(P=>P.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let v=f.map(b=>it(b,t));if(v.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:y,hasSummary:w};let R=v[v.length-1],I=[R],D=Se(R.content);for(let b=v.length-2;b>=0;b--){let C=v[b],M=Se(C.content);if(D+M>u)break;I.unshift(C),D+=M}return{messages:I,estimatedTokens:D,turnsLoaded:y,hasSummary:w}}var Me,De=T(()=>{"use strict";h();Me=require("crypto")});var E,Pe=T(()=>{"use strict";h();E=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var J,oe,ae,ce,de,le,a,Y,Be=T(()=>{"use strict";h();J=require("crypto"),oe=.6,ae=.2,ce=.2,de={low:.3,medium:.6,high:1},le=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"},Y=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,u=Math.exp(-o/le)*ae+de.high*ce+oe;return{...s,score:u}}).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(u=>this.chunkToGoal(u.chunk));else{let p=n;if(o=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===p)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();o=o.filter(d=>d.description.toLowerCase().includes(c))}}return s?.length&&(o=o.filter(p=>s.every(u=>p.tags.includes(u)))),o.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:s,includeExpired:o=!1}=t,p=Date.now(),u=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of u){let l=this.chunkToBelief(d.chunk);if(!o&&l.expiresAt&&l.expiresAt<p||s?.length&&!s.every(y=>l.tags.includes(y)))continue;let m=(p-l.createdAt)/864e5,g=Math.exp(-m/le),A=l.error?.3:de[l.confidence],f=d.score*oe+g*ae+A*ce;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:s,pinned:o}=t,p=Date.now(),u={[a.type]:"reflection"};o===!0&&(u[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:u}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(o===!1&&m.pinned||s?.length&&!s.every(y=>m.tags.includes(y)))continue;let g=(p-m.createdAt)/864e5,A=Math.exp(-g/le),f=l.score*oe+A*ae+de.medium*ce;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 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=(0,J.randomUUID)();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=(0,J.randomUUID)();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()},p=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,p)])}async addReflection(e,t){let i=(0,J.randomUUID)();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 pe(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 Ee(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=pe(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ne(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 ue(r){return Math.ceil(r.length/4)}var me=T(()=>{"use strict";h()});var $e,X,Ge=T(()=>{"use strict";h();$e=require("crypto");me();X=class{constructor(e,t,i,n,s,o,p){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=p}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,s=e.expiresIn??e.ttlDefault;s&&(n=t+pe(s));let o=this._findSimilarInDraft(i);if(o!==null){let d=this.ops[o],l=e.confidence,m=d.confidence,g={low:0,medium:1,high:2},A=g[l]>g[m]||e.allowDowngrade&&g[l]<g[m];return this.ops[o]={...d,content:e.content,confidence:A?l:m,tags:e.tags.length>0?e.tags:d.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:d.existingId??`draft-${o}`}}let p=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(p))return{action:"updated_draft",id:"in-flight-dedup"};let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let d=u.belief,l=e.confidence,m=d.confidence,g={low:0,medium:1,high:2},A=g[l]>g[m]||e.allowDowngrade&&g[l]<g[m],f={op:"believe",content:e.content,confidence:A?l:m,tags:e.tags.length>0?e.tags:d.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(f),{action:"updated_store",id:u.id}}this.inFlightBeliefs.add(p);let c={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(c),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let 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?Ee(e.dueBy):void 0,i={op:"set_goal",tempId:(0,$e.randomUUID)(),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;this.inFlightBeliefs.delete(n.content.trim().toLowerCase()),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;if(n.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content: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){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=i;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(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(Ne(e,s.vector)>=this.deduplicationThreshold)return n}return null}}});function Oe(r,e,t){return[st(r,t),ot(r,e,t),at(e,t),ct(e),dt(e,t),lt(r,e),pt(r)]}function st(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,p=typeof t.pinned=="boolean"?t.pinned:void 0,u=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let A=await r.keywordSearchGoals(i,{limit:d,status:s,tags:o});for(let f of A)l.push(ut(f))}if(g&&(n==="belief"||n==="all")){let A=await r.queryBeliefs(g,{limit:d,threshold:c,tags:o,includeExpired:u});for(let f of A)l.push(mt(f))}if(g&&(n==="reflection"||n==="all")){let A=await r.queryReflections(g,{limit:d,threshold:c,tags:o,pinned:p});for(let f of A)l.push(gt(f))}return l}}}function ot(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 at(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 ct(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 dt(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 lt(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 pt(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 ut(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 mt(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 gt(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 Le=T(()=>{"use strict";h()});async function Ue(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(l=>ft(l)),p=i.map(l=>`- ${l.content}`),{beliefLines:u,reflectionLines:c}=ht(n,s,e.tokenBudget);if(o.length===0&&p.length===0&&u.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return o.length>0&&(d.push("## Goals"),d.push(...o),d.push("")),p.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...p),d.push("")),u.length>0&&(d.push("## Beliefs"),d.push(...u),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
- `)}function ft(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 ht(r,e,t){let i=t,n=[],s=[];for(let o of r){let p=`- ${o.content} (${o.confidence} confidence)`,u=ue(p);if(u>i)break;n.push(p),i-=u}for(let o of e){let u=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,c=ue(u);if(c>i)break;s.push(u),i-=c}return{beliefLines:n,reflectionLines:s}}var qe=T(()=>{"use strict";h();me()});var je={};te(je,{AgentMind:()=>ge});function Rt(r,e){let t=Math.min(e.maxGoals??At,Ct),i=Math.min(e.maxPinnedReflections??vt,xt);return{tokenBudget:e.tokenBudget??yt,recencyWindowDays:e.recencyWindowDays??wt,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??kt,retrievalThreshold:e.retrievalThreshold??bt,ttlDefaults:{belief:e.ttlDefaults?.belief??It,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var yt,wt,At,vt,kt,bt,It,Ct,xt,ge,Fe=T(()=>{"use strict";h();Be();Ge();Le();qe();yt=300,wt=7,At=10,vt=10,kt=.85,bt=.35,It="30d",Ct=10,xt=10,ge=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),p=t.namespace??`mind/${e}`;i=new o({namespace:p})}let n=Rt(e,t),s=new Y(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(),Ue(this.store,this.config)]),n=new X(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Oe(this.store,n,this.config);return{mindHeader:i,tools:s,flush:async p=>{p?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var he={};te(he,{EphemeralAgent:()=>fe});var fe,ye=T(()=>{"use strict";h();Q();fe=class extends L{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})}}});var ze,He,N,L,Q=T(()=>{"use strict";h();ze=require("events"),He=require("async_hooks"),N=require("toolpack-sdk");xe();_e();De();Pe();L=class extends ze.EventEmitter{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new He.AsyncLocalStorage;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new N.InMemoryConversationStore,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await N.Toolpack.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(Fe(),je));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,i){let n=i?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let s,o="",p=[];if(this._mind){let u=await this._mind.createRunContext();o=u.mindHeader,p=u.tools,s=u.flush}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let u=[];if(o&&u.push({role:"system",content:o}),n)try{let y=await Te(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),w=y.messages[y.messages.length-1],v=e.trim(),I=v!==""&&w?.role==="user"&&typeof w.content=="string"&&(w.content===v||w.content.endsWith(`: ${v}`))?y.messages.slice(0,-1):y.messages;u.push(...I)}catch{}e.trim()&&u.push({role:"user",content:e});let c=[...p];if(n){let y=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async w=>{let v=await y.search(n,String(w.query??""),{limit:typeof w.limit=="number"?w.limit:5});return{results:v.map(R=>({role:R.participant.kind==="agent"?"assistant":"user",content:R.content,timestamp:R.timestamp})),count:v.length}}})}if(this.delegation?.enabled&&this._registry){let y=this.delegation.allowedAgents,w=this._registry.getAllAgents().filter(v=>v.name!==this.name&&(y===void 0||y.includes(v.name)));if(w.length>0){let v=w.map(I=>I.name),R=w.map(I=>`- ${I.name}: ${I.description}`).join(`
1
+ "use strict";var Je=Object.create;var V=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var M=(r,e)=>()=>(r&&(e=r(r=0)),e);var ne=(r,e)=>{for(var t in e)V(r,t,{get:e[t],enumerable:!0})},ke=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xe(e))!Ze.call(r,i)&&i!==t&&V(r,i,{get:()=>e[i],enumerable:!(n=Ye(e,i))||n.enumerable});return r};var et=(r,e,t)=>(t=r!=null?Je(Qe(r)):{},ke(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r)),tt=r=>ke(V({},"__esModule",{value:!0}),r);var h=M(()=>{"use strict"});function be(r){return r===J}function Ie(){return J}var J,ie=M(()=>{"use strict";h();J=Symbol("interceptor-skip-sentinel")});function Ce(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let d=(c=>({agent:e,channel:t,registry:n,invocationDepth:c,delegateAndWait:async(p,g)=>{let m=c+1;if(m>s)throw new re(m,s);if(!n)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let w=n.getAgent(p);if(!w)throw new Error(`Agent "${p}" not found for delegation`);let f={message:g.message??"",intent:g.intent,data:g.data,context:g.context,conversationId:g.conversationId??o.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(f)},skip:Ie}))(0),l=async c=>{let p=c??o;return await e.invokeAgent(p)};for(let c=r.length-1;c>=0;c--){let p=r[c],g=l;l=async m=>await p(m??o,d,g)}return await l()}}}async function xe(r,e){let t=await r.execute(e);return t===J?null:t}var re,Re=M(()=>{"use strict";h();ie();re=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function nt(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function _e(r){let e=r.captureAgentReplies??!0,t=r.getScope??nt,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,se.randomUUID)()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,u,d)=>{let l=o.conversationId;if(!l)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await d();let c=o.participant;if(c){let g={id:n(o),conversationId:l,participant:c,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:i(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured inbound message",{messageId:g.id,participantId:c.id,conversationId:l})}catch(m){u.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let p=await d();if(e&&!be(p)&&p.output!=null){let g={kind:"agent",id:u.agent.name,displayName:u.agent.name},m={id:(0,se.randomUUID)(),conversationId:l,participant:g,content:p.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:u.agent.name,conversationId:l})}catch(w){u.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return p};return s[oe]=!0,s}var se,oe,Se=M(()=>{"use strict";h();se=require("crypto");ie();oe=Symbol.for("toolpack:capture-history")});function Me(r){return Math.ceil(r.length/4)}function it(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function rt(r,e){let{participant:t,content:n}=r;return t.kind==="system"?{role:"system",content:n}:t.kind==="agent"?t.id===e?{role:"assistant",content:n}:{role:"user",content:`${t.displayName??t.id} (agent): ${n}`}:{role:"user",content:`${t.displayName??t.id}: ${n}`}}function st(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function Te(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:u=!0,tokenBudget:d=3e3,rollingSummaryThreshold:l=40,timeWindowMinutes:c,maxTurnsToLoad:p=100,agentAliases:g}=i,m=new Set([t,...g??[]]),w=c!==void 0?new Date(Date.now()-c*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:w,limit:p}),T=f.length;if(u){let v=new Set;for(let I=0;I<f.length;I++){let U=f[I];if(st(U,t,m)&&v.add(U.id),I<f.length-1){let k=f[I+1];k.participant.kind==="agent"&&k.participant.id===t&&v.add(U.id)}}let _=f[f.length-1];_&&v.add(_.id),f=f.filter(I=>v.has(I.id))}let y=!1;if(f.length>l&&s){let v=Math.floor(f.length/2),_=f.slice(0,v),I=f.slice(v),U=_.filter(k=>!k.metadata?.isSummary);try{let k=await s.invokeAgent({message:"summarize",data:{turns:U.map(it),agentName:n,agentId:t,maxTokens:Math.floor(d*.25),extractDecisions:!0}}),P=JSON.parse(k.output),N={id:`summary-${(0,Pe.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${P.turnsSummarized} earlier turns]: ${P.summary}`,timestamp:_[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[N,...I],y=!0;try{await r.append(N),await r.deleteMessages(e,_.map(q=>q.id))}catch{}}catch{f=f.slice(-l)}}else f.length>l&&(f=f.slice(-l));let A=f.map(v=>rt(v,t));if(A.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:T,hasSummary:y};let C=A[A.length-1],R=[C],b=Me(C.content);for(let v=A.length-2;v>=0;v--){let _=A[v],I=Me(_.content);if(b+I>d)break;R.unshift(_),b+=I}return{messages:R,estimatedTokens:b,turnsLoaded:T,hasSummary:y}}var Pe,De=M(()=>{"use strict";h();Pe=require("crypto")});var B,Be=M(()=>{"use strict";h();B=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var Y,ae,ce,de,le,pe,a,X,Ee=M(()=>{"use strict";h();Y=require("crypto"),ae=.6,ce=.2,de=.2,le={low:.3,medium:.6,high:1},pe=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"},X=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,n)=>{let i={high:0,normal:1,low:2},s=i[t.priority]-i[n.priority];return s!==0?s:t.createdAt-n.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(i=>i[a.type]==="belief"&&i[a.confidence]==="high"&&!i[a.error]&&!(i[a.expiresAt]&&i[a.expiresAt]<t))).map(i=>{let s=this.chunkToBelief(i),o=(t-s.createdAt)/864e5,d=Math.exp(-o/pe)*ce+le.high*de+ae;return{...s,score:d}}).sort((i,s)=>s.score-i.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:i="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[a.type]:"goal",[a.status]:i}})).map(d=>this.chunkToGoal(d.chunk));else{let u=i;if(o=(await this._getAllByMeta(l=>l[a.type]==="goal"&&l[a.status]===u)).map(l=>this.chunkToGoal(l)),e.trim()){let l=e.toLowerCase();o=o.filter(c=>c.description.toLowerCase().includes(l))}}return s?.length&&(o=o.filter(u=>s.every(d=>u.tags.includes(d)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,u=Date.now(),d=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),l=[];for(let c of d){let p=this.chunkToBelief(c.chunk);if(!o&&p.expiresAt&&p.expiresAt<u||s?.length&&!s.every(T=>p.tags.includes(T)))continue;let g=(u-p.createdAt)/864e5,m=Math.exp(-g/pe),w=p.error?.3:le[p.confidence],f=c.score*ae+m*ce+w*de;f<i||l.push({...p,score:f})}return l.sort((c,p)=>p.score-c.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,u=Date.now(),d={[a.type]:"reflection"};o===!0&&(d[a.pinned]=!0);let l=await this.provider.query(e,{limit:n*4,threshold:0,filter:d}),c=[];for(let p of l){let g=this.chunkToReflection(p.chunk);if(o===!1&&g.pinned||s?.length&&!s.every(T=>g.tags.includes(T)))continue;let m=(u-g.createdAt)/864e5,w=Math.exp(-m/pe),f=p.score*ae+w*ce+le.medium*de;f<i||c.push({...g,score:f})}return c.sort((p,g)=>g.score-p.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),i=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of i){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=(0,Y.randomUUID)();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n),s={...i,description:t.description??i.description,priority:t.priority??i.priority,status:t.status??i.status,outcome:t.outcome??i.outcome,progress:t.appendProgress?[...i.progress,t.appendProgress]:i.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...i,status:"completed",outcome:t??i.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=(0,Y.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(i),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},u=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,u)])}async addReflection(e,t){let n=(0,Y.randomUUID)();return await this.provider.add([this.reflectionToChunk({...e,id:n},t)]),n}async updateReflection(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Reflection not found: ${e}`);let i=this.chunkToReflection(n),s={...i,pinned:t.pinned??i.pinned,error:t.error??i.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,n.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(n=>n.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(n=>e(n.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function ue(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),n=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[n]}function Ne(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=ue(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function $e(r,e){let t=0,n=0,i=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],i+=e[o]*e[o];let s=Math.sqrt(n)*Math.sqrt(i);return s===0?0:t/s}function me(r){return Math.ceil(r.length/4)}var ge=M(()=>{"use strict";h()});var Ge,Q,Oe=M(()=>{"use strict";h();Ge=require("crypto");ge();Q=class{constructor(e,t,n,i,s,o,u){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=u}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+ue(s));let o=this._findSimilarInDraft(n);if(o!==null){let c=this.ops[o],p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},w=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g];return this.ops[o]={...c,content:e.content,confidence:w?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:c.existingId??`draft-${o}`}}let u=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(u))return{action:"updated_draft",id:"in-flight-dedup"};let d=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(d){let c=d.belief,p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},w=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g],f={op:"believe",content:e.content,confidence:w?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:d.id};return this.ops.push(f),{action:"updated_store",id:d.id}}this.inFlightBeliefs.add(u);let l={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(l),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),i={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:n},s=`draft-reflect-${this.ops.length}`;return this.ops.push(i),{id:s,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?Ne(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Ge.randomUUID)(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(n),{id:n.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let n of this.ops)if(n.op==="believe"){let i=n;this.inFlightBeliefs.delete(i.content.trim().toLowerCase()),e?i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0,createdAt:i.createdAt,updatedAt:t},i.vector):i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="reflect"){let i=n;if(i.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content:i.content,pinned:i.pinned,tags:i.tags,relatedTo:i.relatedTo,error:e||void 0,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="set_goal"){if(!e){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=n;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(n.op==="update_goal"){if(!e){let i=n;await this.store.updateGoal(i.id,{description:i.description,priority:i.priority,appendProgress:i.progress})}}else if(n.op==="unpin_reflection"&&!e){let i=n;await this.store.updateReflection(i.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,i)=>({op:n,idx:i})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:i}of t){let s=n;if(s.vector.length===0)continue;if($e(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function Le(r,e,t){return[ot(r,t),at(r,e,t),ct(e,t),dt(e),lt(e,t),pt(r,e),ut(r)]}function ot(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let n=String(t.query??""),i=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,d=t.includeExpired===!0,l=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,c=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,p=[],m=(i==="belief"||i==="reflection"||i==="all")&&n.trim()?await r.embed(n):null;if(i==="goal"||i==="all"){let w=await r.keywordSearchGoals(n,{limit:c,status:s,tags:o});for(let f of w)p.push(mt(f))}if(m&&(i==="belief"||i==="all")){let w=await r.queryBeliefs(m,{limit:c,threshold:l,tags:o,includeExpired:d});for(let f of w)p.push(gt(f))}if(m&&(i==="reflection"||i==="all")){let w=await r.queryReflections(m,{limit:c,threshold:l,tags:o,pinned:u});for(let f of w)p.push(ft(f))}return p}}}function at(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async n=>({status:"ok",...await e.addBelieve({content:String(n.content),confidence:n.confidence??"medium",tags:Array.isArray(n.tags)?n.tags.map(String):[],expiresIn:n.expiresIn?String(n.expiresIn):void 0,allowDowngrade:n.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function ct(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 dt(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 lt(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 pt(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 ut(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 mt(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 gt(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 ft(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 Ue=M(()=>{"use strict";h()});async function je(r,e){let[t,n,i,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(p=>ht(p)),u=n.map(p=>`- ${p.content}`),{beliefLines:d,reflectionLines:l}=yt(i,s,e.tokenBudget);if(o.length===0&&u.length===0&&d.length===0&&l.length===0)return"";let c=["--- AGENT MIND ---",""];return o.length>0&&(c.push("## Goals"),c.push(...o),c.push("")),u.length>0&&(c.push("## Standing Rules (Pinned)"),c.push(...u),c.push("")),d.length>0&&(c.push("## Beliefs"),c.push(...d),c.push("")),l.length>0&&(c.push("## Recent Reflections"),c.push(...l),c.push("")),c.push("---"),c.join(`
2
+ `)}function ht(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 yt(r,e,t){let n=t,i=[],s=[];for(let o of r){let u=`- ${o.content} (${o.confidence} confidence)`,d=me(u);if(d>n)break;i.push(u),n-=d}for(let o of e){let d=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,l=me(d);if(l>n)break;s.push(d),n-=l}return{beliefLines:i,reflectionLines:s}}var qe=M(()=>{"use strict";h();ge()});var Fe={};ne(Fe,{AgentMind:()=>fe});function _t(r,e){let t=Math.min(e.maxGoals??vt,xt),n=Math.min(e.maxPinnedReflections??kt,Rt);return{tokenBudget:e.tokenBudget??wt,recencyWindowDays:e.recencyWindowDays??At,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??bt,retrievalThreshold:e.retrievalThreshold??It,ttlDefaults:{belief:e.ttlDefaults?.belief??Ct,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var wt,At,vt,kt,bt,It,Ct,xt,Rt,fe,ze=M(()=>{"use strict";h();Ee();Oe();Ue();qe();wt=300,At=7,vt=10,kt=10,bt=.85,It=.35,Ct="30d",xt=10,Rt=10,fe=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let n;if(t.provider)n=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;n=new o({namespace:u})}let i=_t(e,t),s=new X(n,t.embedder);return await s.initialize(),new r(s,i)}async createRunContext(){let[e,t,n]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),je(this.store,this.config)]),i=new Q(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Le(this.store,i,this.config),o={manifest:{key:"mind",name:"mind",displayName:"Agent Mind",version:"1.0.0",description:"Agent cognitive tools for beliefs, goals, and reflections.",category:"mind",tools:s.map(d=>d.name)},tools:s};return{mindHeader:n,toolProject:o,flush:async d=>{d?await i.flushOnError():await i.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var ye={};ne(ye,{EphemeralAgent:()=>he});var he,we=M(()=>{"use strict";h();Z();he=class extends L{name;description;mode;constructor(e,t,n,i){super(i),this.name=e,this.description=t,this.mode=n}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0},e.attachments)}}});var He,We,E,L,Z=M(()=>{"use strict";h();He=require("events"),We=require("async_hooks"),E=require("toolpack-sdk");Re();Se();De();Be();L=class extends He.EventEmitter{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new We.AsyncLocalStorage;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new E.InMemoryConversationStore,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await E.Toolpack.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(ze(),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?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,n,i){let s=n?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:s}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,u="";if(this._mind){let d=await this._mind.createRunContext();u=d.mindHeader,o=d.flush,this.toolpack.loadRequestToolProject(d.toolProject)}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let d=[];if(u&&d.push({role:"system",content:u}),s)try{let y=await Te(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),A=y.messages[y.messages.length-1],C=e.trim(),b=C!==""&&A?.role==="user"&&typeof A.content=="string"&&(A.content===C||A.content.endsWith(`: ${C}`))?y.messages.slice(0,-1):y.messages;d.push(...b)}catch{}let l=i&&i.length>0;if(e.trim()||l)if(l){let y=[...e.trim()?[{type:"text",text:e}]:[],...i];d.push({role:"user",content:y})}else d.push({role:"user",content:e});let c=[];if(s){let y=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async A=>{let C=await y.search(s,String(A.query??""),{limit:typeof A.limit=="number"?A.limit:5});return{results:C.map(R=>({role:R.participant.kind==="agent"?"assistant":"user",content:R.content,timestamp:R.timestamp})),count:C.length}}})}if(this.delegation?.enabled&&this._registry){let y=this.delegation.allowedAgents,A=this._registry.getAllAgents().filter(C=>C.name!==this.name&&(y===void 0||y.includes(C.name)));if(A.length>0){let C=A.map(b=>b.name),R=A.map(b=>`- ${b.name}: ${b.description}`).join(`
3
3
  `);this.delegation.mode==="forget"?c.push({name:"delegate_and_forget",displayName:"Delegate and Forget",description:`Hand off the current task to a peer agent. The agent will handle its own delivery (e.g. posting to Slack or GitHub) \u2014 you do not need to relay its response. Call this ONCE, then output an empty string.
4
4
 
5
5
  Available agents:
6
- ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:v,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async I=>{let D=String(I.agent),b=String(I.message??"");return this._registry.invoke(D,{message:b,conversationId:n,context:{delegatedBy:this.name},signal:t?.signal}).catch(C=>{console.error(`[${this.name}] delegate_and_forget to ${D} failed:`,C)}),{status:"delegated",agent:D}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
6
+ ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:C,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async b=>{let v=String(b.agent),_=String(b.message??"");return this._registry.invoke(v,{message:_,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal}).catch(I=>{console.error(`[${this.name}] delegate_and_forget to ${v} failed:`,I)}),{status:"delegated",agent:v}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
7
7
 
8
8
  Available agents:
9
- ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:v,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async I=>{let D=String(I.agent),b=String(I.message??""),C=await this._registry.invoke(D,{message:b,conversationId:n,context:{delegatedBy:this.name},signal:t?.signal});return{...C,output:`[Response from ${D} \u2014 task complete]
9
+ ${R}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:C,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async b=>{let v=String(b.agent),_=String(b.message??""),I=await this._registry.invoke(v,{message:_,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal});return{...I,output:`[Response from ${v} \u2014 task complete]
10
10
 
11
- ${C.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let y=i?.spawnDepth??0,w=this.spawn,v=w.maxDepth??3;if(y<v){let R=w.templates,I=R.some(k=>k.name==="self"),D=R.some(k=>k.allowPromptAddition),b=R.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
12
- `),C=I?`Use template name "self" to spawn a replica of the current agent.
13
- `:"",M=D?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
11
+ ${I.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let y=n?.spawnDepth??0,A=this.spawn,C=A.maxDepth??3;if(y<C){let R=A.templates,b=R.some(k=>k.name==="self"),v=R.some(k=>k.allowPromptAddition),_=R.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
12
+ `),I=b?`Use template name "self" to spawn a replica of the current agent.
13
+ `:"",U=v?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
14
14
 
15
15
  Available templates:
16
- ${b}
17
- `+C+`Spawn depth: ${y}/${v}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:I?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...M},required:["template","task"]},execute:async k=>{let _=String(k.template),$=String(k.task??""),U,P,G,O,x=R.find(B=>B.name===_);if(!x)throw new Error(`Unknown spawn template: "${_}"`);let z=x.allowPromptAddition&&k.systemPromptAddition?`
16
+ ${_}
17
+ `+I+`Spawn depth: ${y}/${C}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:b?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...U},required:["template","task"]},execute:async k=>{let P=String(k.template),N=String(k.task??""),q,$,G,O,x=R.find(D=>D.name===P);if(!x)throw new Error(`Unknown spawn template: "${P}"`);let H=x.allowPromptAddition&&k.systemPromptAddition?`
18
18
 
19
- ${String(k.systemPromptAddition)}`:"";if(_==="self"){let B=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,F=x.systemPrompt($);U={...B,name:`${B.name}-replica-${Date.now()}`,systemPrompt:(B.systemPrompt??"")+(F?`
19
+ ${String(k.systemPromptAddition)}`:"";if(P==="self"){let D=typeof this.mode=="string"?{...E.AGENT_MODE,name:this.mode}:this.mode,z=x.systemPrompt(N);q={...D,name:`${D.name}-replica-${Date.now()}`,systemPrompt:(D.systemPrompt??"")+(z?`
20
20
 
21
- ${F}`:"")+z},P=`${this.name}-replica`,G=this.description,O=this.model}else U={...N.AGENT_MODE,name:`ephemeral-${x.name}-${Date.now()}`,systemPrompt:x.systemPrompt($)+z},P=x.name,G=x.description,O=x.model;let{EphemeralAgent:H}=await Promise.resolve().then(()=>(ye(),he)),q=new H(P,G,U,{toolpack:this.toolpack});O&&(q.model=O),q.spawn={...w};let j=await q.invokeAgent({message:$,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:j.output,spawnedTemplate:_,depth:y+1,metadata:j.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
21
+ ${z}`:"")+H},$=`${this.name}-replica`,G=this.description,O=this.model}else q={...E.AGENT_MODE,name:`ephemeral-${x.name}-${Date.now()}`,systemPrompt:x.systemPrompt(N)+H},$=x.name,G=x.description,O=x.model;let{EphemeralAgent:W}=await Promise.resolve().then(()=>(we(),ye)),j=new W($,G,q,{toolpack:this.toolpack});O&&(j.model=O),j.spawn={...A};let F=await j.invokeAgent({message:N,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:F.output,spawnedTemplate:P,depth:y+1,metadata:F.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
22
22
 
23
23
  Available templates:
24
- ${b}
25
- `+C+`Spawn depth: ${y}/${v}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:I?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...D?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let _=k.tasks;if(!Array.isArray(_)||_.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:$}=await Promise.resolve().then(()=>(ye(),he));return{results:await Promise.all(_.map(async P=>{let G=String(P.template),O=String(P.task??""),x=R.find(W=>W.name===G);if(!x)throw new Error(`Unknown spawn template: "${G}"`);let z=x.allowPromptAddition&&P.systemPromptAddition?`
24
+ ${_}
25
+ `+I+`Spawn depth: ${y}/${C}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:b?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...v?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let P=k.tasks;if(!Array.isArray(P)||P.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:N}=await Promise.resolve().then(()=>(we(),ye));return{results:await Promise.all(P.map(async $=>{let G=String($.template),O=String($.task??""),x=R.find(K=>K.name===G);if(!x)throw new Error(`Unknown spawn template: "${G}"`);let H=x.allowPromptAddition&&$.systemPromptAddition?`
26
26
 
27
- ${String(P.systemPromptAddition)}`:"",H,q,j,B;if(G==="self"){let W=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,Ae=x.systemPrompt(O);H={...W,name:`${W.name}-replica-${Date.now()}`,systemPrompt:(W.systemPrompt??"")+(Ae?`
27
+ ${String($.systemPromptAddition)}`:"",W,j,F,D;if(G==="self"){let K=typeof this.mode=="string"?{...E.AGENT_MODE,name:this.mode}:this.mode,ve=x.systemPrompt(O);W={...K,name:`${K.name}-replica-${Date.now()}`,systemPrompt:(K.systemPrompt??"")+(ve?`
28
28
 
29
- ${Ae}`:"")+z},q=`${this.name}-replica`,j=this.description,B=this.model}else H={...N.AGENT_MODE,name:`ephemeral-${x.name}-${Date.now()}`,systemPrompt:x.systemPrompt(O)+z},q=x.name,j=x.description,B=x.model;let F=new $(q,j,H,{toolpack:this.toolpack});B&&(F.model=B),F.spawn={...w};let we=await F.invokeAgent({message:O,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:we.output,spawnedTemplate:G,depth:y+1,metadata:we.metadata}}))}}})}}let d={messages:u,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},l=null,m,g;if(typeof this.mode!="string"&&this.mode?.streaming){let y="";for await(let w of this.toolpack.stream(d,this.provider))y+=w.delta||"",w.usage&&(m=w.usage);l=y||null,g={content:l,usage:m}}else{let y=await this.toolpack.generate(d,this.provider);l=y.content??null,m=y.usage,g=y}let f={output:l||"",steps:this.extractSteps(g),metadata:m?{usage:m}:void 0};return await this.onComplete(f),s&&await s(!1),this.emit("agent:complete",f),f}catch(u){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(u),this.emit("agent:error",u),u}}getAgentAliases(){let e=[];for(let t of this.channels){let 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 E("Agent not registered - cannot use ask()");let i=this._ctx()?.conversationId??this._conversationId,n=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!i)throw new E("No conversationId available - ask() requires a conversation channel");if(n)throw new E("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!s||s.trim()==="")throw new E("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:i,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new E("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){if(i?.simpleValidation)return i.simpleValidation(t);let n=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
29
+ ${ve}`:"")+H},j=`${this.name}-replica`,F=this.description,D=this.model}else W={...E.AGENT_MODE,name:`ephemeral-${x.name}-${Date.now()}`,systemPrompt:x.systemPrompt(O)+H},j=x.name,F=x.description,D=x.model;let z=new N(j,F,W,{toolpack:this.toolpack});D&&(z.model=D),z.spawn={...A};let Ae=await z.invokeAgent({message:O,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:y+1}});return{output:Ae.output,spawnedTemplate:G,depth:y+1,metadata:Ae.metadata}}))}}})}}let p={messages:d,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode,signal:t?.signal},g=null,m,w;if(typeof this.mode!="string"&&this.mode?.streaming){let y="";for await(let A of this.toolpack.stream(p,this.provider))y+=A.delta||"",A.usage&&(m=A.usage);g=y||null,w={content:g,usage:m}}else{let y=await this.toolpack.generate(p,this.provider);g=y.content??null,m=y.usage,w=y}let T={output:g||"",steps:this.extractSteps(w),metadata:m?{usage:m}:void 0};return await this.onComplete(T),o&&await o(!1),this.emit("agent:complete",T),T}catch(d){throw o&&o(!0).catch(l=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,l)}),await this.onError(d),this.emit("agent:error",d),d}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new B("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,i=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new B("No conversationId available - ask() requires a conversation channel");if(i)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(!s||s.trim()==="")throw new B("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:n,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new B("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){if(n?.simpleValidation)return n.simpleValidation(t);let i=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
30
30
 
31
31
  Question: "${e}"
32
32
  Answer: "${t}"
33
33
 
34
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:n})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),i(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new E("Agent not registered - cannot use delegateAndWait()");let i={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,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[se]===!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);await this._channelCtx.run({conversationId:t.conversationId,triggeringChannel:e.name??"",isTriggerChannel:e.isTriggerChannel},async()=>{try{let n=Ie(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await Ce(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}}});var Mt={};te(Mt,{IntentClassifierAgent:()=>Z,SummarizerAgent:()=>ee});module.exports=et(Mt);h();h();Q();var We=require("toolpack-sdk"),_t={...We.CHAT_MODE,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
35
- `)},Z=class extends L{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=_t;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(`
36
- Recent conversation:`);for(let p of t.recentContext)i.push(` ${p.sender}: ${p.content.substring(0,100)}`)}i.push(`
37
- Message to classify: "${t.message}"`),t.includeExamples&&(i.push(`
38
- 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(`
39
- Classification (start with direct, indirect, passive, or ignore):`);let n=i.join(`
40
- `),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"}};h();Q();var Ke=require("toolpack-sdk"),St={...Ke.CHAT_MODE,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
41
- `)},ee=class extends L{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=St;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"}),l=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${l}`:l,g=`[${d}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(g+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(g+=` [tool: ${c.metadata.toolName}]`),s.push(g)}s.push("","Generate a JSON summary object:");let o=s.join(`
42
- `),p=await this.run(o),u=this.parseSummarizerOutput(p.output,t.turns.length);return{output:JSON.stringify(u),metadata:{turnsProcessed:t.turns.length,rawOutputLength:p.output.length}}}parseSummarizerOutput(e,t){let 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)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
34
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new B("Agent not registered - cannot use delegateAndWait()");let n={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,n)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(i=>i.botUserId).filter(i=>typeof i=="string"&&i.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let n=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[oe]===!0)?this.interceptors:[_e({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let n=await this._acquireConversationLock(t.conversationId);await this._channelCtx.run({conversationId:t.conversationId,triggeringChannel:e.name??"",isTriggerChannel:e.isTriggerChannel},async()=>{try{let i=Ce(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await xe(i,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(i){let s=i instanceof Error?i.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(i=>{t=i});return this._conversationLocks.set(e,n),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let n=t.plan;if(Array.isArray(n.steps))return n.steps.map(i=>({number:i.number||0,description:i.description||"",status:i.status||"completed",result:i.result}))}if(Array.isArray(t.steps))return t.steps}}});var Pt={};ne(Pt,{IntentClassifierAgent:()=>ee,SummarizerAgent:()=>te});module.exports=tt(Pt);h();h();Z();var Ke=require("toolpack-sdk"),St={...Ke.CHAT_MODE,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
35
+ `)},ee=class extends L{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=St;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let n=[];if(n.push(`Context: Public channel #${t.channelName}`),n.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),n.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){n.push(`
36
+ Recent conversation:`);for(let u of t.recentContext)n.push(` ${u.sender}: ${u.content.substring(0,100)}`)}n.push(`
37
+ Message to classify: "${t.message}"`),t.includeExamples&&(n.push(`
38
+ Examples of classifications:`),n.push(` "@${t.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
39
+ Classification (start with direct, indirect, passive, or ignore):`);let i=n.join(`
40
+ `),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:n.includes("indirect")||n.includes("mention")?"indirect":n.includes("passive")||n.includes("listen")?"passive":n.includes("ignore")||n.includes("skip")?"ignore":n.includes("direct")||n.includes("addressed")?"direct":"ignore"}};h();Z();var Ve=require("toolpack-sdk"),Mt={...Ve.CHAT_MODE,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
41
+ `)},te=class extends L{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=Mt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let n=t.maxTokens??800,i=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${i?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let l of t.turns){let c=new Date(l.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=l.participant.displayName??l.participant.id,g=l.participant.kind==="agent"?`[BOT] ${p}`:p,m=`[${c}] ${g}: ${l.content.substring(0,200)}`;l.content.length>200&&(m+="..."),l.metadata?.isToolCall&&l.metadata.toolName&&(m+=` [tool: ${l.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let o=s.join(`
42
+ `),u=await this.run(o),d=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(d),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),i=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);i&&(n=i[1].trim());try{let s=JSON.parse(n);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
@@ -1,6 +1,6 @@
1
- export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-CEmRGpUr.cjs';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-CJinv165.cjs';
3
- import { B as BaseAgent } from '../base-agent-iaQiO7jW.cjs';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-DRNbyZ5N.cjs';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-D5dxhUX8.cjs';
3
+ import { B as BaseAgent } from '../base-agent-C_h8KyH0.cjs';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';
@@ -1,6 +1,6 @@
1
- export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-QuB4WIWf.js';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-CJinv165.js';
3
- import { B as BaseAgent } from '../base-agent-CJE2QCjY.js';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-CZMHh1wf.js';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-D5dxhUX8.js';
3
+ import { B as BaseAgent } from '../base-agent-DIuUtRdS.js';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';