@toolpack-sdk/agents 2.0.0-alpha.1 → 2.0.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
@@ -171,17 +171,23 @@ const webhook = new WebhookChannel({
171
171
 
172
172
  ### ScheduledChannel (Trigger-only)
173
173
 
174
- Runs agents on cron schedules. Supports full cron expressions.
174
+ Runs agents on cron schedules. Three modes: static cron, dynamic store (agent-driven), or hybrid.
175
175
 
176
176
  ```typescript
177
+ // Static — fixed cron schedule
177
178
  const scheduler = new ScheduledChannel({
178
179
  name: 'daily-report',
179
180
  cron: '0 9 * * 1-5', // 9am weekdays
180
- notify: 'webhook:https://hooks.example.com/daily-report',
181
181
  message: 'Generate daily report',
182
182
  });
183
+
184
+ // Dynamic — agent schedules its own jobs via scheduler.* tools
185
+ import { SchedulerStore, createSchedulerTools } from '@toolpack-sdk/agents';
186
+ const store = new SchedulerStore({ dbPath: './scheduler.db' });
187
+ const dynamic = new ScheduledChannel({ name: 'dynamic', store });
188
+
183
189
  // For Slack delivery, attach a named SlackChannel to the same agent and
184
- // call `this.sendTo('<slackChannelName>', output)` from within `run()`.
190
+ // call `this.sendTo('<slackChannelName>', output)` from within `invokeAgent()`.
185
191
  ```
186
192
 
187
193
  ### DiscordChannel (Two-way)
@@ -1,6 +1,83 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack } from 'toolpack-sdk';
3
- import { A as AgentInput, W as WorkflowStep, a as AgentResult, C as ChannelInterface, I as Interceptor, b as IAgentRegistry, B as BaseAgentOptions, c as AgentRunOptions, P as PendingAsk } from './types-BWoRx1ZE.js';
3
+ import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, C as ChannelInterface, I as Interceptor, c as IAgentRegistry, B as BaseAgentOptions, d as AgentRunOptions, P as PendingAsk } from './types-TB6yypig.cjs';
4
+ import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
+
6
+ type GoalStatus = 'active' | 'completed';
7
+ type GoalPriority = 'low' | 'normal' | 'high';
8
+ type ConfidenceLevel = 'low' | 'medium' | 'high';
9
+ type MindEntryType = 'goal' | 'belief' | 'reflection';
10
+ interface MindGoal {
11
+ id: string;
12
+ type: 'goal';
13
+ description: string;
14
+ priority: GoalPriority;
15
+ status: GoalStatus;
16
+ tags: string[];
17
+ dueBy?: string;
18
+ progress: string[];
19
+ outcome?: string;
20
+ createdAt: number;
21
+ updatedAt: number;
22
+ }
23
+ interface MindBelief {
24
+ id: string;
25
+ type: 'belief';
26
+ content: string;
27
+ confidence: ConfidenceLevel;
28
+ tags: string[];
29
+ expiresAt?: number;
30
+ createdAt: number;
31
+ updatedAt: number;
32
+ error?: boolean;
33
+ }
34
+ interface MindReflection {
35
+ id: string;
36
+ type: 'reflection';
37
+ content: string;
38
+ pinned: boolean;
39
+ tags: string[];
40
+ relatedTo?: string;
41
+ createdAt: number;
42
+ updatedAt: number;
43
+ error?: boolean;
44
+ }
45
+ type MindEntry = MindGoal | MindBelief | MindReflection;
46
+ interface MindRecallResult {
47
+ id: string;
48
+ type: MindEntryType;
49
+ content: string;
50
+ score?: number;
51
+ tags: string[];
52
+ createdAt: number;
53
+ updatedAt: number;
54
+ priority?: GoalPriority;
55
+ status?: GoalStatus;
56
+ progress?: string[];
57
+ outcome?: string;
58
+ dueBy?: string;
59
+ confidence?: ConfidenceLevel;
60
+ expiresAt?: number;
61
+ pinned?: boolean;
62
+ relatedTo?: string;
63
+ error?: boolean;
64
+ }
65
+ interface MindTtlDefaults {
66
+ belief?: string;
67
+ reflection?: string;
68
+ }
69
+ interface AgentMindConfig {
70
+ embedder: Embedder;
71
+ provider?: KnowledgeProvider;
72
+ namespace?: string;
73
+ tokenBudget?: number;
74
+ recencyWindowDays?: number;
75
+ maxGoals?: number;
76
+ maxPinnedReflections?: number;
77
+ deduplicationThreshold?: number;
78
+ retrievalThreshold?: number;
79
+ ttlDefaults?: MindTtlDefaults;
80
+ }
4
81
 
5
82
  /**
6
83
  * Abstract base class for all agents.
@@ -27,6 +104,19 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
27
104
  model?: string;
28
105
  /** Workflow configuration merged on top of mode config */
29
106
  workflow?: Record<string, unknown>;
107
+ /**
108
+ * Persistent cognitive layer. When set, the agent gains goals, beliefs, and
109
+ * reflections that survive across runs. Requires @toolpack-sdk/knowledge.
110
+ * Set to undefined (default) to opt out — zero cost when not configured.
111
+ */
112
+ mind?: AgentMindConfig;
113
+ /**
114
+ * AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
115
+ * injected into every run() call so the LLM can hand tasks to peer agents.
116
+ * Only active when the agent is registered in an AgentRegistry with peers.
117
+ * Set to undefined (default) to opt out — zero cost when not configured.
118
+ */
119
+ delegation?: AgentDelegationConfig;
30
120
  /**
31
121
  * Conversation history store. Auto-initialised to `InMemoryConversationStore` in the
32
122
  * constructor so subclass field initialisers (e.g. `interceptors = [createCaptureInterceptor({
@@ -65,6 +155,8 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
65
155
  private readonly _initConfig?;
66
156
  private _ownedToolpack;
67
157
  private readonly _conversationLocks;
158
+ private _mind?;
159
+ private _mindInitPromise?;
68
160
  constructor(options: BaseAgentOptions);
69
161
  /**
70
162
  * Ensure the Toolpack instance is ready.
@@ -72,6 +164,12 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
72
164
  * Creates and owns the instance from `apiKey` if it was not.
73
165
  */
74
166
  _ensureToolpack(): Promise<void>;
167
+ /**
168
+ * Lazily initialise the AgentMind instance the first time it is needed.
169
+ * No-op when `this.mind` is not configured.
170
+ * Uses a shared promise to prevent duplicate initialisation under concurrent run() calls.
171
+ */
172
+ _ensureMind(): Promise<void>;
75
173
  /**
76
174
  * Start the agent: initialise Toolpack (if needed), bind message handlers to all
77
175
  * configured channels, and begin listening.
@@ -144,13 +242,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
144
242
  /**
145
243
  * Delegate a task to another agent by name (fire-and-forget).
146
244
  */
147
- protected delegate(agentName: string, input: Partial<AgentInput>): Promise<void>;
148
245
  /**
149
246
  * Delegate a task to another agent and wait for the result.
150
247
  */
151
248
  protected delegateAndWait(agentName: string, input: Partial<AgentInput>): Promise<AgentResult>;
152
249
  onBeforeRun(_input: AgentInput<TIntent>): Promise<void>;
153
- onStepComplete(_step: WorkflowStep): Promise<void>;
154
250
  onComplete(_result: AgentResult): Promise<void>;
155
251
  onError(_error: Error): Promise<void>;
156
252
  /**
@@ -175,7 +271,6 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
175
271
  * Extracted here so both standalone start() and AgentRegistry can reuse the same logic.
176
272
  */
177
273
  private _bindChannel;
178
- private _attachWorkflowStepUpdates;
179
274
  private _acquireConversationLock;
180
275
  private extractSteps;
181
276
  }
@@ -186,4 +281,4 @@ interface AgentEvents {
186
281
  'agent:error': (error: Error) => void;
187
282
  }
188
283
 
189
- export { type AgentEvents as A, BaseAgent as B };
284
+ export { type AgentMindConfig as A, BaseAgent as B, type ConfidenceLevel as C, type GoalPriority as G, type MindBelief as M, type AgentEvents as a, type GoalStatus as b, type MindEntry as c, type MindEntryType as d, type MindGoal as e, type MindRecallResult as f, type MindReflection as g, type MindTtlDefaults as h };
@@ -1,6 +1,83 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack } from 'toolpack-sdk';
3
- import { A as AgentInput, W as WorkflowStep, a as AgentResult, C as ChannelInterface, I as Interceptor, b as IAgentRegistry, B as BaseAgentOptions, c as AgentRunOptions, P as PendingAsk } from './types-BWoRx1ZE.cjs';
3
+ import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, C as ChannelInterface, I as Interceptor, c as IAgentRegistry, B as BaseAgentOptions, d as AgentRunOptions, P as PendingAsk } from './types-TB6yypig.js';
4
+ import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
+
6
+ type GoalStatus = 'active' | 'completed';
7
+ type GoalPriority = 'low' | 'normal' | 'high';
8
+ type ConfidenceLevel = 'low' | 'medium' | 'high';
9
+ type MindEntryType = 'goal' | 'belief' | 'reflection';
10
+ interface MindGoal {
11
+ id: string;
12
+ type: 'goal';
13
+ description: string;
14
+ priority: GoalPriority;
15
+ status: GoalStatus;
16
+ tags: string[];
17
+ dueBy?: string;
18
+ progress: string[];
19
+ outcome?: string;
20
+ createdAt: number;
21
+ updatedAt: number;
22
+ }
23
+ interface MindBelief {
24
+ id: string;
25
+ type: 'belief';
26
+ content: string;
27
+ confidence: ConfidenceLevel;
28
+ tags: string[];
29
+ expiresAt?: number;
30
+ createdAt: number;
31
+ updatedAt: number;
32
+ error?: boolean;
33
+ }
34
+ interface MindReflection {
35
+ id: string;
36
+ type: 'reflection';
37
+ content: string;
38
+ pinned: boolean;
39
+ tags: string[];
40
+ relatedTo?: string;
41
+ createdAt: number;
42
+ updatedAt: number;
43
+ error?: boolean;
44
+ }
45
+ type MindEntry = MindGoal | MindBelief | MindReflection;
46
+ interface MindRecallResult {
47
+ id: string;
48
+ type: MindEntryType;
49
+ content: string;
50
+ score?: number;
51
+ tags: string[];
52
+ createdAt: number;
53
+ updatedAt: number;
54
+ priority?: GoalPriority;
55
+ status?: GoalStatus;
56
+ progress?: string[];
57
+ outcome?: string;
58
+ dueBy?: string;
59
+ confidence?: ConfidenceLevel;
60
+ expiresAt?: number;
61
+ pinned?: boolean;
62
+ relatedTo?: string;
63
+ error?: boolean;
64
+ }
65
+ interface MindTtlDefaults {
66
+ belief?: string;
67
+ reflection?: string;
68
+ }
69
+ interface AgentMindConfig {
70
+ embedder: Embedder;
71
+ provider?: KnowledgeProvider;
72
+ namespace?: string;
73
+ tokenBudget?: number;
74
+ recencyWindowDays?: number;
75
+ maxGoals?: number;
76
+ maxPinnedReflections?: number;
77
+ deduplicationThreshold?: number;
78
+ retrievalThreshold?: number;
79
+ ttlDefaults?: MindTtlDefaults;
80
+ }
4
81
 
5
82
  /**
6
83
  * Abstract base class for all agents.
@@ -27,6 +104,19 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
27
104
  model?: string;
28
105
  /** Workflow configuration merged on top of mode config */
29
106
  workflow?: Record<string, unknown>;
107
+ /**
108
+ * Persistent cognitive layer. When set, the agent gains goals, beliefs, and
109
+ * reflections that survive across runs. Requires @toolpack-sdk/knowledge.
110
+ * Set to undefined (default) to opt out — zero cost when not configured.
111
+ */
112
+ mind?: AgentMindConfig;
113
+ /**
114
+ * AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
115
+ * injected into every run() call so the LLM can hand tasks to peer agents.
116
+ * Only active when the agent is registered in an AgentRegistry with peers.
117
+ * Set to undefined (default) to opt out — zero cost when not configured.
118
+ */
119
+ delegation?: AgentDelegationConfig;
30
120
  /**
31
121
  * Conversation history store. Auto-initialised to `InMemoryConversationStore` in the
32
122
  * constructor so subclass field initialisers (e.g. `interceptors = [createCaptureInterceptor({
@@ -65,6 +155,8 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
65
155
  private readonly _initConfig?;
66
156
  private _ownedToolpack;
67
157
  private readonly _conversationLocks;
158
+ private _mind?;
159
+ private _mindInitPromise?;
68
160
  constructor(options: BaseAgentOptions);
69
161
  /**
70
162
  * Ensure the Toolpack instance is ready.
@@ -72,6 +164,12 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
72
164
  * Creates and owns the instance from `apiKey` if it was not.
73
165
  */
74
166
  _ensureToolpack(): Promise<void>;
167
+ /**
168
+ * Lazily initialise the AgentMind instance the first time it is needed.
169
+ * No-op when `this.mind` is not configured.
170
+ * Uses a shared promise to prevent duplicate initialisation under concurrent run() calls.
171
+ */
172
+ _ensureMind(): Promise<void>;
75
173
  /**
76
174
  * Start the agent: initialise Toolpack (if needed), bind message handlers to all
77
175
  * configured channels, and begin listening.
@@ -144,13 +242,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
144
242
  /**
145
243
  * Delegate a task to another agent by name (fire-and-forget).
146
244
  */
147
- protected delegate(agentName: string, input: Partial<AgentInput>): Promise<void>;
148
245
  /**
149
246
  * Delegate a task to another agent and wait for the result.
150
247
  */
151
248
  protected delegateAndWait(agentName: string, input: Partial<AgentInput>): Promise<AgentResult>;
152
249
  onBeforeRun(_input: AgentInput<TIntent>): Promise<void>;
153
- onStepComplete(_step: WorkflowStep): Promise<void>;
154
250
  onComplete(_result: AgentResult): Promise<void>;
155
251
  onError(_error: Error): Promise<void>;
156
252
  /**
@@ -175,7 +271,6 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
175
271
  * Extracted here so both standalone start() and AgentRegistry can reuse the same logic.
176
272
  */
177
273
  private _bindChannel;
178
- private _attachWorkflowStepUpdates;
179
274
  private _acquireConversationLock;
180
275
  private extractSteps;
181
276
  }
@@ -186,4 +281,4 @@ interface AgentEvents {
186
281
  'agent:error': (error: Error) => void;
187
282
  }
188
283
 
189
- export { type AgentEvents as A, BaseAgent as B };
284
+ export { type AgentMindConfig as A, BaseAgent as B, type ConfidenceLevel as C, type GoalPriority as G, type MindBelief as M, type AgentEvents as a, type GoalStatus as b, type MindEntry as c, type MindEntryType as d, type MindGoal as e, type MindRecallResult as f, type MindReflection as g, type MindTtlDefaults as h };
@@ -1,17 +1,22 @@
1
- "use strict";var M=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(o,t)=>{for(var e in t)M(o,e,{get:t[e],enumerable:!0})},ne=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of X(t))!ee.call(o,s)&&s!==e&&M(o,s,{get:()=>t[s],enumerable:!(n=Z(t,s))||n.enumerable});return o};var se=o=>ne(M({},"__esModule",{value:!0}),o);var pe={};te(pe,{IntentClassifierAgent:()=>R,SummarizerAgent:()=>_});module.exports=se(pe);var Y=require("events"),b=require("toolpack-sdk");var x=Symbol("interceptor-skip-sentinel");function U(o){return o===x}function H(){return x}var N=class extends Error{constructor(t,e){super(`Invocation depth ${t} exceeds maximum ${e}`),this.name="InvocationDepthExceededError"}};function W(o,t,e,n,s={}){let i=s.maxInvocationDepth??5;return{async execute(r){let l=(u=>({agent:t,channel:e,registry:n,invocationDepth:u,delegateAndWait:async(p,m)=>{let d=u+1;if(d>i)throw new N(d,i);if(!n)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let y=n.getAgent(p);if(!y)throw new Error(`Agent "${p}" not found for delegation`);let g={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??r.conversationId??`delegation-${Date.now()}`};return await y.invokeAgent(g)},skip:H}))(0),c=async u=>{let p=u??r;return await t.invokeAgent(p)};for(let u=o.length-1;u>=0;u--){let p=o[u],m=c;c=async d=>await p(d??r,l,m)}return await c()}}}async function B(o,t){let e=await o.execute(t);return e===x?null:e}var E=require("crypto");function re(o){let t=o.context??{},e=t.channelType;return e==="im"||e==="private"||e==="dm"?"dm":t.threadId!==void 0?"thread":"channel"}var O=Symbol.for("toolpack:capture-history");function F(o){let t=o.captureAgentReplies??!0,e=o.getScope??re,n=o.getMessageId??(r=>r.context?.messageId??r.context?.eventId??(0,E.randomUUID)()),s=o.getMentions??(r=>r.context?.mentions??[]),i=async(r,a,l)=>{let c=r.conversationId;if(!c)return a.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await l();let u=r.participant;if(u){let m={id:n(r),conversationId:c,participant:u,content:r.message??"",timestamp:new Date().toISOString(),scope:e(r),metadata:{channelType:r.context?.channelType,threadId:r.context?.threadId,messageId:r.context?.messageId,mentions:s(r),channelName:r.context?.channelName,channelId:r.context?.channelId}};try{await o.store.append(m),o.onCaptured?.(m),a.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:u.id,conversationId:c})}catch(d){a.logger?.warn("[capture-history] Failed to store inbound message",{error:d instanceof Error?d.message:String(d)})}}let p=await l();if(t&&!U(p)&&p.output!=null){let m={kind:"agent",id:a.agent.name,displayName:a.agent.name},d={id:(0,E.randomUUID)(),conversationId:c,participant:m,content:p.output,timestamp:new Date().toISOString(),scope:e(r),metadata:{channelType:r.context?.channelType,threadId:r.context?.threadId,channelName:r.context?.channelName,channelId:r.context?.channelId}};try{await o.store.append(d),o.onCaptured?.(d),a.logger?.debug("[capture-history] Captured agent reply",{messageId:d.id,agentId:a.agent.name,conversationId:c})}catch(y){a.logger?.warn("[capture-history] Failed to store agent reply",{error:y instanceof Error?y.message:String(y)})}}return p};return i[O]=!0,i}var K=require("crypto");function q(o){return Math.ceil(o.length/4)}function oe(o){return{id:o.id,participant:o.participant,content:o.content,timestamp:o.timestamp}}function ie(o,t){let{participant:e,content:n}=o;return e.kind==="system"?{role:"system",content:n}:e.kind==="agent"?e.id===t?{role:"assistant",content:n}:{role:"user",content:`${e.displayName??e.id} (agent): ${n}`}:{role:"user",content:`${e.displayName??e.id}: ${n}`}}function ae(o,t,e){return!!(o.participant.id===t||o.metadata?.mentions?.some(n=>e.has(n)))}async function J(o,t,e,n,s={},i){let{scope:r,addressedOnlyMode:a=!0,tokenBudget:l=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:u,maxTurnsToLoad:p=100,agentAliases:m}=s,d=new Set([e,...m??[]]),y=u!==void 0?new Date(Date.now()-u*60*1e3).toISOString():void 0,g=await o.get(t,{scope:r,sinceTimestamp:y,limit:p}),$=g.length;if(a){let h=new Set;for(let f=0;f<g.length;f++){let S=g[f];if(ae(S,e,d)&&h.add(S.id),f<g.length-1){let k=g[f+1];k.participant.kind==="agent"&&k.participant.id===e&&h.add(S.id)}}let v=g[g.length-1];v&&h.add(v.id),g=g.filter(f=>h.has(f.id))}let T=!1;if(g.length>c&&i){let h=Math.floor(g.length/2),v=g.slice(0,h),f=g.slice(h),S=v.filter(k=>!k.metadata?.isSummary);try{let k=await i.invokeAgent({message:"summarize",data:{turns:S.map(oe),agentName:n,agentId:e,maxTokens:Math.floor(l*.25),extractDecisions:!0}}),L=JSON.parse(k.output),j={id:`summary-${(0,K.randomUUID)()}`,conversationId:t,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${L.turnsSummarized} earlier turns]: ${L.summary}`,timestamp:v[0].timestamp,scope:r??"channel",metadata:{isSummary:!0}};g=[j,...f],T=!0;try{await o.append(j),await o.deleteMessages(t,v.map(Q=>Q.id))}catch{}}catch{g=g.slice(-c)}}else g.length>c&&(g=g.slice(-c));let C=g.map(h=>ie(h,e));if(C.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:$,hasSummary:T};let D=C[C.length-1],z=[D],P=q(D.content);for(let h=C.length-2;h>=0;h--){let v=C[h],f=q(v.content);if(P+f>l)break;z.unshift(v),P+=f}return{messages:z,estimatedTokens:P,turnsLoaded:$,hasSummary:T}}var I=class extends Error{constructor(t){super(t),this.name="AgentError"}};var A=class extends Y.EventEmitter{provider;model;workflow;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;constructor(t){super(),this.conversationHistory=new b.InMemoryConversationStore,"toolpack"in t?this.toolpack=t.toolpack:this._initConfig=t}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await b.Toolpack.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}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 t of this.channels)this._bindChannel(t),t.listen()}async stop(){for(let t of this.channels)"stop"in t&&typeof t.stop=="function"&&await t.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(t,e,n){let s=n?.conversationId??this._conversationId;await this.onBeforeRun({message:t,conversationId:s}),this.emit("agent:start",{message:t});try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let i=[];if(s)try{let c=await J(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),u=c.messages[c.messages.length-1],p=t.trim(),d=p!==""&&u?.role==="user"&&typeof u.content=="string"&&(u.content===p||u.content.endsWith(`: ${p}`))?c.messages.slice(0,-1):c.messages;i.push(...d)}catch{}t.trim()&&i.push({role:"user",content:t});let r=[];if(s){let c=this.conversationHistory;r.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 u=>{let p=await c.search(s,String(u.query??""),{limit:typeof u.limit=="number"?u.limit:5});return{results:p.map(m=>({role:m.participant.kind==="agent"?"assistant":"user",content:m.content,timestamp:m.timestamp})),count:p.length}}})}let a=await this.toolpack.generate({messages:i,model:this.model||"",requestTools:r.length>0?r:void 0},this.provider),l={output:a.content||"",steps:this.extractSteps(a),metadata:a.usage?{usage:a.usage}:void 0};return await this.onComplete(l),this.emit("agent:complete",l),l}catch(i){throw await this.onError(i),this.emit("agent:error",i),i}}getAgentAliases(){let t=[];for(let e of this.channels){let n=e.botUserId;n&&t.push(n)}return t}async sendTo(t,e){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(t,{output:e})}async ask(t,e){if(!this._registry)throw new I("Agent not registered - cannot use ask()");if(!this._conversationId)throw new I("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new I("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new I("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let n=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:t,context:e?.context??{},maxRetries:e?.maxRetries??2,expiresAt:e?.expiresIn?new Date(Date.now()+e.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,t),{output:t,metadata:{waitingForHuman:!0,askId:n.id}}}getPendingAsk(t){if(!this._registry)return null;let e=t??this._conversationId;return e?this._registry.getPendingAsk(e)??null:null}async resolvePendingAsk(t,e){if(!this._registry)throw new I("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(t,e)}async evaluateAnswer(t,e,n){return n?.simpleValidation?n.simpleValidation(e):(await this.run(`Evaluate if this answer sufficiently addresses the question.
1
+ "use strict";var xe=Object.create;var D=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var x=(r,e)=>()=>(r&&(e=r(r=0)),e);var te=(r,e)=>{for(var t in e)D(r,t,{get:e[t],enumerable:!0})},ne=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!Te.call(r,n)&&n!==t&&D(r,n,{get:()=>e[n],enumerable:!(i=_e(e,n))||i.enumerable});return r};var De=(r,e,t)=>(t=r!=null?xe(Me(r)):{},ne(e||!r||!r.__esModule?D(t,"default",{value:r,enumerable:!0}):t,r)),Pe=r=>ne(D({},"__esModule",{value:!0}),r);var y=x(()=>{"use strict"});var B,z,F,H,W,K,a,E,ue=x(()=>{"use strict";y();B=require("crypto"),z=.6,F=.2,H=.2,W={low:.3,medium:.6,high:1},K=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"},E=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},o=n[t.priority]-n[i.priority];return o!==0?o:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let o=this.chunkToBelief(n),s=(t-o.createdAt)/864e5,p=Math.exp(-s/K)*F+W.high*H+z;return{...o,score:p}}).sort((n,o)=>o.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(o=>o[a.type]==="reflection"&&!o[a.pinned]&&!o[a.error]&&o[a.createdAt]>=i)).map(o=>this.chunkToReflection(o)).sort((o,s)=>s.createdAt-o.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:o}=t,s;if(e.trim()&&typeof this.provider.keywordQuery=="function")s=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(p=>this.chunkToGoal(p.chunk));else{let u=n;if(s=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();s=s.filter(d=>d.description.toLowerCase().includes(c))}}return o?.length&&(s=s.filter(u=>o.every(p=>u.tags.includes(p)))),s.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:o,includeExpired:s=!1}=t,u=Date.now(),p=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of p){let l=this.chunkToBelief(d.chunk);if(!s&&l.expiresAt&&l.expiresAt<u||o?.length&&!o.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,g=Math.exp(-m/K),h=l.error?.3:W[l.confidence],f=d.score*z+g*F+h*H;f<n||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:o,pinned:s}=t,u=Date.now(),p={[a.type]:"reflection"};s===!0&&(p[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:p}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(s===!1&&m.pinned||o?.length&&!o.every(w=>m.tags.includes(w)))continue;let g=(u-m.createdAt)/864e5,h=Math.exp(-g/K),f=l.score*z+h*F+W.medium*H;f<n||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let o of n){let s=this.chunkToBelief(o.chunk);if(!(s.expiresAt&&s.expiresAt<i))return{id:o.chunk.id,score:o.score,belief:s}}return null}async addGoal(e){let t=(0,B.randomUUID)();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),o={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(o)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=(0,B.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let o=this.chunkToBelief(n),s={...o,content:t.content??o.content,confidence:t.confidence??o.confidence,tags:t.tags??o.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:o.expiresAt,error:t.error??o.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(s,u)])}async addReflection(e,t){let i=(0,B.randomUUID)();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),o={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(o,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function V(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function pe(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=V(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function me(r,e){let t=0,i=0,n=0;for(let s=0;s<r.length;s++)t+=r[s]*e[s],i+=r[s]*r[s],n+=e[s]*e[s];let o=Math.sqrt(i)*Math.sqrt(n);return o===0?0:t/o}function J(r){return Math.ceil(r.length/4)}var Y=x(()=>{"use strict";y()});var ge,N,fe=x(()=>{"use strict";y();ge=require("crypto");Y();N=class{constructor(e,t,i,n,o,s){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=o;this.committedPinnedReflectionCount=s}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,o=e.expiresIn??e.ttlDefault;o&&(n=t+V(o));let s=this._findSimilarInDraft(i);if(s!==null){let c=this.ops[s],d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l];return this.ops[s]={...c,content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${s}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l],h={op:"believe",content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let s=this.totalPinnedReflectionCount;if(s>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);s>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${s+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},o=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:o,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?pe(e.dueBy):void 0,i={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(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let o=i;if(o.vector.length===0)continue;if(me(e,o.vector)>=this.deduplicationThreshold)return n}return null}}});function he(r,e,t){return[Oe(r,t),$e(r,e,t),Le(e,t),Ue(e),qe(e,t),je(r,e),ze(r)]}function Oe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",o=t.status??"active",s=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,p=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:o,tags:s});for(let f of h)l.push(Fe(f))}if(g&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(g,{limit:d,threshold:c,tags:s,includeExpired:p});for(let f of h)l.push(He(f))}if(g&&(n==="reflection"||n==="all")){let h=await r.queryReflections(g,{limit:d,threshold:c,tags:s,pinned:u});for(let f of h)l.push(We(f))}return l}}}function $e(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Le(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 Ue(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 qe(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function je(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function ze(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 Fe(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 He(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 We(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 ye=x(()=>{"use strict";y()});async function we(r,e){let[t,i,n,o]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),s=t.map(l=>Ke(l)),u=i.map(l=>`- ${l.content}`),{beliefLines:p,reflectionLines:c}=Ve(n,o,e.tokenBudget);if(s.length===0&&u.length===0&&p.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return s.length>0&&(d.push("## Goals"),d.push(...s),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),p.length>0&&(d.push("## Beliefs"),d.push(...p),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
+ `)}function Ke(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 Ve(r,e,t){let i=t,n=[],o=[];for(let s of r){let u=`- ${s.content} (${s.confidence} confidence)`,p=J(u);if(p>i)break;n.push(u),i-=p}for(let s of e){let p=`- [${new Date(s.createdAt).toISOString().slice(0,10)}] ${s.content}`,c=J(p);if(c>i)break;o.push(p),i-=c}return{beliefLines:n,reflectionLines:o}}var ve=x(()=>{"use strict";y();Y()});var Ae={};te(Ae,{AgentMind:()=>X});function rt(r,e){let t=Math.min(e.maxGoals??Xe,nt),i=Math.min(e.maxPinnedReflections??Qe,it);return{tokenBudget:e.tokenBudget??Je,recencyWindowDays:e.recencyWindowDays??Ye,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??Ze,retrievalThreshold:e.retrievalThreshold??et,ttlDefaults:{belief:e.ttlDefaults?.belief??tt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var Je,Ye,Xe,Qe,Ze,et,tt,nt,it,X,be=x(()=>{"use strict";y();ue();fe();ye();ve();Je=300,Ye=7,Xe=10,Qe=10,Ze=.85,et=.35,tt="30d",nt=10,it=10,X=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:s}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new s({namespace:u})}let n=rt(e,t),o=new E(i,t.embedder);return await o.initialize(),new r(o,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),we(this.store,this.config)]),n=new N(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),o=he(this.store,n,this.config);return{mindHeader:i,tools:o,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var at={};te(at,{IntentClassifierAgent:()=>O,SummarizerAgent:()=>$});module.exports=Pe(at);y();y();y();var ke=require("events"),G=require("toolpack-sdk");y();y();var P=Symbol("interceptor-skip-sentinel");function ie(r){return r===P}function re(){return P}var U=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function oe(r,e,t,i,n={}){let o=n.maxInvocationDepth??5;return{async execute(s){let p=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>o)throw new U(g,o);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let h=i.getAgent(l);if(!h)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:re}))(0),c=async d=>{let l=d??s;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??s,p,m)}return await c()}}}async function se(r,e){let t=await r.execute(e);return t===P?null:t}y();var q=require("crypto");function Be(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var j=Symbol.for("toolpack:capture-history");function ae(r){let e=r.captureAgentReplies??!0,t=r.getScope??Be,i=r.getMessageId??(s=>s.context?.messageId??s.context?.eventId??(0,q.randomUUID)()),n=r.getMentions??(s=>s.context?.mentions??[]),o=async(s,u,p)=>{let c=s.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await p();let d=s.participant;if(d){let m={id:i(s),conversationId:c,participant:d,content:s.message??"",timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:n(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){u.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await p();if(e&&!ie(l)&&l.output!=null){let m={kind:"agent",id:u.agent.name,displayName:u.agent.name},g={id:(0,q.randomUUID)(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return l};return o[j]=!0,o}y();var de=require("crypto");function ce(r){return Math.ceil(r.length/4)}function Ee(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Ne(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Ge(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function le(r,e,t,i,n={},o){let{scope:s,addressedOnlyMode:u=!0,tokenBudget:p=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:s,sinceTimestamp:h,limit:l}),w=f.length;if(u){let A=new Set;for(let b=0;b<f.length;b++){let M=f[b];if(Ge(M,t,g)&&A.add(M.id),b<f.length-1){let _=f[b+1];_.participant.kind==="agent"&&_.participant.id===t&&A.add(M.id)}}let R=f[f.length-1];R&&A.add(R.id),f=f.filter(b=>A.has(b.id))}let k=!1;if(f.length>c&&o){let A=Math.floor(f.length/2),R=f.slice(0,A),b=f.slice(A),M=R.filter(_=>!_.metadata?.isSummary);try{let _=await o.invokeAgent({message:"summarize",data:{turns:M.map(Ee),agentName:i,agentId:t,maxTokens:Math.floor(p*.25),extractDecisions:!0}}),Z=JSON.parse(_.output),ee={id:`summary-${(0,de.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${Z.turnsSummarized} earlier turns]: ${Z.summary}`,timestamp:R[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};f=[ee,...b],k=!0;try{await r.append(ee),await r.deleteMessages(e,R.map(Ce=>Ce.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let I=f.map(A=>Ne(A,t));if(I.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:k};let T=I[I.length-1],Q=[T],L=ce(T.content);for(let A=I.length-2;A>=0;A--){let R=I[A],b=ce(R.content);if(L+b>p)break;Q.unshift(R),L+=b}return{messages:Q,estimatedTokens:L,turnsLoaded:w,hasSummary:k}}y();var C=class extends Error{constructor(e){super(e),this.name="AgentError"}};var S=class extends ke.EventEmitter{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new G.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 G.Toolpack.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(be(),Ae));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await le(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
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.
2
4
 
3
- Question: "${t}"
4
- Answer: "${e}"
5
+ Available agents:
6
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let k=String(w.agent),I=String(w.message??"");return this._registry.invoke(k,{message:I,conversationId:n,context:{delegatedBy:this.name}}).catch(T=>{console.error(`[${this.name}] delegate_and_forget to ${k} failed:`,T)}),{status:"delegated",agent:k}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
5
7
 
6
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(t,e,n,s){return await this.evaluateAnswer(t.question,e,{simpleValidation:r=>r.trim().length>3})?(await this.resolvePendingAsk(t.id,e),n(e)):t.retries>=t.maxRetries?(await this.resolvePendingAsk(t.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),s?s():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:t.id}}):(this._registry?.incrementRetries(t.id),this.ask(`I need a bit more clarity on: "${t.question}". Could you provide more details?`,{context:t.context,maxRetries:t.maxRetries}))}async delegate(t,e){if(!this._registry)throw new I("Agent not registered - cannot use delegate()");let n={message:e.message,intent:e.intent,data:e.data,context:{...e.context||{},delegatedBy:this.name},conversationId:e.conversationId||this._conversationId||`delegation-${Date.now()}`};this._registry.invoke(t,n).catch(s=>{console.error(`[${this.name}] Delegation to ${t} failed:`,s.message)})}async delegateAndWait(t,e){if(!this._registry)throw new I("Agent not registered - cannot use delegateAndWait()");let n={message:e.message,intent:e.intent,data:e.data,context:{...e.context||{},delegatedBy:this.name},conversationId:e.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(t,n)}async onBeforeRun(t){}async onStepComplete(t){}async onComplete(t){}async onError(t){}_resolveAssemblerOptions(){let t=this.channels.map(s=>s.botUserId).filter(s=>typeof s=="string"&&s.length>0),e=this.assemblerOptions?.agentAliases??[];if(t.length===0&&e.length===0)return this.assemblerOptions;let n=Array.from(new Set([...e,...t]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(e=>e[O]===!0)?this.interceptors:[F({store:this.conversationHistory}),...this.interceptors]}_bindChannel(t){t.onMessage(async e=>{if(!e.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let n=await this._acquireConversationLock(e.conversationId),s=()=>{};try{this._triggeringChannel=t.name,this._isTriggerChannel=t.isTriggerChannel,this._conversationId=e.conversationId,s=this._attachWorkflowStepUpdates(t,e);let i=W(this._getEffectiveInterceptors(),this,t,this._registry??null),r=await B(i,e);if(r===null)return;let a={output:r.output,metadata:r.metadata};await t.send({output:a.output,metadata:{...a.metadata,conversationId:e.conversationId,...e.context}})}catch(i){let r=i instanceof Error?i.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${r}`);try{await t.send({output:`Error: ${r}`,metadata:{conversationId:e.conversationId,error:!0,...e.context}})}catch(a){console.error(`[${this.name}] Failed to send error to channel: ${a}`)}}finally{s(),n()}})}_attachWorkflowStepUpdates(t,e){if(t.isTriggerChannel)return()=>{};let n=new Set,s=new Set,i=a=>{a?.id&&n.add(String(a.id))},r=(a,l)=>{if(!l?.id||!n.has(String(l.id))||!a?.result?.output||typeof a.result.output!="string"||l?.steps?.length&&Number(l.steps.length)<=1)return;let c=`${String(l.id)}:${String(a.id??a.number??"unknown")}`;if(s.has(c))return;s.add(c);let u=a.result.output.trim();if(!u)return;let p=u.length>3500?`${u.slice(0,3500)}
7
- ... [truncated]`:u,m=`Step ${a.number}: ${a.description||"Completed"}`;t.send({output:`${m}
8
+ Available agents:
9
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let k=String(w.agent),I=String(w.message??"");return this._registry.invoke(k,{message:I,conversationId:n,context:{delegatedBy:this.name}})}})}}let d=await this.toolpack.generate({messages:p,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds},this.provider),l={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(l),o&&await o(!1),this.emit("agent:complete",l),l}catch(p){throw o&&o(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(p),this.emit("agent:error",p),p}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new C("Agent not registered - cannot use ask()");if(!this._conversationId)throw new C("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new C("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new C("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new C("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
8
10
 
9
- ${p}`,metadata:{conversationId:e.conversationId,...e.context}}).catch(d=>{let y=d instanceof Error?d.message:String(d);console.warn(`[${this.name}] Failed to send workflow step update: ${y}`)})};return this.toolpack.on("workflow:plan_created",i),this.toolpack.on("workflow:step_complete",r),()=>{this.toolpack.off("workflow:plan_created",i),this.toolpack.off("workflow:step_complete",r)}}async _acquireConversationLock(t){for(;this._conversationLocks.has(t);)try{await this._conversationLocks.get(t)}catch{}let e,n=new Promise(s=>{e=s});return this._conversationLocks.set(t,n),()=>{this._conversationLocks.delete(t),e()}}extractSteps(t){let e=t;if(e.plan&&typeof e.plan=="object"){let n=e.plan;if(Array.isArray(n.steps))return n.steps.map(s=>({number:s.number||0,description:s.description||"",status:s.status||"completed",result:s.result}))}if(Array.isArray(e.steps))return e.steps}};var V=require("toolpack-sdk"),ce={...V.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(`
10
- `)},R=class extends A{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=ce;constructor(t){super(t)}async invokeAgent(t){let e=t.data;if(e?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!e?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let n=[];if(n.push(`Context: Public channel #${e.channelName}`),n.push(`Target agent: "${e.agentName}" (ID: ${e.agentId})`),n.push(`Message sender: ${e.senderName}`),e.recentContext&&e.recentContext.length>0){n.push(`
11
- Recent conversation:`);for(let a of e.recentContext)n.push(` ${a.sender}: ${a.content.substring(0,100)}`)}n.push(`
12
- Message to classify: "${e.message}"`),e.includeExamples&&(n.push(`
13
- Examples of classifications:`),n.push(` "@${e.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${e.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${e.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
14
- Classification (start with direct, indirect, passive, or ignore):`);let s=n.join(`
15
- `),i=await this.run(s),r=this.normalizeClassification(i.output);return{output:r,metadata:{rawOutput:i.output,classification:r,confidence:"high"}}}normalizeClassification(t){let e=t.toLowerCase().trim().split(/\s+/)[0],n=t.toLowerCase();return["direct","indirect","passive","ignore"].includes(e)?e: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"}};var G=require("toolpack-sdk"),ue={...G.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(`
16
- `)},_=class extends A{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=ue;constructor(t){super(t)}async invokeAgent(t){let e=t.data;if(!e?.turns||e.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let n=e.maxTokens??800,s=e.extractDecisions??!0,i=[`Target agent: "${e.agentName}" (ID: ${e.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${s?"yes":"no"}`,"",`Conversation turns to summarize (${e.turns.length} turns):`,""];for(let c of e.turns){let u=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${p}`:p,d=`[${u}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(d+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(d+=` [tool: ${c.metadata.toolName}]`),i.push(d)}i.push("","Generate a JSON summary object:");let r=i.join(`
17
- `),a=await this.run(r),l=this.parseSummarizerOutput(a.output,e.turns.length);return{output:JSON.stringify(l),metadata:{turnsProcessed:e.turns.length,rawOutputLength:a.output.length}}}parseSummarizerOutput(t,e){let n=t.trim(),s=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);s&&(n=s[1].trim());try{let i=JSON.parse(n);return{summary:typeof i.summary=="string"&&i.summary.length>0?i.summary:this.generateFallbackSummary(e),turnsSummarized:typeof i.turnsSummarized=="number"?i.turnsSummarized:e,hasDecisions:typeof i.hasDecisions=="boolean"?i.hasDecisions:!1,estimatedTokens:typeof i.estimatedTokens=="number"&&i.estimatedTokens>0?i.estimatedTokens:Math.ceil(t.length/4)}}catch{return{summary:this.generateFallbackSummary(e),turnsSummarized:e,hasDecisions:t.toLowerCase().includes("decision")||t.toLowerCase().includes("action"),estimatedTokens:Math.ceil(t.length/4)}}}generateFallbackSummary(t){return`(Summary of ${t} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
11
+ Question: "${e}"
12
+ Answer: "${t}"
13
+
14
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:s=>s.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new C("Agent not registered - cannot use delegateAndWait()");let i={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,i)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(n=>n.botUserId).filter(n=>typeof n=="string"&&n.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let i=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:i}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[j]===!0)?this.interceptors:[ae({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let i=await this._acquireConversationLock(t.conversationId);try{this._triggeringChannel=e.name,this._isTriggerChannel=e.isTriggerChannel,this._conversationId=t.conversationId;let n=oe(this._getEffectiveInterceptors(),this,e,this._registry??null),o=await se(n,t);if(o===null)return;let s={output:o.output,metadata:o.metadata};await e.send({output:s.output,metadata:{...s.metadata,conversationId:t.conversationId,...t.context}})}catch(n){let o=n instanceof Error?n.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${o}`);try{await e.send({output:`Error: ${o}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(s){console.error(`[${this.name}] Failed to send error to channel: ${s}`)}}finally{i()}})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,i=new Promise(n=>{t=n});return this._conversationLocks.set(e,i),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let i=t.plan;if(Array.isArray(i.steps))return i.steps.map(n=>({number:n.number||0,description:n.description||"",status:n.status||"completed",result:n.result}))}if(Array.isArray(t.steps))return t.steps}};var Ie=require("toolpack-sdk"),ot={...Ie.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(`
15
+ `)},O=class extends S{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=ot;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let i=[];if(i.push(`Context: Public channel #${t.channelName}`),i.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),i.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){i.push(`
16
+ Recent conversation:`);for(let u of t.recentContext)i.push(` ${u.sender}: ${u.content.substring(0,100)}`)}i.push(`
17
+ Message to classify: "${t.message}"`),t.includeExamples&&(i.push(`
18
+ Examples of classifications:`),i.push(` "@${t.agentName} help me" \u2192 direct`),i.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),i.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),i.push(' "Check the logs" \u2192 ignore')),i.push(`
19
+ Classification (start with direct, indirect, passive, or ignore):`);let n=i.join(`
20
+ `),o=await this.run(n),s=this.normalizeClassification(o.output);return{output:s,metadata:{rawOutput:o.output,classification:s,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();var Re=require("toolpack-sdk"),st={...Re.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(`
21
+ `)},$=class extends S{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=st;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let i=t.maxTokens??800,n=t.extractDecisions??!0,o=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${i} tokens`,`Extract decisions/action items: ${n?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let c of t.turns){let d=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),l=c.participant.displayName??c.participant.id,m=c.participant.kind==="agent"?`[BOT] ${l}`:l,g=`[${d}] ${m}: ${c.content.substring(0,200)}`;c.content.length>200&&(g+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(g+=` [tool: ${c.metadata.toolName}]`),o.push(g)}o.push("","Generate a JSON summary object:");let s=o.join(`
22
+ `),u=await this.run(s),p=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(p),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let i=e.trim(),n=i.match(/```(?:json)?\s*([\s\S]*?)\s*```/);n&&(i=n[1].trim());try{let o=JSON.parse(i);return{summary:typeof o.summary=="string"&&o.summary.length>0?o.summary:this.generateFallbackSummary(t),turnsSummarized:typeof o.turnsSummarized=="number"?o.turnsSummarized:t,hasDecisions:typeof o.hasDecisions=="boolean"?o.hasDecisions:!1,estimatedTokens:typeof o.estimatedTokens=="number"&&o.estimatedTokens>0?o.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
@@ -1,9 +1,10 @@
1
- export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-BLXXcbNJ.cjs';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-BWoRx1ZE.cjs';
3
- import { B as BaseAgent } from '../base-agent-CjrUlo6Y.cjs';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-DxyfJWcm.cjs';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-TB6yypig.cjs';
3
+ import { B as BaseAgent } from '../base-agent-DPdK4Pnl.cjs';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';
7
+ import '@toolpack-sdk/knowledge';
7
8
 
8
9
  /**
9
10
  * A message turn in the conversation history.
@@ -1,9 +1,10 @@
1
- export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-BLpDwKVf.js';
2
- import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-BWoRx1ZE.js';
3
- import { B as BaseAgent } from '../base-agent-Cx2kWzLF.js';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-0JZDlhpk.js';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-TB6yypig.js';
3
+ import { B as BaseAgent } from '../base-agent-nU8pr4nu.js';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';
7
+ import '@toolpack-sdk/knowledge';
7
8
 
8
9
  /**
9
10
  * A message turn in the conversation history.