@toolpack-sdk/agents 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,8 @@ Build production-ready AI agents with channels, workflows, and event-driven arch
13
13
  - **Human-in-the-Loop** — `ask()` support for two-way channels
14
14
  - **Knowledge Integration** — Built-in RAG support with knowledge bases
15
15
  - **Agent Mind** — Persistent cognitive layer: goals, beliefs, reflections, cross-run recall
16
+ - **Agent Spawning** — LLM-driven ephemeral sub-agents via `spawn_agent` / `spawn_agents_parallel` tools, with depth control and parallel execution
17
+ - **Hot Reload** — File watcher + graceful restart so code changes take effect without dropping conversations
16
18
  - **Evals** — `EvalDataset`, `EvalRunner`, 4 scorer types, regression reports
17
19
  - **OTel Tracing** — OpenTelemetry interceptor for distributed traces
18
20
  - **Type-Safe** — Full TypeScript support
@@ -441,6 +443,92 @@ agent.on('agent:error', (error) => {
441
443
  });
442
444
  ```
443
445
 
446
+ ## Hot Reload & Graceful Restart
447
+
448
+ `HotReloadWatcher` watches your source files for changes and triggers a graceful restart once all in-flight conversations finish. The process exits cleanly (`process.exit(0)`) so a process manager (PM2, systemd) can bring it back up with the new `dist/` and `.env`.
449
+
450
+ ### How it works
451
+
452
+ 1. A file change is detected in a watched directory.
453
+ 2. A 30-second debounce timer starts. Every new change resets it.
454
+ 3. After 30 seconds of silence:
455
+ - `.ts` / `.tsx` → runs `tsc --build`. On success, calls `onRestartNeeded`.
456
+ - `.env*` → calls `onRestartNeeded` directly (no compile step).
457
+ 4. `onRestartNeeded` calls `registry.scheduleRestart()`.
458
+ 5. The registry waits for all active conversations to finish, then calls `process.exit(0)`.
459
+ 6. The process manager restarts the process with fresh compiled output and environment variables.
460
+
461
+ ### Setup
462
+
463
+ ```typescript
464
+ import { AgentRegistry, HotReloadWatcher } from '@toolpack-sdk/agents';
465
+
466
+ const registry = new AgentRegistry([myAgent]);
467
+ await registry.start();
468
+
469
+ const watcher = new HotReloadWatcher({
470
+ watchPaths: ['./src'], // Directories or files to watch
471
+ cwd: process.cwd(), // Working directory for tsc --build
472
+ debounceMs: 30_000, // Wait 30s of silence before acting (default)
473
+ onRestartNeeded: () => registry.scheduleRestart(),
474
+ onCompileError: (msg) => console.error('[tsc]', msg),
475
+ });
476
+ watcher.start();
477
+ ```
478
+
479
+ ### scheduleRestart options
480
+
481
+ ```typescript
482
+ registry.scheduleRestart({
483
+ maxWaitMinutes: 30, // Force restart after this many minutes even if conversations are still active (default: 30)
484
+ });
485
+ ```
486
+
487
+ `scheduleRestart()` is **idempotent** — calling it multiple times (e.g., two files change within the same debounce window) has no effect after the first call.
488
+
489
+ ### Persistent conversation history across restarts
490
+
491
+ In-memory conversation history is lost when the process exits. Use `SQLiteConversationStore` from `toolpack-sdk` so history survives restarts. Requires `better-sqlite3`:
492
+
493
+ ```bash
494
+ npm install better-sqlite3
495
+ ```
496
+
497
+ ```typescript
498
+ import { SQLiteConversationStore } from 'toolpack-sdk';
499
+
500
+ class MyAgent extends BaseAgent {
501
+ name = 'my-agent';
502
+ description = 'My agent';
503
+ mode = 'chat';
504
+
505
+ conversationHistory = new SQLiteConversationStore({ dbPath: './conversations.db' });
506
+
507
+ async invokeAgent(input) {
508
+ return this.run(input.message);
509
+ }
510
+ }
511
+ ```
512
+
513
+ The SQLite file survives `process.exit(0)`. The new process re-opens the same file and picks up full conversation history — users continue mid-conversation as if nothing happened.
514
+
515
+ ### AgentRegistry — dynamic agent management
516
+
517
+ The registry supports adding and removing agents at runtime after `start()`:
518
+
519
+ ```typescript
520
+ // Add an agent after the registry is already running
521
+ const newAgent = new ResearchAgent({ apiKey: process.env.ANTHROPIC_API_KEY });
522
+ await registry.addAgent(newAgent); // wired + started immediately
523
+
524
+ // Remove an agent by name (stops it and unregisters its channels)
525
+ await registry.removeAgent('research-agent');
526
+ ```
527
+
528
+ ### Self-evolving agents
529
+
530
+ If an agent uses a `CodingAgent` sub-agent to edit its own source files, the orchestrator holds a conversation lock for the duration of that task. The hot reload watcher detects the file changes and calls `scheduleRestart()` — but the restart only executes after the orchestrator's conversation finishes and the lock is released. The new code takes effect on the next PM2/systemd restart cycle.
531
+
444
532
  ## Extending Built-in Agents
445
533
 
446
534
  Customize built-in agents with your own prompts and logic:
@@ -516,6 +604,34 @@ class AgentRegistry {
516
604
  getAgent(name: string): AgentInstance | undefined;
517
605
  getChannel(name: string): ChannelInterface | undefined;
518
606
  invoke(agentName: string, input: AgentInput): Promise<AgentResult>;
607
+
608
+ // Dynamic agent management
609
+ addAgent(agent: BaseAgent): Promise<void>; // Wires + starts immediately if registry is already running
610
+ removeAgent(name: string): Promise<void>; // Stops the agent and unregisters its channels
611
+
612
+ // Graceful restart
613
+ isAllIdle(): boolean; // True when no agent has an active conversation
614
+ scheduleRestart(options?: { maxWaitMinutes?: number }): void; // Idempotent; waits for idle then exits
615
+ }
616
+ ```
617
+
618
+ ### HotReloadWatcher
619
+
620
+ ```typescript
621
+ class HotReloadWatcher {
622
+ constructor(options: HotReloadWatcherOptions);
623
+ start(): void;
624
+ stop(): void;
625
+ }
626
+
627
+ interface HotReloadWatcherOptions {
628
+ watchPaths: string[]; // Directories or files to watch
629
+ cwd?: string; // Working directory for tsc --build (default: process.cwd())
630
+ debounceMs?: number; // Silence window before acting (default: 30 000 ms)
631
+ onRestartNeeded: () => void; // Called after a successful compile or an .env change
632
+ onCompileError?: (stderr: string) => void; // Called when tsc --build exits non-zero (restart NOT triggered)
633
+ spawnFn?: SpawnFn; // Inject a custom spawn function (testing)
634
+ watchFn?: WatchFn; // Inject a custom watch function (testing)
519
635
  }
520
636
  ```
521
637
 
@@ -711,6 +827,65 @@ Failed to invoke agent "data-agent" at http://localhost:3000: fetch failed
711
827
  ```
712
828
  → Verify the JSON-RPC server is running and the URL/port is correct.
713
829
 
830
+ ## Agent Spawning
831
+
832
+ When `spawn` is configured on a `BaseAgent`, two tools are injected into every `run()` call: `spawn_agent` and `spawn_agents_parallel`. The LLM uses these to instantiate lightweight helper agents on-demand, get their results, and continue — all within a single conversation turn. Spawned agents are ephemeral: no channels, no registry entry, discarded after use.
833
+
834
+ ```typescript
835
+ import { BaseAgent } from '@toolpack-sdk/agents';
836
+ import type { AgentSpawnConfig } from '@toolpack-sdk/agents';
837
+
838
+ class OrchestratorAgent extends BaseAgent {
839
+ name = 'orchestrator';
840
+ description = 'Coordinates research and coding tasks';
841
+ mode = 'agent';
842
+
843
+ spawn: AgentSpawnConfig = {
844
+ enabled: true,
845
+ templates: [
846
+ {
847
+ name: 'researcher',
848
+ description: 'Searches the web and summarises findings on a topic.',
849
+ systemPrompt: (task) => `You are a focused research agent. Task: ${task}`,
850
+ },
851
+ {
852
+ name: 'coder',
853
+ description: 'Writes or refactors code for a specific request.',
854
+ systemPrompt: (task) => `You are a senior engineer. Task: ${task}`,
855
+ model: 'claude-opus-4-8',
856
+ },
857
+ ],
858
+ maxDepth: 3, // spawned agents can themselves spawn, up to this depth
859
+ };
860
+
861
+ async invokeAgent(input) {
862
+ return this.run(input.message);
863
+ }
864
+ }
865
+ ```
866
+
867
+ **Key options:**
868
+
869
+ | Option | Type | Default | Description |
870
+ |--------|------|---------|-------------|
871
+ | `enabled` | `boolean` | — | Must be `true` for tools to be injected |
872
+ | `templates` | `AgentSpawnTemplate[]` | — | Available spawn targets. LLM picks by `name` + `description`. |
873
+ | `maxDepth` | `number` | `3` | Max recursive spawn depth. At the limit, spawn tools are silently omitted. |
874
+
875
+ **Template options:**
876
+
877
+ | Option | Type | Description |
878
+ |--------|------|-------------|
879
+ | `name` | `string` | Unique identifier. Use `'self'` for self-replication. |
880
+ | `description` | `string` | Purpose shown to the LLM. |
881
+ | `systemPrompt` | `(task: string) => string` | Called at spawn time with the task string. |
882
+ | `model` | `string` | Model override. Inherits parent when omitted. |
883
+ | `allowPromptAddition` | `boolean` | Allow LLM to append extra instructions via `systemPromptAddition`. Default: `false`. |
884
+
885
+ **Parallel spawning** — the LLM can call `spawn_agents_parallel` with an array of tasks; all agents run via `Promise.all`.
886
+
887
+ **Self-replication** — add `{ name: 'self', ... }` to the templates list. The replica inherits the parent's mode and system prompt with the template's `systemPrompt(task)` appended.
888
+
714
889
  ## Interceptors
715
890
 
716
891
  Interceptors are composable middleware that run before `invokeAgent`. They can filter, enrich, classify, or short-circuit incoming messages. All built-ins are opt-in — none run unless you explicitly list them.
@@ -1,6 +1,6 @@
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, 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';
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-C3EZvpe0.js';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -117,6 +117,15 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
117
117
  * Set to undefined (default) to opt out — zero cost when not configured.
118
118
  */
119
119
  delegation?: AgentDelegationConfig;
120
+ /**
121
+ * AI-driven dynamic agent spawning. When enabled, a `spawn_agent` tool is
122
+ * injected into every run() call so the LLM can instantiate one-off helper
123
+ * agents from templates, get their results, and continue — recursively up to
124
+ * `maxDepth` (default 3). Spawned agents are ephemeral: no channels, no
125
+ * registry entry, discarded after use.
126
+ * Set to undefined (default) to opt out — zero cost when not configured.
127
+ */
128
+ spawn?: AgentSpawnConfig;
120
129
  /**
121
130
  * Conversation history store. Auto-initialised to `InMemoryConversationStore` in the
122
131
  * constructor so subclass field initialisers (e.g. `interceptors = [createCaptureInterceptor({
@@ -182,6 +191,8 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
182
191
  * Stop all channels and release resources owned by this agent.
183
192
  */
184
193
  stop(): Promise<void>;
194
+ /** Returns true when no conversations are currently in progress for this agent. */
195
+ isIdle(): boolean;
185
196
  /**
186
197
  * Main entry point for agent invocation.
187
198
  * Implement this to handle incoming messages and route to appropriate logic.
@@ -198,6 +209,7 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
198
209
  */
199
210
  protected run(message: string, _options?: AgentRunOptions, context?: {
200
211
  conversationId?: string;
212
+ spawnDepth?: number;
201
213
  }): Promise<AgentResult>;
202
214
  /**
203
215
  * Returns extra identity strings (platform user ids, bot ids) that should
@@ -1,6 +1,6 @@
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, 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';
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-C3EZvpe0.cjs';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -117,6 +117,15 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
117
117
  * Set to undefined (default) to opt out — zero cost when not configured.
118
118
  */
119
119
  delegation?: AgentDelegationConfig;
120
+ /**
121
+ * AI-driven dynamic agent spawning. When enabled, a `spawn_agent` tool is
122
+ * injected into every run() call so the LLM can instantiate one-off helper
123
+ * agents from templates, get their results, and continue — recursively up to
124
+ * `maxDepth` (default 3). Spawned agents are ephemeral: no channels, no
125
+ * registry entry, discarded after use.
126
+ * Set to undefined (default) to opt out — zero cost when not configured.
127
+ */
128
+ spawn?: AgentSpawnConfig;
120
129
  /**
121
130
  * Conversation history store. Auto-initialised to `InMemoryConversationStore` in the
122
131
  * constructor so subclass field initialisers (e.g. `interceptors = [createCaptureInterceptor({
@@ -182,6 +191,8 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
182
191
  * Stop all channels and release resources owned by this agent.
183
192
  */
184
193
  stop(): Promise<void>;
194
+ /** Returns true when no conversations are currently in progress for this agent. */
195
+ isIdle(): boolean;
185
196
  /**
186
197
  * Main entry point for agent invocation.
187
198
  * Implement this to handle incoming messages and route to appropriate logic.
@@ -198,6 +209,7 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
198
209
  */
199
210
  protected run(message: string, _options?: AgentRunOptions, context?: {
200
211
  conversationId?: string;
212
+ spawnDepth?: number;
201
213
  }): Promise<AgentResult>;
202
214
  /**
203
215
  * Returns extra identity strings (platform user ids, bot ids) that should
@@ -1,22 +1,40 @@
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(`
1
+ "use strict";var ze=Object.create;var z=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var X=(r,e)=>{for(var t in e)z(r,t,{get:e[t],enumerable:!0})},he=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of He(e))!Ke.call(r,n)&&n!==t&&z(r,n,{get:()=>e[n],enumerable:!(i=Fe(e,n))||i.enumerable});return r};var Ve=(r,e,t)=>(t=r!=null?ze(We(r)):{},he(e||!r||!r.__esModule?z(t,"default",{value:r,enumerable:!0}):t,r)),Je=r=>he(z({},"__esModule",{value:!0}),r);var y=_(()=>{"use strict"});function ye(r){return r===F}function we(){return F}var F,Q=_(()=>{"use strict";y();F=Symbol("interceptor-skip-sentinel")});function Ae(r,e,t,i,n={}){let s=n.maxInvocationDepth??5;return{async execute(o){let g=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(p,l)=>{let m=d+1;if(m>s)throw new Z(m,s);if(!i)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let h=i.getAgent(p);if(!h)throw new Error(`Agent "${p}" not found for delegation`);let f={message:l.message??"",intent:l.intent,data:l.data,context:l.context,conversationId:l.conversationId??o.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:we}))(0),c=async d=>{let p=d??o;return await e.invokeAgent(p)};for(let d=r.length-1;d>=0;d--){let p=r[d],l=c;c=async m=>await p(m??o,g,l)}return await c()}}}async function ve(r,e){let t=await r.execute(e);return t===F?null:t}var Z,ke=_(()=>{"use strict";y();Q();Z=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function Ye(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function be(r){let e=r.captureAgentReplies??!0,t=r.getScope??Ye,i=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,ee.randomUUID)()),n=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,u,g)=>{let c=o.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await g();let d=o.participant;if(d){let l={id:i(o),conversationId:c,participant:d,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:n(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(l),r.onCaptured?.(l),u.logger?.debug("[capture-history] Captured inbound message",{messageId:l.id,participantId:d.id,conversationId:c})}catch(m){u.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let p=await g();if(e&&!ye(p)&&p.output!=null){let l={kind:"agent",id:u.agent.name,displayName:u.agent.name},m={id:(0,ee.randomUUID)(),conversationId:c,participant:l,content:p.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return p};return s[te]=!0,s}var ee,te,Ie=_(()=>{"use strict";y();ee=require("crypto");Q();te=Symbol.for("toolpack:capture-history")});function Re(r){return Math.ceil(r.length/4)}function Xe(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Qe(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Ze(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function xe(r,e,t,i,n={},s){let{scope:o,addressedOnlyMode:u=!0,tokenBudget:g=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:p=100,agentAliases:l}=n,m=new Set([t,...l??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:h,limit:p}),w=f.length;if(u){let A=new Set;for(let b=0;b<f.length;b++){let x=f[b];if(Ze(x,t,m)&&A.add(x.id),b<f.length-1){let R=f[b+1];R.participant.kind==="agent"&&R.participant.id===t&&A.add(x.id)}}let I=f[f.length-1];I&&A.add(I.id),f=f.filter(b=>A.has(b.id))}let S=!1;if(f.length>c&&s){let A=Math.floor(f.length/2),I=f.slice(0,A),b=f.slice(A),x=I.filter(R=>!R.metadata?.isSummary);try{let R=await s.invokeAgent({message:"summarize",data:{turns:x.map(Xe),agentName:i,agentId:t,maxTokens:Math.floor(g*.25),extractDecisions:!0}}),T=JSON.parse(R.output),v={id:`summary-${(0,Ce.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${T.turnsSummarized} earlier turns]: ${T.summary}`,timestamp:I[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[v,...b],S=!0;try{await r.append(v),await r.deleteMessages(e,I.map($=>$.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let M=f.map(A=>Qe(A,t));if(M.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:S};let N=M[M.length-1],j=[N],k=Re(N.content);for(let A=M.length-2;A>=0;A--){let I=M[A],b=Re(I.content);if(k+b>g)break;j.unshift(I),k+=b}return{messages:j,estimatedTokens:k,turnsLoaded:w,hasSummary:S}}var Ce,_e=_(()=>{"use strict";y();Ce=require("crypto")});var P,Se=_(()=>{"use strict";y();P=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var H,ne,ie,re,se,oe,a,W,Me=_(()=>{"use strict";y();H=require("crypto"),ne=.6,ie=.2,re=.2,se={low:.3,medium:.6,high:1},oe=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"},W=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},s=n[t.priority]-n[i.priority];return s!==0?s:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let s=this.chunkToBelief(n),o=(t-s.createdAt)/864e5,g=Math.exp(-o/oe)*ie+se.high*re+ne;return{...s,score:g}}).sort((n,s)=>s.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=i)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(g=>this.chunkToGoal(g.chunk));else{let u=n;if(o=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();o=o.filter(d=>d.description.toLowerCase().includes(c))}}return s?.length&&(o=o.filter(u=>s.every(g=>u.tags.includes(g)))),o.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:s,includeExpired:o=!1}=t,u=Date.now(),g=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of g){let p=this.chunkToBelief(d.chunk);if(!o&&p.expiresAt&&p.expiresAt<u||s?.length&&!s.every(w=>p.tags.includes(w)))continue;let l=(u-p.createdAt)/864e5,m=Math.exp(-l/oe),h=p.error?.3:se[p.confidence],f=d.score*ne+m*ie+h*re;f<n||c.push({...p,score:f})}return c.sort((d,p)=>p.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:s,pinned:o}=t,u=Date.now(),g={[a.type]:"reflection"};o===!0&&(g[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:g}),d=[];for(let p of c){let l=this.chunkToReflection(p.chunk);if(o===!1&&l.pinned||s?.length&&!s.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,h=Math.exp(-m/oe),f=p.score*ne+h*ie+se.medium*re;f<n||d.push({...l,score:f})}return d.sort((p,l)=>l.score-p.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of n){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<i))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=(0,H.randomUUID)();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),s={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=(0,H.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(n),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,u)])}async addReflection(e,t){let i=(0,H.randomUUID)();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),s={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function ae(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 Te(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=ae(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function De(r,e){let t=0,i=0,n=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],i+=r[o]*r[o],n+=e[o]*e[o];let s=Math.sqrt(i)*Math.sqrt(n);return s===0?0:t/s}function ce(r){return Math.ceil(r.length/4)}var de=_(()=>{"use strict";y()});var Pe,K,Be=_(()=>{"use strict";y();Pe=require("crypto");de();K=class{constructor(e,t,i,n,s,o){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=s;this.committedPinnedReflectionCount=o}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,s=e.expiresIn??e.ttlDefault;s&&(n=t+ae(s));let o=this._findSimilarInDraft(i);if(o!==null){let c=this.ops[o],d=e.confidence,p=c.confidence,l={low:0,medium:1,high:2},m=l[d]>l[p]||e.allowDowngrade&&l[d]<l[p];return this.ops[o]={...c,content:e.content,confidence:m?d:p,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${o}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,p=c.confidence,l={low:0,medium:1,high:2},m=l[d]>l[p]||e.allowDowngrade&&l[d]<l[p],h={op:"believe",content:e.content,confidence:m?d:p,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let g={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(g),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},s=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:s,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?Te(e.dueBy):void 0,i={op:"set_goal",tempId:(0,Pe.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 s=i;if(s.vector.length===0)continue;if(De(e,s.vector)>=this.deduplicationThreshold)return n}return null}}});function Ee(r,e,t){return[et(r,t),tt(r,e,t),nt(e,t),it(e),rt(e,t),st(r,e),ot(r)]}function et(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,g=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,p=[],m=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:s,tags:o});for(let f of h)p.push(at(f))}if(m&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(m,{limit:d,threshold:c,tags:o,includeExpired:g});for(let f of h)p.push(ct(f))}if(m&&(n==="reflection"||n==="all")){let h=await r.queryReflections(m,{limit:d,threshold:c,tags:o,pinned:u});for(let f of h)p.push(dt(f))}return p}}}function tt(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 nt(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 it(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 rt(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 st(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 ot(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 at(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 ct(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 dt(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 Ne=_(()=>{"use strict";y()});async function $e(r,e){let[t,i,n,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(p=>lt(p)),u=i.map(p=>`- ${p.content}`),{beliefLines:g,reflectionLines:c}=pt(n,s,e.tokenBudget);if(o.length===0&&u.length===0&&g.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return o.length>0&&(d.push("## Goals"),d.push(...o),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),g.length>0&&(d.push("## Beliefs"),d.push(...g),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
+ `)}function lt(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 pt(r,e,t){let i=t,n=[],s=[];for(let o of r){let u=`- ${o.content} (${o.confidence} confidence)`,g=ce(u);if(g>i)break;n.push(u),i-=g}for(let o of e){let g=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,c=ce(g);if(c>i)break;s.push(g),i-=c}return{beliefLines:n,reflectionLines:s}}var Ge=_(()=>{"use strict";y();de()});var Oe={};X(Oe,{AgentMind:()=>le});function kt(r,e){let t=Math.min(e.maxGoals??gt,At),i=Math.min(e.maxPinnedReflections??ft,vt);return{tokenBudget:e.tokenBudget??ut,recencyWindowDays:e.recencyWindowDays??mt,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??ht,retrievalThreshold:e.retrievalThreshold??yt,ttlDefaults:{belief:e.ttlDefaults?.belief??wt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var ut,mt,gt,ft,ht,yt,wt,At,vt,le,Le=_(()=>{"use strict";y();Me();Be();Ne();Ge();ut=300,mt=7,gt=10,ft=10,ht=.85,yt=.35,wt="30d",At=10,vt=10,le=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new o({namespace:u})}let n=kt(e,t),s=new W(i,t.embedder);return await s.initialize(),new r(s,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),$e(this.store,this.config)]),n=new K(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),s=Ee(this.store,n,this.config);return{mindHeader:i,tools:s,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});var ue={};X(ue,{EphemeralAgent:()=>pe});var pe,me=_(()=>{"use strict";y();V();pe=class extends E{name;description;mode;constructor(e,t,i,n){super(n),this.name=e,this.description=t,this.mode=i}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0})}}});var Ue,B,E,V=_(()=>{"use strict";y();Ue=require("events"),B=require("toolpack-sdk");ke();Ie();_e();Se();E=class extends Ue.EventEmitter{provider;model;workflow;mind;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new B.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 B.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(()=>(Le(),Oe));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let s,o="",u=[];if(this._mind){let g=await this._mind.createRunContext();o=g.mindHeader,u=g.tools,s=g.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let g=[];if(o&&g.push({role:"system",content:o}),n)try{let l=await xe(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),m=l.messages[l.messages.length-1],h=e.trim(),w=h!==""&&m?.role==="user"&&typeof m.content=="string"&&(m.content===h||m.content.endsWith(`: ${h}`))?l.messages.slice(0,-1):l.messages;g.push(...w)}catch{}e.trim()&&g.push({role:"user",content:e});let c=[...u];if(n){let l=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async m=>{let h=await l.search(n,String(m.query??""),{limit:typeof m.limit=="number"?m.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let l=this.delegation.allowedAgents,m=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(l===void 0||l.includes(h.name)));if(m.length>0){let h=m.map(w=>w.name),f=m.map(w=>`- ${w.name}: ${w.description}`).join(`
3
3
  `);this.delegation.mode==="forget"?c.push({name:"delegate_and_forget",displayName:"Delegate and Forget",description:`Hand off the current task to a peer agent. The agent will handle its own delivery (e.g. posting to Slack or GitHub) \u2014 you do not need to relay its response. Call this ONCE, then output an empty string.
4
4
 
5
5
  Available agents:
6
- ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let 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.
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 S=String(w.agent),M=String(w.message??"");return this._registry.invoke(S,{message:M,conversationId:n,context:{delegatedBy:this.name}}).catch(N=>{console.error(`[${this.name}] delegate_and_forget to ${S} failed:`,N)}),{status:"delegated",agent:S}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
7
7
 
8
8
  Available agents:
9
- ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let 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.
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 S=String(w.agent),M=String(w.message??"");return this._registry.invoke(S,{message:M,conversationId:n,context:{delegatedBy:this.name}})}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let l=i?.spawnDepth??0,m=this.spawn,h=m.maxDepth??3;if(l<h){let f=m.templates,w=f.some(k=>k.name==="self"),S=f.some(k=>k.allowPromptAddition),M=f.filter(k=>k.name!=="self").map(k=>`- ${k.name}: ${k.description}`).join(`
10
+ `),N=w?`Use template name "self" to spawn a replica of the current agent.
11
+ `:"",j=S?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};c.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
12
+
13
+ Available templates:
14
+ ${M}
15
+ `+N+`Spawn depth: ${l}/${h}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:w?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...j},required:["template","task"]},execute:async k=>{let A=String(k.template),I=String(k.task??""),b,x,R,T,v=f.find(D=>D.name===A);if(!v)throw new Error(`Unknown spawn template: "${A}"`);let $=v.allowPromptAddition&&k.systemPromptAddition?`
16
+
17
+ ${String(k.systemPromptAddition)}`:"";if(A==="self"){let D=typeof this.mode=="string"?{...B.AGENT_MODE,name:this.mode}:this.mode,L=v.systemPrompt(I);b={...D,name:`${D.name}-replica-${Date.now()}`,systemPrompt:(D.systemPrompt??"")+(L?`
18
+
19
+ ${L}`:"")+$},x=`${this.name}-replica`,R=this.description,T=this.model}else b={...B.AGENT_MODE,name:`ephemeral-${v.name}-${Date.now()}`,systemPrompt:v.systemPrompt(I)+$},x=v.name,R=v.description,T=v.model;let{EphemeralAgent:U}=await Promise.resolve().then(()=>(me(),ue)),G=new U(x,R,b,{toolpack:this.toolpack});T&&(G.model=T),G.spawn={...m};let O=await G.invokeAgent({message:I,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:l+1}});return{output:O.output,spawnedTemplate:A,depth:l+1,metadata:O.metadata}}}),c.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
20
+
21
+ Available templates:
22
+ ${M}
23
+ `+N+`Spawn depth: ${l}/${h}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:w?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...S?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async k=>{let A=k.tasks;if(!Array.isArray(A)||A.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:I}=await Promise.resolve().then(()=>(me(),ue));return{results:await Promise.all(A.map(async x=>{let R=String(x.template),T=String(x.task??""),v=f.find(q=>q.name===R);if(!v)throw new Error(`Unknown spawn template: "${R}"`);let $=v.allowPromptAddition&&x.systemPromptAddition?`
24
+
25
+ ${String(x.systemPromptAddition)}`:"",U,G,O,D;if(R==="self"){let q=typeof this.mode=="string"?{...B.AGENT_MODE,name:this.mode}:this.mode,fe=v.systemPrompt(T);U={...q,name:`${q.name}-replica-${Date.now()}`,systemPrompt:(q.systemPrompt??"")+(fe?`
26
+
27
+ ${fe}`:"")+$},G=`${this.name}-replica`,O=this.description,D=this.model}else U={...B.AGENT_MODE,name:`ephemeral-${v.name}-${Date.now()}`,systemPrompt:v.systemPrompt(T)+$},G=v.name,O=v.description,D=v.model;let L=new I(G,O,U,{toolpack:this.toolpack});D&&(L.model=D),L.spawn={...m};let ge=await L.invokeAgent({message:T,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:l+1}});return{output:ge.output,spawnedTemplate:R,depth:l+1,metadata:ge.metadata}}))}}})}}let d=await this.toolpack.generate({messages:g,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode},this.provider),p={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(p),s&&await s(!1),this.emit("agent:complete",p),p}catch(g){throw s&&s(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(g),this.emit("agent:error",g),g}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new P("Agent not registered - cannot use ask()");if(!this._conversationId)throw new P("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new P("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 P("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 P("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
10
28
 
11
29
  Question: "${e}"
12
30
  Answer: "${t}"
13
31
 
14
- Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:s=>s.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new 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(`
32
+ Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,i,n){return await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3})?(await this.resolvePendingAsk(e.id,t),i(t)):e.retries>=e.maxRetries?(await this.resolvePendingAsk(e.id,"__insufficient__"),this._triggeringChannel&&await this.sendTo(this._triggeringChannel,"I was unable to get enough information to proceed. Skipping this step."),n?n():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}):(this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries}))}async delegateAndWait(e,t){if(!this._registry)throw new P("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[te]===!0)?this.interceptors:[be({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=Ae(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await ve(n,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(n){let s=n instanceof Error?n.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{i()}})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,i=new Promise(n=>{t=n});return this._conversationLocks.set(e,i),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let i=t.plan;if(Array.isArray(i.steps))return i.steps.map(n=>({number:n.number||0,description:n.description||"",status:n.status||"completed",result:n.result}))}if(Array.isArray(t.steps))return t.steps}}});var Rt={};X(Rt,{IntentClassifierAgent:()=>J,SummarizerAgent:()=>Y});module.exports=Je(Rt);y();y();V();var qe=require("toolpack-sdk"),bt={...qe.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(`
33
+ `)},J=class extends E{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=bt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let i=[];if(i.push(`Context: Public channel #${t.channelName}`),i.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),i.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){i.push(`
16
34
  Recent conversation:`);for(let u of t.recentContext)i.push(` ${u.sender}: ${u.content.substring(0,100)}`)}i.push(`
17
35
  Message to classify: "${t.message}"`),t.includeExamples&&(i.push(`
18
36
  Examples of classifications:`),i.push(` "@${t.agentName} help me" \u2192 direct`),i.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),i.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),i.push(' "Check the logs" \u2192 ignore')),i.push(`
19
37
  Classification (start with direct, indirect, passive, or ignore):`);let n=i.join(`
20
- `),o=await this.run(n),s=this.normalizeClassification(o.output);return{output:s,metadata:{rawOutput:o.output,classification:s,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();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});
38
+ `),s=await this.run(n),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],i=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:i.includes("indirect")||i.includes("mention")?"indirect":i.includes("passive")||i.includes("listen")?"passive":i.includes("ignore")||i.includes("skip")?"ignore":i.includes("direct")||i.includes("addressed")?"direct":"ignore"}};y();V();var je=require("toolpack-sdk"),It={...je.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(`
39
+ `)},Y=class extends E{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=It;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let i=t.maxTokens??800,n=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${i} tokens`,`Extract decisions/action items: ${n?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let c of t.turns){let d=new Date(c.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),p=c.participant.displayName??c.participant.id,l=c.participant.kind==="agent"?`[BOT] ${p}`:p,m=`[${d}] ${l}: ${c.content.substring(0,200)}`;c.content.length>200&&(m+="..."),c.metadata?.isToolCall&&c.metadata.toolName&&(m+=` [tool: ${c.metadata.toolName}]`),s.push(m)}s.push("","Generate a JSON summary object:");let o=s.join(`
40
+ `),u=await this.run(o),g=this.parseSummarizerOutput(u.output,t.turns.length);return{output:JSON.stringify(g),metadata:{turnsProcessed:t.turns.length,rawOutputLength:u.output.length}}}parseSummarizerOutput(e,t){let i=e.trim(),n=i.match(/```(?:json)?\s*([\s\S]*?)\s*```/);n&&(i=n[1].trim());try{let s=JSON.parse(i);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
@@ -1,6 +1,6 @@
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';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-CPKmOVJx.cjs';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C3EZvpe0.cjs';
3
+ import { B as BaseAgent } from '../base-agent-Dqca3WLY.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-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';
1
+ export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-ACQSotfT.js';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C3EZvpe0.js';
3
+ import { B as BaseAgent } from '../base-agent-C4fYjHPu.js';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';