@toolpack-sdk/agents 3.4.0 → 3.6.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
@@ -385,7 +385,7 @@ class SupportAgent extends BaseAgent {
385
385
  - Auto-stores user and assistant messages via the capture interceptor
386
386
  - Auto-trims to `maxMessagesPerConversation` limit (default: 500)
387
387
  - Zero-config in-memory mode for development
388
- - `conversation_search` tool is automatically provided as a request-scoped tool whenever a `conversationId` is active
388
+ - `conversation_search` tool is automatically provided as a request-scoped tool whenever a `conversationId` is active. Set `conversationSearch = false` on the agent to leave it out (for example to give it your own search tool under the same name); the history still loads
389
389
 
390
390
  **Memory model:**
391
391
  Agent memory is per-conversation by default. The `conversation_search` tool is bound at invocation time to the current conversation — the LLM cannot override this scope, and turns from other conversations are structurally unreachable. Use `knowledge_add` to promote durable facts that should persist across conversations; knowledge is the only cross-conversation bridge.
@@ -596,10 +596,10 @@ const toolpack = await Toolpack.init({
596
596
 
597
597
  ## Peer Dependencies
598
598
 
599
- Requires `toolpack-sdk` (`^3.1.0`). Optional peers — install only what you need:
599
+ Requires `toolpack-sdk` (`^3.6.0`). Optional peers, install only what you need:
600
600
 
601
601
  ```bash
602
- # Knowledge / RAG (optional)
602
+ # Knowledge / RAG and Agent Mind (optional, ^3.6.0)
603
603
  npm install @toolpack-sdk/knowledge
604
604
 
605
605
  # For DiscordChannel
@@ -646,6 +646,36 @@ if (result.metadata?.mindSaveError) {
646
646
  }
647
647
  ```
648
648
 
649
+ #### Stopping or changing a tool call
650
+
651
+ `AgentRunOptions` accepts `interceptTool`, which wraps every tool call of that run (see `toolpack-sdk`). Call `run()` to run the tool, or return text without calling it to stop the call; the model sees that text as the tool's result. This is not the same as the [Interceptors](#interceptors) below, which handle incoming messages before `invokeAgent`.
652
+
653
+ ```typescript
654
+ const result = await this.run(input.message, {
655
+ interceptTool: async (call, run) => {
656
+ if (call.toolName.startsWith('fs.delete')) return 'Ask the user before deleting anything.';
657
+ return run();
658
+ },
659
+ });
660
+ ```
661
+
662
+ #### Agent Mind: what it remembers
663
+
664
+ Set `mind` on the agent to give it memory that lasts across runs. By default it keeps beliefs (facts), reflections and goals. Pass `kinds` to keep only some of them:
665
+
666
+ ```typescript
667
+ import { OllamaEmbedder } from '@toolpack-sdk/knowledge';
668
+
669
+ class FactsAgent extends BaseAgent {
670
+ mind = {
671
+ embedder: new OllamaEmbedder({ model: 'nomic-embed-text' }),
672
+ kinds: ['belief'], // facts only
673
+ };
674
+ }
675
+ ```
676
+
677
+ A kind that is left out is switched off: it is not in the mind header, its tools are not given to the agent, and `mind_recall` does not search it. `kinds` must name at least one of `'belief'`, `'reflection'` and `'goal'`.
678
+
649
679
  ### AgentRegistry
650
680
 
651
681
  ```typescript
@@ -1136,10 +1166,33 @@ const resultPromise = agent.invokeAgent({
1136
1166
  // Abort from wherever you need — HTTP stop endpoint, UI button, timeout, etc.
1137
1167
  controller.abort();
1138
1168
 
1139
- const result = await resultPromise;
1140
- // result.output will indicate the run was stopped
1169
+ const result = await resultPromise; // see "What the caller gets back" below
1170
+ ```
1171
+
1172
+ ### What the caller gets back
1173
+
1174
+ | Run | On a stop |
1175
+ |---|---|
1176
+ | Streaming (`onChunk` set, or the mode has `streaming`) | Resolves with the text that had arrived, and `result.metadata.aborted` is `true` |
1177
+ | Not streaming | Rejects with an error whose `name` is `'AbortError'` |
1178
+
1179
+ ```typescript
1180
+ try {
1181
+ const result = await agent.invokeAgent({ message, signal: controller.signal, onChunk });
1182
+ if (result.metadata?.aborted) {
1183
+ // stopped while streaming: result.output is the part that arrived
1184
+ }
1185
+ } catch (err) {
1186
+ if ((err as Error).name === 'AbortError') {
1187
+ // stopped while not streaming
1188
+ } else {
1189
+ throw err;
1190
+ }
1191
+ }
1141
1192
  ```
1142
1193
 
1194
+ A stopped streaming run is saved to the agent's mind like a failed one: what it learned is kept, its goal writes are dropped.
1195
+
1143
1196
  ### In a web server (stop endpoint)
1144
1197
 
1145
1198
  ```typescript
@@ -1177,9 +1230,9 @@ await executiveAgent.invokeAgent({ message: '...', signal: controller.signal });
1177
1230
  controller.abort(); // stops executive + all delegates it spawned
1178
1231
  ```
1179
1232
 
1180
- ### Limitation
1233
+ ### Timing
1181
1234
 
1182
- The signal fires at **tool-round boundaries**, not mid-tool-execution. A running tool call (including a delegation) finishes its current step before the abort is observed. Sub-agents stop at their own next round boundary once the signal is propagated. This is the standard behavior for cooperative cancellation with `AbortSignal`.
1235
+ A stop takes effect at once: in the middle of a model call, a rate limit wait, or a tool. Tools that have not started are not run. A tool that is already running is no longer waited for, but its own work only ends early if it reads `ctx.signal`; otherwise it finishes in the background and its result is ignored. Sub-agents receive the same signal and stop the same way.
1183
1236
 
1184
1237
  ## Testing
1185
1238
 
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
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-BZ4tAT_N.js';
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-C_2Rkpio.js';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -77,6 +77,11 @@ interface AgentMindConfig {
77
77
  deduplicationThreshold?: number;
78
78
  retrievalThreshold?: number;
79
79
  ttlDefaults?: MindTtlDefaults;
80
+ /**
81
+ * Which kinds of entry this agent remembers. Default: all three. With only `['belief']` the agent remembers facts and nothing else: the mind
82
+ * header has no goals and no reflections, there are no goal or reflection tools, and `mind_recall` searches beliefs only.
83
+ */
84
+ kinds?: MindEntryType[];
80
85
  }
81
86
 
82
87
  /**
@@ -110,6 +115,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
110
115
  * Set to undefined (default) to opt out — zero cost when not configured.
111
116
  */
112
117
  mind?: AgentMindConfig;
118
+ /**
119
+ * Adds the built-in `conversation_search` tool to every run that has a conversation. Set to false to leave it out, for
120
+ * example to give the agent your own search tool under the same name. Default true.
121
+ */
122
+ conversationSearch: boolean;
113
123
  /**
114
124
  * AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
115
125
  * injected into every run() call so the LLM can hand tasks to peer agents.
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
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-BZ4tAT_N.cjs';
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-C_2Rkpio.cjs';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -77,6 +77,11 @@ interface AgentMindConfig {
77
77
  deduplicationThreshold?: number;
78
78
  retrievalThreshold?: number;
79
79
  ttlDefaults?: MindTtlDefaults;
80
+ /**
81
+ * Which kinds of entry this agent remembers. Default: all three. With only `['belief']` the agent remembers facts and nothing else: the mind
82
+ * header has no goals and no reflections, there are no goal or reflection tools, and `mind_recall` searches beliefs only.
83
+ */
84
+ kinds?: MindEntryType[];
80
85
  }
81
86
 
82
87
  /**
@@ -110,6 +115,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
110
115
  * Set to undefined (default) to opt out — zero cost when not configured.
111
116
  */
112
117
  mind?: AgentMindConfig;
118
+ /**
119
+ * Adds the built-in `conversation_search` tool to every run that has a conversation. Set to false to leave it out, for
120
+ * example to give the agent your own search tool under the same name. Default true.
121
+ */
122
+ conversationSearch: boolean;
113
123
  /**
114
124
  * AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
115
125
  * injected into every run() call so the LLM can hand tasks to peer agents.
@@ -1,42 +1,42 @@
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 y=M(()=>{"use strict"});function be(r){return r===J}function Ie(){return J}var J,ie=M(()=>{"use strict";y();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 A=n.getAgent(p);if(!A)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 A.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";y();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(A){u.logger?.warn("[capture-history] Failed to store agent reply",{error:A instanceof Error?A.message:String(A)})}}return p};return s[oe]=!0,s}var se,oe,Se=M(()=>{"use strict";y();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 Pe(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??[]]),A=c!==void 0?new Date(Date.now()-c*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:A,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 h=!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,Te.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],h=!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 w=f.map(v=>rt(v,t));if(w.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:T,hasSummary:h};let C=w[w.length-1],R=[C],b=Me(C.content);for(let v=w.length-2;v>=0;v--){let _=w[v],I=Me(_.content);if(b+I>d)break;R.unshift(_),b+=I}return{messages:R,estimatedTokens:b,turnsLoaded:T,hasSummary:h}}var Te,De=M(()=>{"use strict";y();Te=require("crypto")});var B,Be=M(()=>{"use strict";y();B=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var Y,ae,ce,de,le,pe,a,X,Ee=M(()=>{"use strict";y();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),A=p.error?.3:le[p.confidence],f=c.score*ae+m*ce+A*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,A=Math.exp(-m/pe),f=p.score*ae+A*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";y()});var Ge,Q,Oe=M(()=>{"use strict";y();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},A=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g];return this.ops[o]={...c,content:e.content,confidence:A?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},A=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g],f={op:"believe",content:e.content,confidence:A?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 A=await r.keywordSearchGoals(n,{limit:c,status:s,tags:o});for(let f of A)p.push(mt(f))}if(m&&(i==="belief"||i==="all")){let A=await r.queryBeliefs(m,{limit:c,threshold:l,tags:o,includeExpired:d});for(let f of A)p.push(gt(f))}if(m&&(i==="reflection"||i==="all")){let A=await r.queryReflections(m,{limit:c,threshold:l,tags:o,pinned:u});for(let f of A)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";y()});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";y();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";y();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";y();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";y();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 h=await Pe(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),w=h.messages[h.messages.length-1],C=e.trim(),b=C!==""&&w?.role==="user"&&typeof w.content=="string"&&(w.content===C||w.content.endsWith(`: ${C}`))?h.messages.slice(0,-1):h.messages;d.push(...b)}catch{}let l=i&&i.length>0;if(e.trim()||l)if(l){let h=[...e.trim()?[{type:"text",text:e}]:[],...i];d.push({role:"user",content:h})}else d.push({role:"user",content:e});let c=[];if(s){let h=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 C=await h.search(s,String(w.query??""),{limit:typeof w.limit=="number"?w.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 h=this.delegation.allowedAgents,w=this._registry.getAllAgents().filter(C=>C.name!==this.name&&(h===void 0||h.includes(C.name)));if(w.length>0){let C=w.map(b=>b.name),R=w.map(b=>`- ${b.name}: ${b.description}`).join(`
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.
1
+ "use strict";var Xe=Object.create;var J=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var ie=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},be=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ze(e))!tt.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=Qe(e,i))||n.enumerable});return r};var nt=(r,e,t)=>(t=r!=null?Xe(et(r)):{},be(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r)),it=r=>be(J({},"__esModule",{value:!0}),r);var y=_(()=>{"use strict"});function Ie(r){return r===Y}function Ce(){return Y}var Y,re=_(()=>{"use strict";y();Y=Symbol("interceptor-skip-sentinel")});function xe(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let c=(m=>({agent:e,channel:t,registry:n,invocationDepth:m,delegateAndWait:async(u,g)=>{let d=m+1;if(d>s)throw new se(d,s);if(!n)throw new Error(`Cannot delegate to "${u}": agent is running in standalone mode without a registry`);let w=n.getAgent(u);if(!w)throw new Error(`Agent "${u}" 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:Ce}))(0),l=async m=>{let u=m??o;return await e.invokeAgent(u)};for(let m=r.length-1;m>=0;m--){let u=r[m],g=l;l=async d=>await u(d??o,c,g)}return await l()}}}async function Re(r,e){let t=await r.execute(e);return t===Y?null:t}var se,Se=_(()=>{"use strict";y();re();se=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function rt(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??rt,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,oe.randomUUID)()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,p,c)=>{let l=o.conversationId;if(!l)return p.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await c();let m=o.participant;if(m){let g={id:n(o),conversationId:l,participant:m,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),p.logger?.debug("[capture-history] Captured inbound message",{messageId:g.id,participantId:m.id,conversationId:l})}catch(d){p.logger?.warn("[capture-history] Failed to store inbound message",{error:d instanceof Error?d.message:String(d)})}}let u=await c();if(e&&!Ie(u)&&u.output!=null){let g={kind:"agent",id:p.agent.name,displayName:p.agent.name},d={id:(0,oe.randomUUID)(),conversationId:l,participant:g,content:u.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(d),r.onCaptured?.(d),p.logger?.debug("[capture-history] Captured agent reply",{messageId:d.id,agentId:p.agent.name,conversationId:l})}catch(w){p.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return u};return s[ae]=!0,s}var oe,ae,Me=_(()=>{"use strict";y();oe=require("crypto");re();ae=Symbol.for("toolpack:capture-history")});function Te(r){return Math.ceil(r.length/4)}function st(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function ot(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 at(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function De(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:p=!0,tokenBudget:c=3e3,rollingSummaryThreshold:l=40,timeWindowMinutes:m,maxTurnsToLoad:u=100,agentAliases:g}=i,d=new Set([t,...g??[]]),w=m!==void 0?new Date(Date.now()-m*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:w,limit:u}),M=f.length;if(p){let A=new Set;for(let I=0;I<f.length;I++){let T=f[I];if(at(T,t,d)&&A.add(T.id),I<f.length-1){let $=f[I+1];$.participant.kind==="agent"&&$.participant.id===t&&A.add(T.id)}}let b=f[f.length-1];b&&A.add(b.id),f=f.filter(I=>A.has(I.id))}let P=!1;if(f.length>l&&s){let A=Math.floor(f.length/2),b=f.slice(0,A),I=f.slice(A),T=b.filter($=>!$.metadata?.isSummary);try{let $=await s.invokeAgent({message:"summarize",data:{turns:T.map(st),agentName:n,agentId:t,maxTokens:Math.floor(c*.25),extractDecisions:!0}}),C=JSON.parse($.output),D={id:`summary-${(0,Pe.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${C.turnsSummarized} earlier turns]: ${C.summary}`,timestamp:b[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[D,...I],P=!0;try{await r.append(D),await r.deleteMessages(e,b.map(j=>j.id))}catch{}}catch{f=f.slice(-l)}}else f.length>l&&(f=f.slice(-l));let h=f.map(A=>ot(A,t));if(h.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:M,hasSummary:P};let v=h[h.length-1],k=[v],x=Te(v.content);for(let A=h.length-2;A>=0;A--){let b=h[A],I=Te(b.content);if(x+I>c)break;k.unshift(b),x+=I}return{messages:k,estimatedTokens:x,turnsLoaded:M,hasSummary:P}}var Pe,Be=_(()=>{"use strict";y();Pe=require("crypto")});var E,Ee=_(()=>{"use strict";y();E=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var X,ce,de,le,pe,ue,a,Q,Ne=_(()=>{"use strict";y();X=require("crypto"),ce=.6,de=.2,le=.2,pe={low:.3,medium:.6,high:1},ue=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"},Q=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,c=Math.exp(-o/ue)*de+pe.high*le+ce;return{...s,score:c}}).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(c=>this.chunkToGoal(c.chunk));else{let p=i;if(o=(await this._getAllByMeta(l=>l[a.type]==="goal"&&l[a.status]===p)).map(l=>this.chunkToGoal(l)),e.trim()){let l=e.toLowerCase();o=o.filter(m=>m.description.toLowerCase().includes(l))}}return s?.length&&(o=o.filter(p=>s.every(c=>p.tags.includes(c)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,p=Date.now(),c=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),l=[];for(let m of c){let u=this.chunkToBelief(m.chunk);if(!o&&u.expiresAt&&u.expiresAt<p||s?.length&&!s.every(M=>u.tags.includes(M)))continue;let g=(p-u.createdAt)/864e5,d=Math.exp(-g/ue),w=u.error?.3:pe[u.confidence],f=m.score*ce+d*de+w*le;f<i||l.push({...u,score:f})}return l.sort((m,u)=>u.score-m.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,p=Date.now(),c={[a.type]:"reflection"};o===!0&&(c[a.pinned]=!0);let l=await this.provider.query(e,{limit:n*4,threshold:0,filter:c}),m=[];for(let u of l){let g=this.chunkToReflection(u.chunk);if(o===!1&&g.pinned||s?.length&&!s.every(M=>g.tags.includes(M)))continue;let d=(p-g.createdAt)/864e5,w=Math.exp(-d/ue),f=u.score*ce+w*de+pe.medium*le;f<i||m.push({...g,score:f})}return m.sort((u,g)=>g.score-u.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,X.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,X.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()},p=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,p)])}async addReflection(e,t){let n=(0,X.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 me(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 $e(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=me(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ge(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 ge(r){return Math.ceil(r.length/4)}var fe=_(()=>{"use strict";y()});var Oe,Z,Le=_(()=>{"use strict";y();Oe=require("crypto");fe();Z=class{constructor(e,t,n,i,s,o,p){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=p}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+me(s));let o=this._findSimilarInDraft(n);if(o!==null){let m=this.ops[o],u=e.confidence,g=m.confidence,d={low:0,medium:1,high:2},w=d[u]>d[g]||e.allowDowngrade&&d[u]<d[g];return this.ops[o]={...m,content:e.content,confidence:w?u:g,tags:e.tags.length>0?e.tags:m.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:m.existingId??`draft-${o}`}}let p=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(p))return{action:"updated_draft",id:"in-flight-dedup"};let c=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(c){let m=c.belief,u=e.confidence,g=m.confidence,d={low:0,medium:1,high:2},w=d[u]>d[g]||e.allowDowngrade&&d[u]<d[g],f={op:"believe",content:e.content,confidence:w?u:g,tags:e.tags.length>0?e.tags:m.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:c.id};return this.ops.push(f),{action:"updated_store",id:c.id}}this.inFlightBeliefs.add(p);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?$e(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Oe.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(Ge(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function Ue(r,e,t){let n=t.kinds.includes("reflection"),i=t.kinds.includes("goal");return[ct(r,t),...t.kinds.includes("belief")?[dt(r,e,t)]:[],...n?[lt(e,t),pt(e)]:[],...i?[ut(e,t),mt(r,e),gt(r)]:[]]}function ct(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:[...e.kinds,"all"],description:e.kinds.length===3?"Entry type to search. Default: 'all'":`Entry type to search: ${e.kinds.join(", ")}. Default: 'all' (${e.kinds.join(" and ")}).`},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=f=>e.kinds.includes(f)&&(i===f||i==="all"),o=t.status??"active",p=Array.isArray(t.tags)?t.tags.map(String):void 0,c=typeof t.pinned=="boolean"?t.pinned:void 0,l=t.includeExpired===!0,m=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,u=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,g=[],w=(s("belief")||s("reflection"))&&n.trim()?await r.embed(n):null;if(s("goal")){let f=await r.keywordSearchGoals(n,{limit:u,status:o,tags:p});for(let M of f)g.push(ft(M))}if(w&&s("belief")){let f=await r.queryBeliefs(w,{limit:u,threshold:m,tags:p,includeExpired:l});for(let M of f)g.push(ht(M))}if(w&&s("reflection")){let f=await r.queryReflections(w,{limit:u,threshold:m,tags:p,pinned:c});for(let M of f)g.push(yt(M))}return g}}}function dt(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 lt(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 pt(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 ut(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 mt(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 gt(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 ft(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 ht(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 yt(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 je=_(()=>{"use strict";y()});async function qe(r,e){let t=e.kinds.includes("goal"),n=e.kinds.includes("reflection"),i=e.kinds.includes("belief"),[s,o,p,c]=await Promise.all([t?r.getActiveGoals():Promise.resolve([]),n?r.getPinnedReflections():Promise.resolve([]),i?r.getHighConfidenceBeliefs(20):Promise.resolve([]),n?r.getRecentReflections(e.recencyWindowDays,3):Promise.resolve([])]),l=s.map(w=>wt(w)),m=o.map(w=>`- ${w.content}`),{beliefLines:u,reflectionLines:g}=At(p,c,e.tokenBudget);if(l.length===0&&m.length===0&&u.length===0&&g.length===0)return"";let d=["--- AGENT MIND ---",""];return l.length>0&&(d.push("## Goals"),d.push(...l),d.push("")),m.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...m),d.push("")),u.length>0&&(d.push("## Beliefs"),d.push(...u),d.push("")),g.length>0&&(d.push("## Recent Reflections"),d.push(...g),d.push("")),d.push("---"),d.join(`
2
+ `)}function wt(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 At(r,e,t){let n=t,i=[],s=[];for(let o of r){let p=`- ${o.content} (${o.confidence} confidence)`,c=ge(p);if(c>n)break;i.push(p),n-=c}for(let o of e){let c=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,l=ge(c);if(l>n)break;s.push(c),n-=l}return{beliefLines:i,reflectionLines:s}}var Fe=_(()=>{"use strict";y();fe()});var He={};ie(He,{AgentMind:()=>he});function Mt(r,e){let t=Math.min(e.maxGoals??bt,St),n=Math.min(e.maxPinnedReflections??It,_t);return{tokenBudget:e.tokenBudget??vt,recencyWindowDays:e.recencyWindowDays??kt,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??Ct,retrievalThreshold:e.retrievalThreshold??xt,ttlDefaults:{belief:e.ttlDefaults?.belief??Rt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`,kinds:Tt(e.kinds)}}function Tt(r){if(r===void 0)return[...ze];let e=ze.filter(t=>r.includes(t));if(e.length===0)throw new Error("AgentMindConfig.kinds must name at least one of belief, reflection and goal.");return e}var vt,kt,bt,It,Ct,xt,Rt,St,_t,he,ze,We=_(()=>{"use strict";y();Ne();Le();je();Fe();vt=300,kt=7,bt=10,It=10,Ct=.85,xt=.35,Rt="30d",St=10,_t=10,he=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let n;if(t.provider)n=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),p=t.namespace??`mind/${e}`;n=new o({namespace:p})}let i=Mt(e,t),s=new Q(n,t.embedder);return await s.initialize(),new r(s,i)}async createRunContext(){let[e,t,n]=await Promise.all([this.config.kinds.includes("goal")?this.store.getActiveGoalCount():Promise.resolve(0),this.config.kinds.includes("reflection")?this.store.getPinnedReflectionCount():Promise.resolve(0),qe(this.store,this.config)]),i=new Z(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Ue(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(c=>c.name)},tools:s};return{mindHeader:n,toolProject:o,flush:async c=>{c?await i.flushOnError():await i.flushClean()}}}async close(){this.store&&await Promise.resolve()}};ze=["belief","reflection","goal"]});var we={};ie(we,{EphemeralAgent:()=>ye});var ye,Ae=_(()=>{"use strict";y();ee();ye=class extends U{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 Ke,Ve,N,U,ee=_(()=>{"use strict";y();Ke=require("events"),Ve=require("async_hooks"),N=require("toolpack-sdk");Se();Me();Be();Ee();U=class extends Ke.EventEmitter{provider;model;workflow;mind;conversationSearch=!0;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new Ve.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(()=>(We(),He));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,p="";if(this._mind){let c=await this._mind.createRunContext();p=c.mindHeader,o=c.flush,this.toolpack.loadRequestToolProject(c.toolProject)}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let c=[];if(p&&c.push({role:"system",content:p}),s)try{let h=await De(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),v=h.messages[h.messages.length-1],k=e.trim(),A=k!==""&&v?.role==="user"&&typeof v.content=="string"&&(v.content===k||v.content.endsWith(`: ${k}`))?h.messages.slice(0,-1):h.messages;c.push(...A)}catch{}let l=i&&i.length>0;if(e.trim()||l)if(l){let h=[...e.trim()?[{type:"text",text:e}]:[],...i];c.push({role:"user",content:h})}else c.push({role:"user",content:e});let m=[];if(s&&this.conversationSearch){let h=this.conversationHistory;m.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 v=>{let k=await h.search(s,String(v.query??""),{limit:typeof v.limit=="number"?v.limit:5});return{results:k.map(x=>({role:x.participant.kind==="agent"?"assistant":"user",content:x.content,timestamp:x.timestamp})),count:k.length}}})}if(this.delegation?.enabled&&this._registry){let h=this.delegation.allowedAgents,v=this._registry.getAllAgents().filter(k=>k.name!==this.name&&(h===void 0||h.includes(k.name)));if(v.length>0){let k=v.map(A=>A.name),x=v.map(A=>`- ${A.name}: ${A.description}`).join(`
3
+ `);this.delegation.mode==="forget"?m.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: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.
6
+ ${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async A=>{let b=String(A.agent),I=String(A.message??"");return this._registry.invoke(b,{message:I,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal}).catch(T=>{console.error(`[${this.name}] delegate_and_forget to ${b} failed:`,T)}),{status:"delegated",agent:b}}}):m.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: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]
9
+ ${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async A=>{let b=String(A.agent),I=String(A.message??""),T=await this._registry.invoke(b,{message:I,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal});return{...T,output:`[Response from ${b} \u2014 task complete]
10
10
 
11
- ${I.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let h=n?.spawnDepth??0,w=this.spawn,C=w.maxDepth??3;if(h<C){let R=w.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.
11
+ ${T.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let h=n?.spawnDepth??0,v=this.spawn,k=v.maxDepth??3;if(h<k){let x=v.templates,A=x.some(C=>C.name==="self"),b=x.some(C=>C.allowPromptAddition),I=x.filter(C=>C.name!=="self").map(C=>`- ${C.name}: ${C.description}`).join(`
12
+ `),T=A?`Use template name "self" to spawn a replica of the current agent.
13
+ `:"",$=b?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};m.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
- ${_}
17
- `+I+`Spawn depth: ${h}/${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?`
16
+ ${I}
17
+ `+T+`Spawn depth: ${h}/${k}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:A?'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."},...$},required:["template","task"]},execute:async C=>{let D=String(C.template),j=String(C.task??""),V,G,O,L,R=x.find(B=>B.name===D);if(!R)throw new Error(`Unknown spawn template: "${D}"`);let H=R.allowPromptAddition&&C.systemPromptAddition?`
18
18
 
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?`
19
+ ${String(C.systemPromptAddition)}`:"";if(D==="self"){let B=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,z=R.systemPrompt(j);V={...B,name:`${B.name}-replica-${Date.now()}`,systemPrompt:(B.systemPrompt??"")+(z?`
20
20
 
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={...w};let F=await j.invokeAgent({message:N,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:F.output,spawnedTemplate:P,depth:h+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.
21
+ ${z}`:"")+H},G=`${this.name}-replica`,O=this.description,L=this.model}else V={...N.AGENT_MODE,name:`ephemeral-${R.name}-${Date.now()}`,systemPrompt:R.systemPrompt(j)+H},G=R.name,O=R.description,L=R.model;let{EphemeralAgent:W}=await Promise.resolve().then(()=>(Ae(),we)),q=new W(G,O,V,{toolpack:this.toolpack});L&&(q.model=L),q.spawn={...v};let F=await q.invokeAgent({message:j,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:F.output,spawnedTemplate:D,depth:h+1,metadata:F.metadata}}}),m.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
- ${_}
25
- `+I+`Spawn depth: ${h}/${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?`
24
+ ${I}
25
+ `+T+`Spawn depth: ${h}/${k}`,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:A?'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."},...b?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async C=>{let D=C.tasks;if(!Array.isArray(D)||D.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:j}=await Promise.resolve().then(()=>(Ae(),we));return{results:await Promise.all(D.map(async G=>{let O=String(G.template),L=String(G.task??""),R=x.find(K=>K.name===O);if(!R)throw new Error(`Unknown spawn template: "${O}"`);let H=R.allowPromptAddition&&G.systemPromptAddition?`
26
26
 
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?`
27
+ ${String(G.systemPromptAddition)}`:"",W,q,F,B;if(O==="self"){let K=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,ke=R.systemPrompt(L);W={...K,name:`${K.name}-replica-${Date.now()}`,systemPrompt:(K.systemPrompt??"")+(ke?`
28
28
 
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={...w};let Ae=await z.invokeAgent({message:O,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:Ae.output,spawnedTemplate:G,depth:h+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,...t?.maxTokens?{max_tokens:t.maxTokens}:{}},g=null,m,A;if(typeof this.mode!="string"&&this.mode?.streaming||!!t?.onChunk){let h="";for await(let w of this.toolpack.stream(p,this.provider))w.delta&&(h+=w.delta,t?.onChunk?.(w.delta)),w.usage&&(m=w.usage);g=h||null,A={content:g,usage:m}}else{let h=await this.toolpack.generate(p,this.provider);g=h.content??null,m=h.usage,A=h}let T={output:g||"",steps:this.extractSteps(A),metadata:m?{usage:m}:void 0};if(await this.onComplete(T),o)try{await o(!1)}catch(h){console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush failed; the reply is kept:`,h),T.metadata={...T.metadata,mindSaveError:h instanceof Error?h.message:String(h)}}return 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.
29
+ ${ke}`:"")+H},q=`${this.name}-replica`,F=this.description,B=this.model}else W={...N.AGENT_MODE,name:`ephemeral-${R.name}-${Date.now()}`,systemPrompt:R.systemPrompt(L)+H},q=R.name,F=R.description,B=R.model;let z=new j(q,F,W,{toolpack:this.toolpack});B&&(z.model=B),z.spawn={...v};let ve=await z.invokeAgent({message:L,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:ve.output,spawnedTemplate:O,depth:h+1,metadata:ve.metadata}}))}}})}}let u={messages:c,model:this.model||"",requestTools:m.length>0?m:void 0,maxToolRounds:t?.maxToolRounds,...t?.interceptTool?{interceptTool:t.interceptTool}:{},mode:this.mode,signal:t?.signal,...t?.maxTokens?{max_tokens:t.maxTokens}:{}},g=null,d,w,f=!1;if(typeof this.mode!="string"&&this.mode?.streaming||!!t?.onChunk){let h="";for await(let v of this.toolpack.stream(u,this.provider))v.delta&&(h+=v.delta,t?.onChunk?.(v.delta)),v.usage&&(d=v.usage),v.finish_reason==="aborted"&&(f=!0);g=h||null,w={content:g,usage:d}}else{let h=await this.toolpack.generate(u,this.provider);g=h.content??null,d=h.usage,w=h}let P={output:g||"",steps:this.extractSteps(w),metadata:d?{usage:d}:void 0};if(f&&(P.metadata={...P.metadata,aborted:!0}),await this.onComplete(P),o)try{await o(f)}catch(h){console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush failed; the reply is kept:`,h),P.metadata={...P.metadata,mindSaveError:h instanceof Error?h.message:String(h)}}return this.emit("agent:complete",P),P}catch(c){throw o&&o(!0).catch(l=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,l)}),await this.onError(c),this.emit("agent:error",c),c}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new E("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,i=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new E("No conversationId available - ask() requires a conversation channel");if(i)throw new E("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!s||s.trim()==="")throw new E("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:n,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new E("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){if(n?.simpleValidation)return n.simpleValidation(t);let i=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
30
30
 
31
31
  Question: "${e}"
32
32
  Answer: "${t}"
33
33
 
34
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new 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 Tt={};ne(Tt,{IntentClassifierAgent:()=>ee,SummarizerAgent:()=>te});module.exports=tt(Tt);y();y();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(`
34
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new E("Agent not registered - cannot use delegateAndWait()");let n={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,n)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(i=>i.botUserId).filter(i=>typeof i=="string"&&i.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let n=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[ae]===!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=xe(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await Re(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 Bt={};ie(Bt,{IntentClassifierAgent:()=>te,SummarizerAgent:()=>ne});module.exports=it(Bt);y();y();ee();var Je=require("toolpack-sdk"),Pt={...Je.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
+ `)},te=class extends U{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=Pt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let n=[];if(n.push(`Context: Public channel #${t.channelName}`),n.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),n.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){n.push(`
36
+ Recent conversation:`);for(let p of t.recentContext)n.push(` ${p.sender}: ${p.content.substring(0,100)}`)}n.push(`
37
37
  Message to classify: "${t.message}"`),t.includeExamples&&(n.push(`
38
38
  Examples of classifications:`),n.push(` "@${t.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
39
39
  Classification (start with direct, indirect, passive, or ignore):`);let i=n.join(`
40
- `),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:n.includes("indirect")||n.includes("mention")?"indirect":n.includes("passive")||n.includes("listen")?"passive":n.includes("ignore")||n.includes("skip")?"ignore":n.includes("direct")||n.includes("addressed")?"direct":"ignore"}};y();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});
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"}};y();ee();var Ye=require("toolpack-sdk"),Dt={...Ye.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
+ `)},ne=class extends U{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=Dt;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 m=new Date(l.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=l.participant.displayName??l.participant.id,g=l.participant.kind==="agent"?`[BOT] ${u}`:u,d=`[${m}] ${g}: ${l.content.substring(0,200)}`;l.content.length>200&&(d+="..."),l.metadata?.isToolCall&&l.metadata.toolName&&(d+=` [tool: ${l.metadata.toolName}]`),s.push(d)}s.push("","Generate a JSON summary object:");let o=s.join(`
42
+ `),p=await this.run(o),c=this.parseSummarizerOutput(p.output,t.turns.length);return{output:JSON.stringify(c),metadata:{turnsProcessed:t.turns.length,rawOutputLength:p.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),i=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);i&&(n=i[1].trim());try{let s=JSON.parse(n);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
@@ -1,6 +1,6 @@
1
- export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-BugOILjt.cjs';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-BZ4tAT_N.cjs';
3
- import { B as BaseAgent } from '../base-agent-CxH_1lRG.cjs';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-A4thJQ0z.cjs';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C_2Rkpio.cjs';
3
+ import { B as BaseAgent } from '../base-agent-YX0G2Ur3.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-aHbGLRct.js';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-BZ4tAT_N.js';
3
- import { B as BaseAgent } from '../base-agent-BC0ipegO.js';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-DXlxbZ_r.js';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C_2Rkpio.js';
3
+ import { B as BaseAgent } from '../base-agent-5Dbq8iQi.js';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';