@toolpack-sdk/agents 2.1.1 → 2.3.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.
Files changed (32) hide show
  1. package/README.md +72 -4
  2. package/dist/{base-agent-DPdK4Pnl.d.cts → base-agent-65162dq7.d.cts} +1 -1
  3. package/dist/{base-agent-nU8pr4nu.d.ts → base-agent-DzspMyaG.d.ts} +1 -1
  4. package/dist/capabilities/index.cjs +2 -2
  5. package/dist/capabilities/index.d.cts +3 -3
  6. package/dist/capabilities/index.d.ts +3 -3
  7. package/dist/capabilities/index.js +3 -3
  8. package/dist/channels/index.cjs +2 -2
  9. package/dist/channels/index.d.cts +2 -2
  10. package/dist/channels/index.d.ts +2 -2
  11. package/dist/channels/index.js +2 -2
  12. package/dist/eval-report-BUD6NRiP.d.cts +343 -0
  13. package/dist/eval-report-C6dSvR3Y.d.ts +343 -0
  14. package/dist/{index-Du6S0eG7.d.cts → index-BxUlu-qG.d.ts} +76 -2
  15. package/dist/{index-o8Lbzv5N.d.ts → index-DrigwC1A.d.cts} +76 -2
  16. package/dist/index.cjs +40 -26
  17. package/dist/index.d.cts +9 -8
  18. package/dist/index.d.ts +9 -8
  19. package/dist/index.js +40 -26
  20. package/dist/{intent-classifier-agent-DxyfJWcm.d.cts → intent-classifier-agent-D0rWtviD.d.cts} +2 -2
  21. package/dist/{intent-classifier-agent-0JZDlhpk.d.ts → intent-classifier-agent-mmNoAozf.d.ts} +2 -2
  22. package/dist/interceptors/index.cjs +1 -1
  23. package/dist/interceptors/index.d.cts +92 -5
  24. package/dist/interceptors/index.d.ts +92 -5
  25. package/dist/interceptors/index.js +1 -1
  26. package/dist/testing/index.cjs +16 -2
  27. package/dist/testing/index.d.cts +3 -2
  28. package/dist/testing/index.d.ts +3 -2
  29. package/dist/testing/index.js +16 -2
  30. package/dist/{types-TB6yypig.d.cts → types-C3eW-auY.d.cts} +6 -8
  31. package/dist/{types-TB6yypig.d.ts → types-C3eW-auY.d.ts} +6 -8
  32. package/package.json +18 -9
package/README.md CHANGED
@@ -8,12 +8,14 @@ Build production-ready AI agents with channels, workflows, and event-driven arch
8
8
  ## Features
9
9
 
10
10
  - **4 Built-in Agents** — Research, Coding, Data, Browser
11
- - **7 Channel Types** — Slack, Telegram, Discord, Email, SMS, Webhook, Scheduled
11
+ - **8 Channel Types** — Slack, Telegram, Discord, Email, SMS, Webhook, Scheduled, MCP
12
12
  - **Event-Driven** — Full lifecycle hooks and events
13
13
  - **Human-in-the-Loop** — `ask()` support for two-way channels
14
14
  - **Knowledge Integration** — Built-in RAG support with knowledge bases
15
+ - **Agent Mind** — Persistent cognitive layer: goals, beliefs, reflections, cross-run recall
16
+ - **Evals** — `EvalDataset`, `EvalRunner`, 4 scorer types, regression reports
17
+ - **OTel Tracing** — OpenTelemetry interceptor for distributed traces
15
18
  - **Type-Safe** — Full TypeScript support
16
- - **Production-Ready** — 573 tests passing
17
19
 
18
20
  ## Installation
19
21
 
@@ -239,6 +241,27 @@ const smsOutbound = new SMSChannel({
239
241
  });
240
242
  ```
241
243
 
244
+ ### McpChannel (Two-way)
245
+
246
+ Exposes a Toolpack agent as a tool in an MCP server. The agent appears in `tools/list` as `agent.<name>` and is callable by any MCP client.
247
+
248
+ ```typescript
249
+ import { McpChannel } from '@toolpack-sdk/agents';
250
+ import { Toolpack } from 'toolpack-sdk';
251
+
252
+ const ch = new McpChannel({ name: 'mcp' });
253
+ const agent = new PrReviewerAgent({ channels: [ch] });
254
+ await agent.start();
255
+
256
+ const sdk = await Toolpack.init({ provider: 'anthropic', tools: true });
257
+ await sdk.startMcpServer({
258
+ transport: 'stdio', // or 'http' with port
259
+ agents: [ch.asAgentDefinition(agent)],
260
+ });
261
+ ```
262
+
263
+ `ch.asAgentDefinition(agent)` produces the entry that `startMcpServer` registers in `tools/list`. Each MCP `tools/call` for `agent.<name>` is routed through the channel to `agent.invokeAgent()` and the output is returned as the tool result.
264
+
242
265
  ## Creating Custom Agents
243
266
 
244
267
  Extend `BaseAgent` to create custom agents:
@@ -763,6 +786,7 @@ class MyAgent extends BaseAgent {
763
786
  | `createCaptureInterceptor` | Persist inbound and outbound messages to conversation history (auto-registered) |
764
787
  | `createDepthGuardInterceptor` | Reject delegation chains that exceed a configured depth |
765
788
  | `createTracerInterceptor` | Structured logging of each chain hop for debugging |
789
+ | `createOTelTracerInterceptor` | OpenTelemetry span per invocation — compatible with any OTel-compliant backend |
766
790
 
767
791
  ## Capabilities
768
792
 
@@ -818,14 +842,58 @@ const result = await summarizer.invokeAgent({
818
842
  const summary = JSON.parse(result.output) as SummarizerOutput;
819
843
  ```
820
844
 
845
+ ## Evals — LLM Quality Evaluation
846
+
847
+ Unit tests verify wiring; evals verify agent **quality**. Use the eval primitives to build regression suites and track answer quality over time.
848
+
849
+ ```typescript
850
+ import {
851
+ EvalDataset,
852
+ EvalRunner,
853
+ ContainsScorer,
854
+ LLMJudgeScorer,
855
+ compareEvalRuns,
856
+ formatEvalReport,
857
+ } from '@toolpack-sdk/agents';
858
+
859
+ const dataset = new EvalDataset([
860
+ { id: 'q1', input: 'What is 2+2?', expectedOutput: '4' },
861
+ { id: 'q2', input: 'Capital of France?', expectedOutput: 'Paris' },
862
+ ]);
863
+
864
+ const runner = new EvalRunner({
865
+ agent: myAgent,
866
+ dataset,
867
+ scorers: [new ContainsScorer()],
868
+ });
869
+
870
+ const run = await runner.run();
871
+ console.log(`Average score: ${(run.averageScore * 100).toFixed(1)}%`);
872
+ ```
873
+
874
+ **Four built-in scorers:**
875
+
876
+ | Scorer | When to use |
877
+ |---|---|
878
+ | `ExactMatchScorer` | Deterministic outputs — exact string match |
879
+ | `ContainsScorer` | Output must contain the expected string |
880
+ | `LLMJudgeScorer` | Open-ended answers — ask an LLM to grade on 0–1 |
881
+ | `CustomScorer` | Any custom scoring logic |
882
+
883
+ **Regression detection:**
884
+
885
+ ```typescript
886
+ const report = compareEvalRuns(baselineRun, currentRun);
887
+ console.log(formatEvalReport(report));
888
+ expect(report.regressions).toHaveLength(0); // CI gate
889
+ ```
890
+
821
891
  ## Testing
822
892
 
823
893
  ```bash
824
894
  npm test
825
895
  ```
826
896
 
827
- **Test Coverage:** 573 tests passing across 29 test files.
828
-
829
897
  ## License
830
898
 
831
899
  Apache 2.0 © Toolpack SDK
@@ -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 ChannelInterface, I as Interceptor, c as IAgentRegistry, B as BaseAgentOptions, d as AgentRunOptions, P as PendingAsk } from './types-C3eW-auY.cjs';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -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 ChannelInterface, I as Interceptor, c as IAgentRegistry, B as BaseAgentOptions, d as AgentRunOptions, P as PendingAsk } from './types-C3eW-auY.js';
4
4
  import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
5
5
 
6
6
  type GoalStatus = 'active' | 'completed';
@@ -1,12 +1,12 @@
1
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(`
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 Ae=x(()=>{"use strict";y();Y()});var ve={};te(ve,{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();Ae();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 v=new Set;for(let b=0;b<f.length;b++){let M=f[b];if(Ge(M,t,g)&&v.add(M.id),b<f.length-1){let _=f[b+1];_.participant.kind==="agent"&&_.participant.id===t&&v.add(M.id)}}let R=f[f.length-1];R&&v.add(R.id),f=f.filter(b=>v.has(b.id))}let k=!1;if(f.length>c&&o){let v=Math.floor(f.length/2),R=f.slice(0,v),b=f.slice(v),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(v=>Ne(v,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 v=I.length-2;v>=0;v--){let R=I[v],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(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(()=>(be(),ve));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await le(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
3
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
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.
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 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,mode:this.mode},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.
10
10
 
11
11
  Question: "${e}"
12
12
  Answer: "${t}"
@@ -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-D0rWtviD.cjs';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C3eW-auY.cjs';
3
+ import { B as BaseAgent } from '../base-agent-65162dq7.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-mmNoAozf.js';
2
+ import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C3eW-auY.js';
3
+ import { B as BaseAgent } from '../base-agent-DzspMyaG.js';
4
4
  import { Participant, ModeConfig } from 'toolpack-sdk';
5
5
  export { Participant } from 'toolpack-sdk';
6
6
  import 'events';
@@ -1,12 +1,12 @@
1
- var we=Object.defineProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var ve=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})};import it from"path";import{fileURLToPath as ot}from"url";var y=_(()=>{"use strict"});import{randomUUID as $}from"crypto";var L,U,q,j,z,a,B,ae=_(()=>{"use strict";y();L=.6,U=.2,q=.2,j={low:.3,medium:.6,high:1},z=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},B=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},o=n[t.priority]-n[i.priority];return o!==0?o:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let o=this.chunkToBelief(n),s=(t-o.createdAt)/864e5,p=Math.exp(-s/z)*U+j.high*q+L;return{...o,score:p}}).sort((n,o)=>o.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(o=>o[a.type]==="reflection"&&!o[a.pinned]&&!o[a.error]&&o[a.createdAt]>=i)).map(o=>this.chunkToReflection(o)).sort((o,s)=>s.createdAt-o.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:o}=t,s;if(e.trim()&&typeof this.provider.keywordQuery=="function")s=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(p=>this.chunkToGoal(p.chunk));else{let u=n;if(s=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();s=s.filter(d=>d.description.toLowerCase().includes(c))}}return o?.length&&(s=s.filter(u=>o.every(p=>u.tags.includes(p)))),s.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:o,includeExpired:s=!1}=t,u=Date.now(),p=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of p){let l=this.chunkToBelief(d.chunk);if(!s&&l.expiresAt&&l.expiresAt<u||o?.length&&!o.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,g=Math.exp(-m/z),h=l.error?.3:j[l.confidence],f=d.score*L+g*U+h*q;f<n||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:o,pinned:s}=t,u=Date.now(),p={[a.type]:"reflection"};s===!0&&(p[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:p}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(s===!1&&m.pinned||o?.length&&!o.every(w=>m.tags.includes(w)))continue;let g=(u-m.createdAt)/864e5,h=Math.exp(-g/z),f=l.score*L+h*U+j.medium*q;f<n||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let o of n){let s=this.chunkToBelief(o.chunk);if(!(s.expiresAt&&s.expiresAt<i))return{id:o.chunk.id,score:o.score,belief:s}}return null}async addGoal(e){let t=$();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),o={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(o)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=$();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let o=this.chunkToBelief(n),s={...o,content:t.content??o.content,confidence:t.confidence??o.confidence,tags:t.tags??o.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:o.expiresAt,error:t.error??o.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(s,u)])}async addReflection(e,t){let i=$();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),o={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(o,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function F(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function ce(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=F(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function de(r,e){let t=0,i=0,n=0;for(let s=0;s<r.length;s++)t+=r[s]*e[s],i+=r[s]*r[s],n+=e[s]*e[s];let o=Math.sqrt(i)*Math.sqrt(n);return o===0?0:t/o}function H(r){return Math.ceil(r.length/4)}var W=_(()=>{"use strict";y()});import{randomUUID as Ce}from"crypto";var E,le=_(()=>{"use strict";y();W();E=class{constructor(e,t,i,n,o,s){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=o;this.committedPinnedReflectionCount=s}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,o=e.expiresIn??e.ttlDefault;o&&(n=t+F(o));let s=this._findSimilarInDraft(i);if(s!==null){let c=this.ops[s],d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l];return this.ops[s]={...c,content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${s}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l],h={op:"believe",content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let s=this.totalPinnedReflectionCount;if(s>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);s>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${s+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},o=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:o,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?ce(e.dueBy):void 0,i={op:"set_goal",tempId:Ce(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let o=i;if(o.vector.length===0)continue;if(de(e,o.vector)>=this.deduplicationThreshold)return n}return null}}});function ue(r,e,t){return[xe(r,t),_e(r,e,t),Me(e,t),Se(e),Te(e,t),De(r,e),Pe(r)]}function xe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",o=t.status??"active",s=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,p=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:o,tags:s});for(let f of h)l.push(Be(f))}if(g&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(g,{limit:d,threshold:c,tags:s,includeExpired:p});for(let f of h)l.push(Ee(f))}if(g&&(n==="reflection"||n==="all")){let h=await r.queryReflections(g,{limit:d,threshold:c,tags:s,pinned:u});for(let f of h)l.push(Ne(f))}return l}}}function _e(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Me(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function Se(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function Te(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function De(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function Pe(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Be(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function Ee(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function Ne(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var pe=_(()=>{"use strict";y()});async function me(r,e){let[t,i,n,o]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),s=t.map(l=>Ge(l)),u=i.map(l=>`- ${l.content}`),{beliefLines:p,reflectionLines:c}=Oe(n,o,e.tokenBudget);if(s.length===0&&u.length===0&&p.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return s.length>0&&(d.push("## Goals"),d.push(...s),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),p.length>0&&(d.push("## Beliefs"),d.push(...p),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
- `)}function Ge(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function Oe(r,e,t){let i=t,n=[],o=[];for(let s of r){let u=`- ${s.content} (${s.confidence} confidence)`,p=H(u);if(p>i)break;n.push(u),i-=p}for(let s of e){let p=`- [${new Date(s.createdAt).toISOString().slice(0,10)}] ${s.content}`,c=H(p);if(c>i)break;o.push(p),i-=c}return{beliefLines:n,reflectionLines:o}}var ge=_(()=>{"use strict";y();W()});var fe={};ve(fe,{AgentMind:()=>K});function Ke(r,e){let t=Math.min(e.maxGoals??Ue,He),i=Math.min(e.maxPinnedReflections??qe,We);return{tokenBudget:e.tokenBudget??$e,recencyWindowDays:e.recencyWindowDays??Le,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??je,retrievalThreshold:e.retrievalThreshold??ze,ttlDefaults:{belief:e.ttlDefaults?.belief??Fe,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var $e,Le,Ue,qe,je,ze,Fe,He,We,K,he=_(()=>{"use strict";y();ae();le();pe();ge();$e=300,Le=7,Ue=10,qe=10,je=.85,ze=.35,Fe="30d",He=10,We=10,K=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:s}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new s({namespace:u})}let n=Ke(e,t),o=new B(i,t.embedder);return await o.initialize(),new r(o,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),me(this.store,this.config)]),n=new E(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),o=ue(this.store,n,this.config);return{mindHeader:i,tools:o,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});y();y();y();import{EventEmitter as Ve}from"events";import{Toolpack as Je,InMemoryConversationStore as Ye}from"toolpack-sdk";y();y();var P=Symbol("interceptor-skip-sentinel");function Z(r){return r===P}function ee(){return P}var G=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function te(r,e,t,i,n={}){let o=n.maxInvocationDepth??5;return{async execute(s){let p=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>o)throw new G(g,o);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let h=i.getAgent(l);if(!h)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:ee}))(0),c=async d=>{let l=d??s;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??s,p,m)}return await c()}}}async function ne(r,e){let t=await r.execute(e);return t===P?null:t}y();import{randomUUID as ie}from"crypto";function Ae(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var O=Symbol.for("toolpack:capture-history");function re(r){let e=r.captureAgentReplies??!0,t=r.getScope??Ae,i=r.getMessageId??(s=>s.context?.messageId??s.context?.eventId??ie()),n=r.getMentions??(s=>s.context?.mentions??[]),o=async(s,u,p)=>{let c=s.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await p();let d=s.participant;if(d){let m={id:i(s),conversationId:c,participant:d,content:s.message??"",timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:n(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){u.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await p();if(e&&!Z(l)&&l.output!=null){let m={kind:"agent",id:u.agent.name,displayName:u.agent.name},g={id:ie(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return l};return o[O]=!0,o}y();import{randomUUID as be}from"crypto";function oe(r){return Math.ceil(r.length/4)}function ke(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Ie(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Re(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function se(r,e,t,i,n={},o){let{scope:s,addressedOnlyMode:u=!0,tokenBudget:p=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:s,sinceTimestamp:h,limit:l}),w=f.length;if(u){let b=new Set;for(let k=0;k<f.length;k++){let T=f[k];if(Re(T,t,g)&&b.add(T.id),k<f.length-1){let M=f[k+1];M.participant.kind==="agent"&&M.participant.id===t&&b.add(T.id)}}let C=f[f.length-1];C&&b.add(C.id),f=f.filter(k=>b.has(k.id))}let I=!1;if(f.length>c&&o){let b=Math.floor(f.length/2),C=f.slice(0,b),k=f.slice(b),T=C.filter(M=>!M.metadata?.isSummary);try{let M=await o.invokeAgent({message:"summarize",data:{turns:T.map(ke),agentName:i,agentId:t,maxTokens:Math.floor(p*.25),extractDecisions:!0}}),X=JSON.parse(M.output),Q={id:`summary-${be()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${X.turnsSummarized} earlier turns]: ${X.summary}`,timestamp:C[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};f=[Q,...k],I=!0;try{await r.append(Q),await r.deleteMessages(e,C.map(ye=>ye.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let R=f.map(b=>Ie(b,t));if(R.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:I};let D=R[R.length-1],Y=[D],N=oe(D.content);for(let b=R.length-2;b>=0;b--){let C=R[b],k=oe(C.content);if(N+k>p)break;Y.unshift(C),N+=k}return{messages:Y,estimatedTokens:N,turnsLoaded:w,hasSummary:I}}y();var x=class extends Error{constructor(e){super(e),this.name="AgentError"}};var S=class extends Ve{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Ye,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Je.init({provider:this._initConfig.provider??"anthropic",apiKey:this._initConfig.apiKey,model:this._initConfig.model}),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(he(),fe));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await se(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
1
+ var we=Object.defineProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var Ae=(r,e)=>{for(var t in e)we(r,t,{get:e[t],enumerable:!0})};import it from"path";import{fileURLToPath as ot}from"url";var y=_(()=>{"use strict"});import{randomUUID as $}from"crypto";var L,U,q,j,z,a,B,ae=_(()=>{"use strict";y();L=.6,U=.2,q=.2,j={low:.3,medium:.6,high:1},z=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},B=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,i)=>{let n={high:0,normal:1,low:2},o=n[t.priority]-n[i.priority];return o!==0?o:t.createdAt-i.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(n=>n[a.type]==="belief"&&n[a.confidence]==="high"&&!n[a.error]&&!(n[a.expiresAt]&&n[a.expiresAt]<t))).map(n=>{let o=this.chunkToBelief(n),s=(t-o.createdAt)/864e5,p=Math.exp(-s/z)*U+j.high*q+L;return{...o,score:p}}).sort((n,o)=>o.score-n.score).slice(0,e)}async getRecentReflections(e,t){let i=Date.now()-e*864e5;return(await this._getAllByMeta(o=>o[a.type]==="reflection"&&!o[a.pinned]&&!o[a.error]&&o[a.createdAt]>=i)).map(o=>this.chunkToReflection(o)).sort((o,s)=>s.createdAt-o.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:i=10,status:n="active",tags:o}=t,s;if(e.trim()&&typeof this.provider.keywordQuery=="function")s=(await this.provider.keywordQuery(e,{limit:i*2,threshold:0,filter:{[a.type]:"goal",[a.status]:n}})).map(p=>this.chunkToGoal(p.chunk));else{let u=n;if(s=(await this._getAllByMeta(c=>c[a.type]==="goal"&&c[a.status]===u)).map(c=>this.chunkToGoal(c)),e.trim()){let c=e.toLowerCase();s=s.filter(d=>d.description.toLowerCase().includes(c))}}return o?.length&&(s=s.filter(u=>o.every(p=>u.tags.includes(p)))),s.slice(0,i)}async queryBeliefs(e,t){let{limit:i=10,threshold:n=0,tags:o,includeExpired:s=!1}=t,u=Date.now(),p=await this.provider.query(e,{limit:i*4,threshold:0,filter:{[a.type]:"belief"}}),c=[];for(let d of p){let l=this.chunkToBelief(d.chunk);if(!s&&l.expiresAt&&l.expiresAt<u||o?.length&&!o.every(w=>l.tags.includes(w)))continue;let m=(u-l.createdAt)/864e5,g=Math.exp(-m/z),h=l.error?.3:j[l.confidence],f=d.score*L+g*U+h*q;f<n||c.push({...l,score:f})}return c.sort((d,l)=>l.score-d.score).slice(0,i)}async queryReflections(e,t){let{limit:i=10,threshold:n=0,tags:o,pinned:s}=t,u=Date.now(),p={[a.type]:"reflection"};s===!0&&(p[a.pinned]=!0);let c=await this.provider.query(e,{limit:i*4,threshold:0,filter:p}),d=[];for(let l of c){let m=this.chunkToReflection(l.chunk);if(s===!1&&m.pinned||o?.length&&!o.every(w=>m.tags.includes(w)))continue;let g=(u-m.createdAt)/864e5,h=Math.exp(-g/z),f=l.score*L+h*U+j.medium*q;f<n||d.push({...m,score:f})}return d.sort((l,m)=>m.score-l.score).slice(0,i)}async findSimilarBelief(e,t){let i=Date.now(),n=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let o of n){let s=this.chunkToBelief(o.chunk);if(!(s.expiresAt&&s.expiresAt<i))return{id:o.chunk.id,score:o.score,belief:s}}return null}async addGoal(e){let t=$();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i),o={...n,description:t.description??n.description,priority:t.priority??n.priority,status:t.status??n.status,outcome:t.outcome??n.outcome,progress:t.appendProgress?[...n.progress,t.appendProgress]:n.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(o)])}async completeGoal(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Goal not found: ${e}`);let n=this.chunkToGoal(i);await this.provider.add([this.goalToChunk({...n,status:"completed",outcome:t??n.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let i=$();return await this.provider.add([this.beliefToChunk({...e,id:i},t)]),i}async updateBelief(e,t,i){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Belief not found: ${e}`);let o=this.chunkToBelief(n),s={...o,content:t.content??o.content,confidence:t.confidence??o.confidence,tags:t.tags??o.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:o.expiresAt,error:t.error??o.error,updatedAt:Date.now()},u=i??n.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(s,u)])}async addReflection(e,t){let i=$();return await this.provider.add([this.reflectionToChunk({...e,id:i},t)]),i}async updateReflection(e,t){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Reflection not found: ${e}`);let n=this.chunkToReflection(i),o={...n,pinned:t.pinned??n.pinned,error:t.error??n.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(o,i.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(i=>i.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(i=>e(i.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function F(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),i=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[i]}function ce(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=F(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function de(r,e){let t=0,i=0,n=0;for(let s=0;s<r.length;s++)t+=r[s]*e[s],i+=r[s]*r[s],n+=e[s]*e[s];let o=Math.sqrt(i)*Math.sqrt(n);return o===0?0:t/o}function H(r){return Math.ceil(r.length/4)}var W=_(()=>{"use strict";y()});import{randomUUID as Ce}from"crypto";var E,le=_(()=>{"use strict";y();W();E=class{constructor(e,t,i,n,o,s){this.store=e;this.deduplicationThreshold=t;this.maxGoals=i;this.maxPinnedReflections=n;this.committedGoalCount=o;this.committedPinnedReflectionCount=s}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),i=await this.store.embed(e.content),n,o=e.expiresIn??e.ttlDefault;o&&(n=t+F(o));let s=this._findSimilarInDraft(i);if(s!==null){let c=this.ops[s],d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l];return this.ops[s]={...c,content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,vector:i},{action:"updated_draft",id:c.existingId??`draft-${s}`}}let u=await this.store.findSimilarBelief(i,this.deduplicationThreshold);if(u){let c=u.belief,d=e.confidence,l=c.confidence,m={low:0,medium:1,high:2},g=m[d]>m[l]||e.allowDowngrade&&m[d]<m[l],h={op:"believe",content:e.content,confidence:g?d:l,tags:e.tags.length>0?e.tags:c.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i,existingId:u.id};return this.ops.push(h),{action:"updated_store",id:u.id}}let p={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:n,allowDowngrade:e.allowDowngrade,createdAt:t,vector:i};return this.ops.push(p),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let s=this.totalPinnedReflectionCount;if(s>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);s>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${s+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let i=await this.store.embed(e.content),n={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:i},o=`draft-reflect-${this.ops.length}`;return this.ops.push(n),{id:o,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?ce(e.dueBy):void 0,i={op:"set_goal",tempId:Ce(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(i),{id:i.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let i of this.ops)if(i.op==="believe"){let n=i;e?n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,error:!0,createdAt:n.createdAt,updatedAt:t},n.vector):n.existingId?await this.store.updateBelief(n.existingId,{content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt},n.vector):await this.store.addBelief({type:"belief",content:n.content,confidence:n.confidence,tags:n.tags,expiresAt:n.expiresAt,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="reflect"){let n=i;await this.store.addReflection({type:"reflection",content:n.content,pinned:n.pinned,tags:n.tags,relatedTo:n.relatedTo,error:e||void 0,createdAt:n.createdAt,updatedAt:t},n.vector)}else if(i.op==="set_goal"){if(!e){let n=i;await this.store.addGoal({type:"goal",description:n.description,priority:n.priority,status:"active",tags:n.tags,dueBy:n.dueBy,progress:[],createdAt:n.createdAt,updatedAt:n.createdAt})}}else if(i.op==="update_goal"){if(!e){let n=i;await this.store.updateGoal(n.id,{description:n.description,priority:n.priority,appendProgress:n.progress})}}else if(i.op==="unpin_reflection"&&!e){let n=i;await this.store.updateReflection(n.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((i,n)=>({op:i,idx:n})).filter(({op:i})=>i.op==="believe");for(let{op:i,idx:n}of t){let o=i;if(o.vector.length===0)continue;if(de(e,o.vector)>=this.deduplicationThreshold)return n}return null}}});function ue(r,e,t){return[xe(r,t),_e(r,e,t),Me(e,t),Se(e),Te(e,t),De(r,e),Pe(r)]}function xe(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let i=String(t.query??""),n=t.type??"all",o=t.status??"active",s=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,p=t.includeExpired===!0,c=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,d=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,l=[],g=(n==="belief"||n==="reflection"||n==="all")&&i.trim()?await r.embed(i):null;if(n==="goal"||n==="all"){let h=await r.keywordSearchGoals(i,{limit:d,status:o,tags:s});for(let f of h)l.push(Be(f))}if(g&&(n==="belief"||n==="all")){let h=await r.queryBeliefs(g,{limit:d,threshold:c,tags:s,includeExpired:p});for(let f of h)l.push(Ee(f))}if(g&&(n==="reflection"||n==="all")){let h=await r.queryReflections(g,{limit:d,threshold:c,tags:s,pinned:u});for(let f of h)l.push(Ne(f))}return l}}}function _e(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async i=>({status:"ok",...await e.addBelieve({content:String(i.content),confidence:i.confidence??"medium",tags:Array.isArray(i.tags)?i.tags.map(String):[],expiresIn:i.expiresIn?String(i.expiresIn):void 0,allowDowngrade:i.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function Me(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function Se(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function Te(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function De(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function Pe(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function Be(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function Ee(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function Ne(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var pe=_(()=>{"use strict";y()});async function me(r,e){let[t,i,n,o]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),s=t.map(l=>Ge(l)),u=i.map(l=>`- ${l.content}`),{beliefLines:p,reflectionLines:c}=Oe(n,o,e.tokenBudget);if(s.length===0&&u.length===0&&p.length===0&&c.length===0)return"";let d=["--- AGENT MIND ---",""];return s.length>0&&(d.push("## Goals"),d.push(...s),d.push("")),u.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...u),d.push("")),p.length>0&&(d.push("## Beliefs"),d.push(...p),d.push("")),c.length>0&&(d.push("## Recent Reflections"),d.push(...c),d.push("")),d.push("---"),d.join(`
2
+ `)}function Ge(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function Oe(r,e,t){let i=t,n=[],o=[];for(let s of r){let u=`- ${s.content} (${s.confidence} confidence)`,p=H(u);if(p>i)break;n.push(u),i-=p}for(let s of e){let p=`- [${new Date(s.createdAt).toISOString().slice(0,10)}] ${s.content}`,c=H(p);if(c>i)break;o.push(p),i-=c}return{beliefLines:n,reflectionLines:o}}var ge=_(()=>{"use strict";y();W()});var fe={};Ae(fe,{AgentMind:()=>K});function Ke(r,e){let t=Math.min(e.maxGoals??Ue,He),i=Math.min(e.maxPinnedReflections??qe,We);return{tokenBudget:e.tokenBudget??$e,recencyWindowDays:e.recencyWindowDays??Le,maxGoals:t,maxPinnedReflections:i,deduplicationThreshold:e.deduplicationThreshold??je,retrievalThreshold:e.retrievalThreshold??ze,ttlDefaults:{belief:e.ttlDefaults?.belief??Fe,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`}}var $e,Le,Ue,qe,je,ze,Fe,He,We,K,he=_(()=>{"use strict";y();ae();le();pe();ge();$e=300,Le=7,Ue=10,qe=10,je=.85,ze=.35,Fe="30d",He=10,We=10,K=class r{constructor(e,t){this.store=e;this.config=t}store;config;static async create(e,t){let i;if(t.provider)i=t.provider;else{let{PersistentKnowledgeProvider:s}=await import("@toolpack-sdk/knowledge"),u=t.namespace??`mind/${e}`;i=new s({namespace:u})}let n=Ke(e,t),o=new B(i,t.embedder);return await o.initialize(),new r(o,n)}async createRunContext(){let[e,t,i]=await Promise.all([this.store.getActiveGoalCount(),this.store.getPinnedReflectionCount(),me(this.store,this.config)]),n=new E(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t),o=ue(this.store,n,this.config);return{mindHeader:i,tools:o,flush:async u=>{u?await n.flushOnError():await n.flushClean()}}}async close(){this.store&&await Promise.resolve()}}});y();y();y();import{EventEmitter as Ve}from"events";import{Toolpack as Je,InMemoryConversationStore as Ye}from"toolpack-sdk";y();y();var P=Symbol("interceptor-skip-sentinel");function Z(r){return r===P}function ee(){return P}var G=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}};function te(r,e,t,i,n={}){let o=n.maxInvocationDepth??5;return{async execute(s){let p=(d=>({agent:e,channel:t,registry:i,invocationDepth:d,delegateAndWait:async(l,m)=>{let g=d+1;if(g>o)throw new G(g,o);if(!i)throw new Error(`Cannot delegate to "${l}": agent is running in standalone mode without a registry`);let h=i.getAgent(l);if(!h)throw new Error(`Agent "${l}" not found for delegation`);let f={message:m.message??"",intent:m.intent,data:m.data,context:m.context,conversationId:m.conversationId??s.conversationId??`delegation-${Date.now()}`};return await h.invokeAgent(f)},skip:ee}))(0),c=async d=>{let l=d??s;return await e.invokeAgent(l)};for(let d=r.length-1;d>=0;d--){let l=r[d],m=c;c=async g=>await l(g??s,p,m)}return await c()}}}async function ne(r,e){let t=await r.execute(e);return t===P?null:t}y();import{randomUUID as ie}from"crypto";function ve(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}var O=Symbol.for("toolpack:capture-history");function re(r){let e=r.captureAgentReplies??!0,t=r.getScope??ve,i=r.getMessageId??(s=>s.context?.messageId??s.context?.eventId??ie()),n=r.getMentions??(s=>s.context?.mentions??[]),o=async(s,u,p)=>{let c=s.conversationId;if(!c)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await p();let d=s.participant;if(d){let m={id:i(s),conversationId:c,participant:d,content:s.message??"",timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,messageId:s.context?.messageId,mentions:n(s),channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured inbound message",{messageId:m.id,participantId:d.id,conversationId:c})}catch(g){u.logger?.warn("[capture-history] Failed to store inbound message",{error:g instanceof Error?g.message:String(g)})}}let l=await p();if(e&&!Z(l)&&l.output!=null){let m={kind:"agent",id:u.agent.name,displayName:u.agent.name},g={id:ie(),conversationId:c,participant:m,content:l.output,timestamp:new Date().toISOString(),scope:t(s),metadata:{channelType:s.context?.channelType,threadId:s.context?.threadId,channelName:s.context?.channelName,channelId:s.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured agent reply",{messageId:g.id,agentId:u.agent.name,conversationId:c})}catch(h){u.logger?.warn("[capture-history] Failed to store agent reply",{error:h instanceof Error?h.message:String(h)})}}return l};return o[O]=!0,o}y();import{randomUUID as be}from"crypto";function oe(r){return Math.ceil(r.length/4)}function ke(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function Ie(r,e){let{participant:t,content:i}=r;return t.kind==="system"?{role:"system",content:i}:t.kind==="agent"?t.id===e?{role:"assistant",content:i}:{role:"user",content:`${t.displayName??t.id} (agent): ${i}`}:{role:"user",content:`${t.displayName??t.id}: ${i}`}}function Re(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(i=>t.has(i)))}async function se(r,e,t,i,n={},o){let{scope:s,addressedOnlyMode:u=!0,tokenBudget:p=3e3,rollingSummaryThreshold:c=40,timeWindowMinutes:d,maxTurnsToLoad:l=100,agentAliases:m}=n,g=new Set([t,...m??[]]),h=d!==void 0?new Date(Date.now()-d*60*1e3).toISOString():void 0,f=await r.get(e,{scope:s,sinceTimestamp:h,limit:l}),w=f.length;if(u){let b=new Set;for(let k=0;k<f.length;k++){let T=f[k];if(Re(T,t,g)&&b.add(T.id),k<f.length-1){let M=f[k+1];M.participant.kind==="agent"&&M.participant.id===t&&b.add(T.id)}}let C=f[f.length-1];C&&b.add(C.id),f=f.filter(k=>b.has(k.id))}let I=!1;if(f.length>c&&o){let b=Math.floor(f.length/2),C=f.slice(0,b),k=f.slice(b),T=C.filter(M=>!M.metadata?.isSummary);try{let M=await o.invokeAgent({message:"summarize",data:{turns:T.map(ke),agentName:i,agentId:t,maxTokens:Math.floor(p*.25),extractDecisions:!0}}),X=JSON.parse(M.output),Q={id:`summary-${be()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${X.turnsSummarized} earlier turns]: ${X.summary}`,timestamp:C[0].timestamp,scope:s??"channel",metadata:{isSummary:!0}};f=[Q,...k],I=!0;try{await r.append(Q),await r.deleteMessages(e,C.map(ye=>ye.id))}catch{}}catch{f=f.slice(-c)}}else f.length>c&&(f=f.slice(-c));let R=f.map(b=>Ie(b,t));if(R.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:w,hasSummary:I};let D=R[R.length-1],Y=[D],N=oe(D.content);for(let b=R.length-2;b>=0;b--){let C=R[b],k=oe(C.content);if(N+k>p)break;Y.unshift(C),N+=k}return{messages:Y,estimatedTokens:N,turnsLoaded:w,hasSummary:I}}y();var x=class extends Error{constructor(e){super(e),this.name="AgentError"}};var S=class extends Ve{provider;model;workflow;mind;delegation;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;constructor(e){super(),this.conversationHistory=new Ye,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await Je.init(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(()=>(he(),fe));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}async run(e,t,i){let n=i?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:n}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,s="",u=[];if(this._mind){let p=await this._mind.createRunContext();s=p.mindHeader,u=p.tools,o=p.flush}try{typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name));let p=[];if(s&&p.push({role:"system",content:s}),n)try{let m=await se(this.conversationHistory,n,this.name,this.name,this._resolveAssemblerOptions()),g=m.messages[m.messages.length-1],h=e.trim(),w=h!==""&&g?.role==="user"&&typeof g.content=="string"&&(g.content===h||g.content.endsWith(`: ${h}`))?m.messages.slice(0,-1):m.messages;p.push(...w)}catch{}e.trim()&&p.push({role:"user",content:e});let c=[...u];if(n){let m=this.conversationHistory;c.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async g=>{let h=await m.search(n,String(g.query??""),{limit:typeof g.limit=="number"?g.limit:5});return{results:h.map(f=>({role:f.participant.kind==="agent"?"assistant":"user",content:f.content,timestamp:f.timestamp})),count:h.length}}})}if(this.delegation?.enabled&&this._registry){let m=this.delegation.allowedAgents,g=this._registry.getAllAgents().filter(h=>h.name!==this.name&&(m===void 0||m.includes(h.name)));if(g.length>0){let h=g.map(w=>w.name),f=g.map(w=>`- ${w.name}: ${w.description}`).join(`
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
6
  ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}}).catch(D=>{console.error(`[${this.name}] delegate_and_forget to ${I} failed:`,D)}),{status:"delegated",agent:I}}}):c.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
7
7
 
8
8
  Available agents:
9
- ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}})}})}}let d=await this.toolpack.generate({messages:p,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds},this.provider),l={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(l),o&&await o(!1),this.emit("agent:complete",l),l}catch(p){throw o&&o(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(p),this.emit("agent:error",p),p}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new x("Agent not registered - cannot use ask()");if(!this._conversationId)throw new x("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new x("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new x("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new x("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
9
+ ${f}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:h,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async w=>{let I=String(w.agent),R=String(w.message??"");return this._registry.invoke(I,{message:R,conversationId:n,context:{delegatedBy:this.name}})}})}}let d=await this.toolpack.generate({messages:p,model:this.model||"",requestTools:c.length>0?c:void 0,maxToolRounds:t?.maxToolRounds,mode:this.mode},this.provider),l={output:d.content||"",steps:this.extractSteps(d),metadata:d.usage?{usage:d.usage}:void 0};return await this.onComplete(l),o&&await o(!1),this.emit("agent:complete",l),l}catch(p){throw o&&o(!0).catch(c=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,c)}),await this.onError(p),this.emit("agent:error",p),p}}getAgentAliases(){let e=[];for(let t of this.channels){let i=t.botUserId;i&&e.push(i)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new x("Agent not registered - cannot use ask()");if(!this._conversationId)throw new x("No conversationId available - ask() requires a conversation channel");if(this._isTriggerChannel)throw new x("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!this._triggeringChannel||this._triggeringChannel.trim()==="")throw new x("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let i=this._registry.addPendingAsk({conversationId:this._conversationId,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:this._triggeringChannel});return await this.sendTo(this._triggeringChannel,e),{output:e,metadata:{waitingForHuman:!0,askId:i.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new x("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,i){return i?.simpleValidation?i.simpleValidation(t):(await this.run(`Evaluate if this answer sufficiently addresses the question.
10
10
 
11
11
  Question: "${e}"
12
12
  Answer: "${t}"