@toolpack-sdk/agents 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -3
- package/dist/{base-agent-BfQbqIqI.d.cts → base-agent-5Dbq8iQi.d.ts} +11 -1
- package/dist/{base-agent-Cge0xlL7.d.ts → base-agent-YX0G2Ur3.d.cts} +11 -1
- package/dist/capabilities/index.cjs +20 -20
- package/dist/capabilities/index.d.cts +3 -3
- package/dist/capabilities/index.d.ts +3 -3
- package/dist/capabilities/index.js +20 -20
- package/dist/channels/index.d.cts +2 -2
- package/dist/channels/index.d.ts +2 -2
- package/dist/{eval-report-DjWw37Y1.d.cts → eval-report-CqW2VrJ7.d.cts} +1 -1
- package/dist/{eval-report-CmRgZW2r.d.ts → eval-report-DO-9E5Kq.d.ts} +1 -1
- package/dist/{index-CcjIB00Y.d.ts → index-CaFts8va.d.ts} +1 -1
- package/dist/{index-B9txljO1.d.cts → index-DN3HGEJV.d.cts} +1 -1
- package/dist/index.cjs +25 -25
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +25 -25
- package/dist/{intent-classifier-agent-CURERNsv.d.cts → intent-classifier-agent-A4thJQ0z.d.cts} +2 -2
- package/dist/{intent-classifier-agent-CRRAjM4Y.d.ts → intent-classifier-agent-DXlxbZ_r.d.ts} +2 -2
- package/dist/interceptors/index.d.cts +4 -4
- package/dist/interceptors/index.d.ts +4 -4
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/{types-DEXlIfZP.d.cts → types-C_2Rkpio.d.cts} +3 -0
- package/dist/{types-DEXlIfZP.d.ts → types-C_2Rkpio.d.ts} +3 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -385,7 +385,7 @@ class SupportAgent extends BaseAgent {
|
|
|
385
385
|
- Auto-stores user and assistant messages via the capture interceptor
|
|
386
386
|
- Auto-trims to `maxMessagesPerConversation` limit (default: 500)
|
|
387
387
|
- Zero-config in-memory mode for development
|
|
388
|
-
- `conversation_search` tool is automatically provided as a request-scoped tool whenever a `conversationId` is active
|
|
388
|
+
- `conversation_search` tool is automatically provided as a request-scoped tool whenever a `conversationId` is active. Set `conversationSearch = false` on the agent to leave it out (for example to give it your own search tool under the same name); the history still loads
|
|
389
389
|
|
|
390
390
|
**Memory model:**
|
|
391
391
|
Agent memory is per-conversation by default. The `conversation_search` tool is bound at invocation time to the current conversation — the LLM cannot override this scope, and turns from other conversations are structurally unreachable. Use `knowledge_add` to promote durable facts that should persist across conversations; knowledge is the only cross-conversation bridge.
|
|
@@ -596,10 +596,10 @@ const toolpack = await Toolpack.init({
|
|
|
596
596
|
|
|
597
597
|
## Peer Dependencies
|
|
598
598
|
|
|
599
|
-
Requires `toolpack-sdk` (`^3.
|
|
599
|
+
Requires `toolpack-sdk` (`^3.6.0`). Optional peers, install only what you need:
|
|
600
600
|
|
|
601
601
|
```bash
|
|
602
|
-
# Knowledge / RAG (optional)
|
|
602
|
+
# Knowledge / RAG and Agent Mind (optional, ^3.6.0)
|
|
603
603
|
npm install @toolpack-sdk/knowledge
|
|
604
604
|
|
|
605
605
|
# For DiscordChannel
|
|
@@ -646,6 +646,36 @@ if (result.metadata?.mindSaveError) {
|
|
|
646
646
|
}
|
|
647
647
|
```
|
|
648
648
|
|
|
649
|
+
#### Stopping or changing a tool call
|
|
650
|
+
|
|
651
|
+
`AgentRunOptions` accepts `interceptTool`, which wraps every tool call of that run (see `toolpack-sdk`). Call `run()` to run the tool, or return text without calling it to stop the call; the model sees that text as the tool's result. This is not the same as the [Interceptors](#interceptors) below, which handle incoming messages before `invokeAgent`.
|
|
652
|
+
|
|
653
|
+
```typescript
|
|
654
|
+
const result = await this.run(input.message, {
|
|
655
|
+
interceptTool: async (call, run) => {
|
|
656
|
+
if (call.toolName.startsWith('fs.delete')) return 'Ask the user before deleting anything.';
|
|
657
|
+
return run();
|
|
658
|
+
},
|
|
659
|
+
});
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
#### Agent Mind: what it remembers
|
|
663
|
+
|
|
664
|
+
Set `mind` on the agent to give it memory that lasts across runs. By default it keeps beliefs (facts), reflections and goals. Pass `kinds` to keep only some of them:
|
|
665
|
+
|
|
666
|
+
```typescript
|
|
667
|
+
import { OllamaEmbedder } from '@toolpack-sdk/knowledge';
|
|
668
|
+
|
|
669
|
+
class FactsAgent extends BaseAgent {
|
|
670
|
+
mind = {
|
|
671
|
+
embedder: new OllamaEmbedder({ model: 'nomic-embed-text' }),
|
|
672
|
+
kinds: ['belief'], // facts only
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
```
|
|
676
|
+
|
|
677
|
+
A kind that is left out is switched off: it is not in the mind header, its tools are not given to the agent, and `mind_recall` does not search it. `kinds` must name at least one of `'belief'`, `'reflection'` and `'goal'`.
|
|
678
|
+
|
|
649
679
|
### AgentRegistry
|
|
650
680
|
|
|
651
681
|
```typescript
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from 'events';
|
|
2
2
|
import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack, ImagePart, FilePart } from 'toolpack-sdk';
|
|
3
|
-
import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-
|
|
3
|
+
import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-C_2Rkpio.js';
|
|
4
4
|
import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
|
|
5
5
|
|
|
6
6
|
type GoalStatus = 'active' | 'completed';
|
|
@@ -77,6 +77,11 @@ interface AgentMindConfig {
|
|
|
77
77
|
deduplicationThreshold?: number;
|
|
78
78
|
retrievalThreshold?: number;
|
|
79
79
|
ttlDefaults?: MindTtlDefaults;
|
|
80
|
+
/**
|
|
81
|
+
* Which kinds of entry this agent remembers. Default: all three. With only `['belief']` the agent remembers facts and nothing else: the mind
|
|
82
|
+
* header has no goals and no reflections, there are no goal or reflection tools, and `mind_recall` searches beliefs only.
|
|
83
|
+
*/
|
|
84
|
+
kinds?: MindEntryType[];
|
|
80
85
|
}
|
|
81
86
|
|
|
82
87
|
/**
|
|
@@ -110,6 +115,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
|
|
|
110
115
|
* Set to undefined (default) to opt out — zero cost when not configured.
|
|
111
116
|
*/
|
|
112
117
|
mind?: AgentMindConfig;
|
|
118
|
+
/**
|
|
119
|
+
* Adds the built-in `conversation_search` tool to every run that has a conversation. Set to false to leave it out, for
|
|
120
|
+
* example to give the agent your own search tool under the same name. Default true.
|
|
121
|
+
*/
|
|
122
|
+
conversationSearch: boolean;
|
|
113
123
|
/**
|
|
114
124
|
* AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
|
|
115
125
|
* injected into every run() call so the LLM can hand tasks to peer agents.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { EventEmitter } from 'events';
|
|
2
2
|
import { ModeConfig, ConversationStore, AssemblerOptions, Toolpack, ImagePart, FilePart } from 'toolpack-sdk';
|
|
3
|
-
import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-
|
|
3
|
+
import { A as AgentInput, W as WorkflowStep, a as AgentResult, b as AgentDelegationConfig, c as AgentSpawnConfig, C as ChannelInterface, I as Interceptor, d as IAgentRegistry, B as BaseAgentOptions, e as AgentRunOptions, P as PendingAsk } from './types-C_2Rkpio.cjs';
|
|
4
4
|
import { Embedder, KnowledgeProvider } from '@toolpack-sdk/knowledge';
|
|
5
5
|
|
|
6
6
|
type GoalStatus = 'active' | 'completed';
|
|
@@ -77,6 +77,11 @@ interface AgentMindConfig {
|
|
|
77
77
|
deduplicationThreshold?: number;
|
|
78
78
|
retrievalThreshold?: number;
|
|
79
79
|
ttlDefaults?: MindTtlDefaults;
|
|
80
|
+
/**
|
|
81
|
+
* Which kinds of entry this agent remembers. Default: all three. With only `['belief']` the agent remembers facts and nothing else: the mind
|
|
82
|
+
* header has no goals and no reflections, there are no goal or reflection tools, and `mind_recall` searches beliefs only.
|
|
83
|
+
*/
|
|
84
|
+
kinds?: MindEntryType[];
|
|
80
85
|
}
|
|
81
86
|
|
|
82
87
|
/**
|
|
@@ -110,6 +115,11 @@ declare abstract class BaseAgent<TIntent extends string = string> extends EventE
|
|
|
110
115
|
* Set to undefined (default) to opt out — zero cost when not configured.
|
|
111
116
|
*/
|
|
112
117
|
mind?: AgentMindConfig;
|
|
118
|
+
/**
|
|
119
|
+
* Adds the built-in `conversation_search` tool to every run that has a conversation. Set to false to leave it out, for
|
|
120
|
+
* example to give the agent your own search tool under the same name. Default true.
|
|
121
|
+
*/
|
|
122
|
+
conversationSearch: boolean;
|
|
113
123
|
/**
|
|
114
124
|
* AI-driven agent delegation. When enabled, a `delegate_to_agent` tool is
|
|
115
125
|
* injected into every run() call so the LLM can hand tasks to peer agents.
|
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
"use strict";var Ye=Object.create;var J=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var S=(r,e)=>()=>(r&&(e=r(r=0)),e);var ie=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},be=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qe(e))!et.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=Xe(e,i))||n.enumerable});return r};var tt=(r,e,t)=>(t=r!=null?Ye(Ze(r)):{},be(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r)),nt=r=>be(J({},"__esModule",{value:!0}),r);var y=S(()=>{"use strict"});function Ie(r){return r===Y}function Ce(){return Y}var Y,re=S(()=>{"use strict";y();Y=Symbol("interceptor-skip-sentinel")});function xe(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let d=(c=>({agent:e,channel:t,registry:n,invocationDepth:c,delegateAndWait:async(p,g)=>{let m=c+1;if(m>s)throw new se(m,s);if(!n)throw new Error(`Cannot delegate to "${p}": agent is running in standalone mode without a registry`);let A=n.getAgent(p);if(!A)throw new Error(`Agent "${p}" not found for delegation`);let f={message:g.message??"",intent:g.intent,data:g.data,context:g.context,conversationId:g.conversationId??o.conversationId??`delegation-${Date.now()}`};return await A.invokeAgent(f)},skip:Ce}))(0),l=async c=>{let p=c??o;return await e.invokeAgent(p)};for(let c=r.length-1;c>=0;c--){let p=r[c],g=l;l=async m=>await p(m??o,d,g)}return await l()}}}async function Re(r,e){let t=await r.execute(e);return t===Y?null:t}var se,_e=S(()=>{"use strict";y();re();se=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function it(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function Se(r){let e=r.captureAgentReplies??!0,t=r.getScope??it,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,oe.randomUUID)()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,u,d)=>{let l=o.conversationId;if(!l)return u.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await d();let c=o.participant;if(c){let g={id:n(o),conversationId:l,participant:c,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:i(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),u.logger?.debug("[capture-history] Captured inbound message",{messageId:g.id,participantId:c.id,conversationId:l})}catch(m){u.logger?.warn("[capture-history] Failed to store inbound message",{error:m instanceof Error?m.message:String(m)})}}let p=await d();if(e&&!Ie(p)&&p.output!=null){let g={kind:"agent",id:u.agent.name,displayName:u.agent.name},m={id:(0,oe.randomUUID)(),conversationId:l,participant:g,content:p.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(m),r.onCaptured?.(m),u.logger?.debug("[capture-history] Captured agent reply",{messageId:m.id,agentId:u.agent.name,conversationId:l})}catch(A){u.logger?.warn("[capture-history] Failed to store agent reply",{error:A instanceof Error?A.message:String(A)})}}return p};return s[ae]=!0,s}var oe,ae,Me=S(()=>{"use strict";y();oe=require("crypto");re();ae=Symbol.for("toolpack:capture-history")});function Te(r){return Math.ceil(r.length/4)}function rt(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function st(r,e){let{participant:t,content:n}=r;return t.kind==="system"?{role:"system",content:n}:t.kind==="agent"?t.id===e?{role:"assistant",content:n}:{role:"user",content:`${t.displayName??t.id} (agent): ${n}`}:{role:"user",content:`${t.displayName??t.id}: ${n}`}}function ot(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function De(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:u=!0,tokenBudget:d=3e3,rollingSummaryThreshold:l=40,timeWindowMinutes:c,maxTurnsToLoad:p=100,agentAliases:g}=i,m=new Set([t,...g??[]]),A=c!==void 0?new Date(Date.now()-c*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:A,limit:p}),U=f.length;if(u){let w=new Set;for(let I=0;I<f.length;I++){let M=f[I];if(ot(M,t,m)&&w.add(M.id),I<f.length-1){let N=f[I+1];N.participant.kind==="agent"&&N.participant.id===t&&w.add(M.id)}}let b=f[f.length-1];b&&w.add(b.id),f=f.filter(I=>w.has(I.id))}let T=!1;if(f.length>l&&s){let w=Math.floor(f.length/2),b=f.slice(0,w),I=f.slice(w),M=b.filter(N=>!N.metadata?.isSummary);try{let N=await s.invokeAgent({message:"summarize",data:{turns:M.map(rt),agentName:n,agentId:t,maxTokens:Math.floor(d*.25),extractDecisions:!0}}),C=JSON.parse(N.output),P={id:`summary-${(0,Pe.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${C.turnsSummarized} earlier turns]: ${C.summary}`,timestamp:b[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[P,...I],T=!0;try{await r.append(P),await r.deleteMessages(e,b.map(j=>j.id))}catch{}}catch{f=f.slice(-l)}}else f.length>l&&(f=f.slice(-l));let h=f.map(w=>st(w,t));if(h.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:U,hasSummary:T};let v=h[h.length-1],k=[v],x=Te(v.content);for(let w=h.length-2;w>=0;w--){let b=h[w],I=Te(b.content);if(x+I>d)break;k.unshift(b),x+=I}return{messages:k,estimatedTokens:x,turnsLoaded:U,hasSummary:T}}var Pe,Be=S(()=>{"use strict";y();Pe=require("crypto")});var B,Ee=S(()=>{"use strict";y();B=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var X,ce,de,le,pe,ue,a,Q,Ne=S(()=>{"use strict";y();X=require("crypto"),ce=.6,de=.2,le=.2,pe={low:.3,medium:.6,high:1},ue=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},Q=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,n)=>{let i={high:0,normal:1,low:2},s=i[t.priority]-i[n.priority];return s!==0?s:t.createdAt-n.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(i=>i[a.type]==="belief"&&i[a.confidence]==="high"&&!i[a.error]&&!(i[a.expiresAt]&&i[a.expiresAt]<t))).map(i=>{let s=this.chunkToBelief(i),o=(t-s.createdAt)/864e5,d=Math.exp(-o/ue)*de+pe.high*le+ce;return{...s,score:d}}).sort((i,s)=>s.score-i.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:i="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[a.type]:"goal",[a.status]:i}})).map(d=>this.chunkToGoal(d.chunk));else{let u=i;if(o=(await this._getAllByMeta(l=>l[a.type]==="goal"&&l[a.status]===u)).map(l=>this.chunkToGoal(l)),e.trim()){let l=e.toLowerCase();o=o.filter(c=>c.description.toLowerCase().includes(l))}}return s?.length&&(o=o.filter(u=>s.every(d=>u.tags.includes(d)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,u=Date.now(),d=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),l=[];for(let c of d){let p=this.chunkToBelief(c.chunk);if(!o&&p.expiresAt&&p.expiresAt<u||s?.length&&!s.every(U=>p.tags.includes(U)))continue;let g=(u-p.createdAt)/864e5,m=Math.exp(-g/ue),A=p.error?.3:pe[p.confidence],f=c.score*ce+m*de+A*le;f<i||l.push({...p,score:f})}return l.sort((c,p)=>p.score-c.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,u=Date.now(),d={[a.type]:"reflection"};o===!0&&(d[a.pinned]=!0);let l=await this.provider.query(e,{limit:n*4,threshold:0,filter:d}),c=[];for(let p of l){let g=this.chunkToReflection(p.chunk);if(o===!1&&g.pinned||s?.length&&!s.every(U=>g.tags.includes(U)))continue;let m=(u-g.createdAt)/864e5,A=Math.exp(-m/ue),f=p.score*ce+A*de+pe.medium*le;f<i||c.push({...g,score:f})}return c.sort((p,g)=>g.score-p.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),i=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of i){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=(0,X.randomUUID)();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n),s={...i,description:t.description??i.description,priority:t.priority??i.priority,status:t.status??i.status,outcome:t.outcome??i.outcome,progress:t.appendProgress?[...i.progress,t.appendProgress]:i.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...i,status:"completed",outcome:t??i.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=(0,X.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(i),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},u=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,u)])}async addReflection(e,t){let n=(0,X.randomUUID)();return await this.provider.add([this.reflectionToChunk({...e,id:n},t)]),n}async updateReflection(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Reflection not found: ${e}`);let i=this.chunkToReflection(n),s={...i,pinned:t.pinned??i.pinned,error:t.error??i.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,n.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(n=>n.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(n=>e(n.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function me(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),n=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[n]}function $e(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=me(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ge(r,e){let t=0,n=0,i=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],i+=e[o]*e[o];let s=Math.sqrt(n)*Math.sqrt(i);return s===0?0:t/s}function ge(r){return Math.ceil(r.length/4)}var fe=S(()=>{"use strict";y()});var Oe,Z,Le=S(()=>{"use strict";y();Oe=require("crypto");fe();Z=class{constructor(e,t,n,i,s,o,u){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=u}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+me(s));let o=this._findSimilarInDraft(n);if(o!==null){let c=this.ops[o],p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},A=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g];return this.ops[o]={...c,content:e.content,confidence:A?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:c.existingId??`draft-${o}`}}let u=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(u))return{action:"updated_draft",id:"in-flight-dedup"};let d=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(d){let c=d.belief,p=e.confidence,g=c.confidence,m={low:0,medium:1,high:2},A=m[p]>m[g]||e.allowDowngrade&&m[p]<m[g],f={op:"believe",content:e.content,confidence:A?p:g,tags:e.tags.length>0?e.tags:c.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:d.id};return this.ops.push(f),{action:"updated_store",id:d.id}}this.inFlightBeliefs.add(u);let l={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(l),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),i={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:n},s=`draft-reflect-${this.ops.length}`;return this.ops.push(i),{id:s,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?$e(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Oe.randomUUID)(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(n),{id:n.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let n of this.ops)if(n.op==="believe"){let i=n;this.inFlightBeliefs.delete(i.content.trim().toLowerCase()),e?i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0,createdAt:i.createdAt,updatedAt:t},i.vector):i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="reflect"){let i=n;if(i.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content:i.content,pinned:i.pinned,tags:i.tags,relatedTo:i.relatedTo,error:e||void 0,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="set_goal"){if(!e){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=n;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(n.op==="update_goal"){if(!e){let i=n;await this.store.updateGoal(i.id,{description:i.description,priority:i.priority,appendProgress:i.progress})}}else if(n.op==="unpin_reflection"&&!e){let i=n;await this.store.updateReflection(i.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,i)=>({op:n,idx:i})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:i}of t){let s=n;if(s.vector.length===0)continue;if(Ge(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function Ue(r,e,t){return[at(r,t),ct(r,e,t),dt(e,t),lt(e),pt(e,t),ut(r,e),mt(r)]}function at(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:["belief","reflection","goal","all"],description:"Entry type to search. Default: 'all'"},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let n=String(t.query??""),i=t.type??"all",s=t.status??"active",o=Array.isArray(t.tags)?t.tags.map(String):void 0,u=typeof t.pinned=="boolean"?t.pinned:void 0,d=t.includeExpired===!0,l=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,c=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,p=[],m=(i==="belief"||i==="reflection"||i==="all")&&n.trim()?await r.embed(n):null;if(i==="goal"||i==="all"){let A=await r.keywordSearchGoals(n,{limit:c,status:s,tags:o});for(let f of A)p.push(gt(f))}if(m&&(i==="belief"||i==="all")){let A=await r.queryBeliefs(m,{limit:c,threshold:l,tags:o,includeExpired:d});for(let f of A)p.push(ft(f))}if(m&&(i==="reflection"||i==="all")){let A=await r.queryReflections(m,{limit:c,threshold:l,tags:o,pinned:u});for(let f of A)p.push(ht(f))}return p}}}function ct(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async n=>({status:"ok",...await e.addBelieve({content:String(n.content),confidence:n.confidence??"medium",tags:Array.isArray(n.tags)?n.tags.map(String):[],expiresIn:n.expiresIn?String(n.expiresIn):void 0,allowDowngrade:n.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function dt(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 lt(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 pt(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 ut(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 mt(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 gt(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 ft(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 ht(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var je=S(()=>{"use strict";y()});async function qe(r,e){let[t,n,i,s]=await Promise.all([r.getActiveGoals(),r.getPinnedReflections(),r.getHighConfidenceBeliefs(20),r.getRecentReflections(e.recencyWindowDays,3)]),o=t.map(p=>yt(p)),u=n.map(p=>`- ${p.content}`),{beliefLines:d,reflectionLines:l}=wt(i,s,e.tokenBudget);if(o.length===0&&u.length===0&&d.length===0&&l.length===0)return"";let c=["--- AGENT MIND ---",""];return o.length>0&&(c.push("## Goals"),c.push(...o),c.push("")),u.length>0&&(c.push("## Standing Rules (Pinned)"),c.push(...u),c.push("")),d.length>0&&(c.push("## Beliefs"),c.push(...d),c.push("")),l.length>0&&(c.push("## Recent Reflections"),c.push(...l),c.push("")),c.push("---"),c.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`);this.delegation.mode==="forget"?
|
|
1
|
+
"use strict";var Xe=Object.create;var J=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var ie=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},be=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ze(e))!tt.call(r,i)&&i!==t&&J(r,i,{get:()=>e[i],enumerable:!(n=Qe(e,i))||n.enumerable});return r};var nt=(r,e,t)=>(t=r!=null?Xe(et(r)):{},be(e||!r||!r.__esModule?J(t,"default",{value:r,enumerable:!0}):t,r)),it=r=>be(J({},"__esModule",{value:!0}),r);var y=_(()=>{"use strict"});function Ie(r){return r===Y}function Ce(){return Y}var Y,re=_(()=>{"use strict";y();Y=Symbol("interceptor-skip-sentinel")});function xe(r,e,t,n,i={}){let s=i.maxInvocationDepth??5;return{async execute(o){let c=(m=>({agent:e,channel:t,registry:n,invocationDepth:m,delegateAndWait:async(u,g)=>{let d=m+1;if(d>s)throw new se(d,s);if(!n)throw new Error(`Cannot delegate to "${u}": agent is running in standalone mode without a registry`);let w=n.getAgent(u);if(!w)throw new Error(`Agent "${u}" not found for delegation`);let f={message:g.message??"",intent:g.intent,data:g.data,context:g.context,conversationId:g.conversationId??o.conversationId??`delegation-${Date.now()}`};return await w.invokeAgent(f)},skip:Ce}))(0),l=async m=>{let u=m??o;return await e.invokeAgent(u)};for(let m=r.length-1;m>=0;m--){let u=r[m],g=l;l=async d=>await u(d??o,c,g)}return await l()}}}async function Re(r,e){let t=await r.execute(e);return t===Y?null:t}var se,Se=_(()=>{"use strict";y();re();se=class extends Error{constructor(e,t){super(`Invocation depth ${e} exceeds maximum ${t}`),this.name="InvocationDepthExceededError"}}});function rt(r){let e=r.context??{},t=e.channelType;return t==="im"||t==="private"||t==="dm"?"dm":e.threadId!==void 0?"thread":"channel"}function _e(r){let e=r.captureAgentReplies??!0,t=r.getScope??rt,n=r.getMessageId??(o=>o.context?.messageId??o.context?.eventId??(0,oe.randomUUID)()),i=r.getMentions??(o=>o.context?.mentions??[]),s=async(o,p,c)=>{let l=o.conversationId;if(!l)return p.logger?.warn("[capture-history] Message has no conversationId \u2014 skipping capture"),await c();let m=o.participant;if(m){let g={id:n(o),conversationId:l,participant:m,content:o.message??"",timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,messageId:o.context?.messageId,mentions:i(o),channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(g),r.onCaptured?.(g),p.logger?.debug("[capture-history] Captured inbound message",{messageId:g.id,participantId:m.id,conversationId:l})}catch(d){p.logger?.warn("[capture-history] Failed to store inbound message",{error:d instanceof Error?d.message:String(d)})}}let u=await c();if(e&&!Ie(u)&&u.output!=null){let g={kind:"agent",id:p.agent.name,displayName:p.agent.name},d={id:(0,oe.randomUUID)(),conversationId:l,participant:g,content:u.output,timestamp:new Date().toISOString(),scope:t(o),metadata:{channelType:o.context?.channelType,threadId:o.context?.threadId,channelName:o.context?.channelName,channelId:o.context?.channelId}};try{await r.store.append(d),r.onCaptured?.(d),p.logger?.debug("[capture-history] Captured agent reply",{messageId:d.id,agentId:p.agent.name,conversationId:l})}catch(w){p.logger?.warn("[capture-history] Failed to store agent reply",{error:w instanceof Error?w.message:String(w)})}}return u};return s[ae]=!0,s}var oe,ae,Me=_(()=>{"use strict";y();oe=require("crypto");re();ae=Symbol.for("toolpack:capture-history")});function Te(r){return Math.ceil(r.length/4)}function st(r){return{id:r.id,participant:r.participant,content:r.content,timestamp:r.timestamp}}function ot(r,e){let{participant:t,content:n}=r;return t.kind==="system"?{role:"system",content:n}:t.kind==="agent"?t.id===e?{role:"assistant",content:n}:{role:"user",content:`${t.displayName??t.id} (agent): ${n}`}:{role:"user",content:`${t.displayName??t.id}: ${n}`}}function at(r,e,t){return!!(r.participant.id===e||r.metadata?.mentions?.some(n=>t.has(n)))}async function De(r,e,t,n,i={},s){let{scope:o,addressedOnlyMode:p=!0,tokenBudget:c=3e3,rollingSummaryThreshold:l=40,timeWindowMinutes:m,maxTurnsToLoad:u=100,agentAliases:g}=i,d=new Set([t,...g??[]]),w=m!==void 0?new Date(Date.now()-m*60*1e3).toISOString():void 0,f=await r.get(e,{scope:o,sinceTimestamp:w,limit:u}),M=f.length;if(p){let A=new Set;for(let I=0;I<f.length;I++){let T=f[I];if(at(T,t,d)&&A.add(T.id),I<f.length-1){let $=f[I+1];$.participant.kind==="agent"&&$.participant.id===t&&A.add(T.id)}}let b=f[f.length-1];b&&A.add(b.id),f=f.filter(I=>A.has(I.id))}let P=!1;if(f.length>l&&s){let A=Math.floor(f.length/2),b=f.slice(0,A),I=f.slice(A),T=b.filter($=>!$.metadata?.isSummary);try{let $=await s.invokeAgent({message:"summarize",data:{turns:T.map(st),agentName:n,agentId:t,maxTokens:Math.floor(c*.25),extractDecisions:!0}}),C=JSON.parse($.output),D={id:`summary-${(0,Pe.randomUUID)()}`,conversationId:e,participant:{kind:"system",id:"summarizer"},content:`[Summary of ${C.turnsSummarized} earlier turns]: ${C.summary}`,timestamp:b[0].timestamp,scope:o??"channel",metadata:{isSummary:!0}};f=[D,...I],P=!0;try{await r.append(D),await r.deleteMessages(e,b.map(j=>j.id))}catch{}}catch{f=f.slice(-l)}}else f.length>l&&(f=f.slice(-l));let h=f.map(A=>ot(A,t));if(h.length===0)return{messages:[],estimatedTokens:0,turnsLoaded:M,hasSummary:P};let v=h[h.length-1],k=[v],x=Te(v.content);for(let A=h.length-2;A>=0;A--){let b=h[A],I=Te(b.content);if(x+I>c)break;k.unshift(b),x+=I}return{messages:k,estimatedTokens:x,turnsLoaded:M,hasSummary:P}}var Pe,Be=_(()=>{"use strict";y();Pe=require("crypto")});var E,Ee=_(()=>{"use strict";y();E=class extends Error{constructor(e){super(e),this.name="AgentError"}}});var X,ce,de,le,pe,ue,a,Q,Ne=_(()=>{"use strict";y();X=require("crypto"),ce=.6,de=.2,le=.2,pe={low:.3,medium:.6,high:1},ue=30,a={type:"_type",status:"_status",priority:"_priority",tags:"_tags",progress:"_progress",dueBy:"_dueBy",outcome:"_outcome",confidence:"_confidence",expiresAt:"_expiresAt",pinned:"_pinned",relatedTo:"_relatedTo",error:"_error",createdAt:"_createdAt",updatedAt:"_updatedAt"},Q=class{constructor(e,t){this.provider=e;this.embedder=t;this.zeroVector=new Array(t.dimensions).fill(0)}provider;embedder;zeroVector;async initialize(){await this.provider.validateDimensions(this.embedder.dimensions)}async embed(e){return this.embedder.embed(e)}async embedBatch(e){return this.embedder.embedBatch(e)}async getActiveGoals(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).map(t=>this.chunkToGoal(t)).sort((t,n)=>{let i={high:0,normal:1,low:2},s=i[t.priority]-i[n.priority];return s!==0?s:t.createdAt-n.createdAt})}async getActiveGoalCount(){return(await this._getAllByMeta(t=>t[a.type]==="goal"&&t[a.status]==="active")).length}async getPinnedReflections(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).map(t=>this.chunkToReflection(t))}async getPinnedReflectionCount(){return(await this._getAllByMeta(t=>t[a.type]==="reflection"&&t[a.pinned]===!0)).length}async getHighConfidenceBeliefs(e){let t=Date.now();return(await this._getAllByMeta(i=>i[a.type]==="belief"&&i[a.confidence]==="high"&&!i[a.error]&&!(i[a.expiresAt]&&i[a.expiresAt]<t))).map(i=>{let s=this.chunkToBelief(i),o=(t-s.createdAt)/864e5,c=Math.exp(-o/ue)*de+pe.high*le+ce;return{...s,score:c}}).sort((i,s)=>s.score-i.score).slice(0,e)}async getRecentReflections(e,t){let n=Date.now()-e*864e5;return(await this._getAllByMeta(s=>s[a.type]==="reflection"&&!s[a.pinned]&&!s[a.error]&&s[a.createdAt]>=n)).map(s=>this.chunkToReflection(s)).sort((s,o)=>o.createdAt-s.createdAt).slice(0,t)}async keywordSearchGoals(e,t={}){let{limit:n=10,status:i="active",tags:s}=t,o;if(e.trim()&&typeof this.provider.keywordQuery=="function")o=(await this.provider.keywordQuery(e,{limit:n*2,threshold:0,filter:{[a.type]:"goal",[a.status]:i}})).map(c=>this.chunkToGoal(c.chunk));else{let p=i;if(o=(await this._getAllByMeta(l=>l[a.type]==="goal"&&l[a.status]===p)).map(l=>this.chunkToGoal(l)),e.trim()){let l=e.toLowerCase();o=o.filter(m=>m.description.toLowerCase().includes(l))}}return s?.length&&(o=o.filter(p=>s.every(c=>p.tags.includes(c)))),o.slice(0,n)}async queryBeliefs(e,t){let{limit:n=10,threshold:i=0,tags:s,includeExpired:o=!1}=t,p=Date.now(),c=await this.provider.query(e,{limit:n*4,threshold:0,filter:{[a.type]:"belief"}}),l=[];for(let m of c){let u=this.chunkToBelief(m.chunk);if(!o&&u.expiresAt&&u.expiresAt<p||s?.length&&!s.every(M=>u.tags.includes(M)))continue;let g=(p-u.createdAt)/864e5,d=Math.exp(-g/ue),w=u.error?.3:pe[u.confidence],f=m.score*ce+d*de+w*le;f<i||l.push({...u,score:f})}return l.sort((m,u)=>u.score-m.score).slice(0,n)}async queryReflections(e,t){let{limit:n=10,threshold:i=0,tags:s,pinned:o}=t,p=Date.now(),c={[a.type]:"reflection"};o===!0&&(c[a.pinned]=!0);let l=await this.provider.query(e,{limit:n*4,threshold:0,filter:c}),m=[];for(let u of l){let g=this.chunkToReflection(u.chunk);if(o===!1&&g.pinned||s?.length&&!s.every(M=>g.tags.includes(M)))continue;let d=(p-g.createdAt)/864e5,w=Math.exp(-d/ue),f=u.score*ce+w*de+pe.medium*le;f<i||m.push({...g,score:f})}return m.sort((u,g)=>g.score-u.score).slice(0,n)}async findSimilarBelief(e,t){let n=Date.now(),i=await this.provider.query(e,{limit:5,threshold:t,filter:{[a.type]:"belief"}});for(let s of i){let o=this.chunkToBelief(s.chunk);if(!(o.expiresAt&&o.expiresAt<n))return{id:s.chunk.id,score:s.score,belief:o}}return null}async addGoal(e){let t=(0,X.randomUUID)();return await this.provider.add([this.goalToChunk({...e,id:t})]),t}async updateGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n),s={...i,description:t.description??i.description,priority:t.priority??i.priority,status:t.status??i.status,outcome:t.outcome??i.outcome,progress:t.appendProgress?[...i.progress,t.appendProgress]:i.progress,updatedAt:Date.now()};await this.provider.add([this.goalToChunk(s)])}async completeGoal(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Goal not found: ${e}`);let i=this.chunkToGoal(n);await this.provider.add([this.goalToChunk({...i,status:"completed",outcome:t??i.outcome,updatedAt:Date.now()})])}async addBelief(e,t){let n=(0,X.randomUUID)();return await this.provider.add([this.beliefToChunk({...e,id:n},t)]),n}async updateBelief(e,t,n){let i=await this._getById(e);if(!i)throw new Error(`[AgentMind] Belief not found: ${e}`);let s=this.chunkToBelief(i),o={...s,content:t.content??s.content,confidence:t.confidence??s.confidence,tags:t.tags??s.tags,expiresAt:t.expiresAt!==void 0?t.expiresAt:s.expiresAt,error:t.error??s.error,updatedAt:Date.now()},p=n??i.vector??this.zeroVector;await this.provider.add([this.beliefToChunk(o,p)])}async addReflection(e,t){let n=(0,X.randomUUID)();return await this.provider.add([this.reflectionToChunk({...e,id:n},t)]),n}async updateReflection(e,t){let n=await this._getById(e);if(!n)throw new Error(`[AgentMind] Reflection not found: ${e}`);let i=this.chunkToReflection(n),s={...i,pinned:t.pinned??i.pinned,error:t.error??i.error,updatedAt:Date.now()};await this.provider.add([this.reflectionToChunk(s,n.vector??this.zeroVector)])}goalToChunk(e){return{id:e.id,content:e.description,metadata:{[a.type]:"goal",[a.status]:e.status,[a.priority]:e.priority,[a.tags]:JSON.stringify(e.tags),[a.progress]:JSON.stringify(e.progress),[a.dueBy]:e.dueBy??"",[a.outcome]:e.outcome??"",[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:this.zeroVector}}chunkToGoal(e){let t=e.metadata;return{id:e.id,type:"goal",description:e.content,status:t[a.status],priority:t[a.priority],tags:this._parseTags(t[a.tags]),progress:this._parseTags(t[a.progress]),dueBy:t[a.dueBy]||void 0,outcome:t[a.outcome]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}beliefToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"belief",[a.confidence]:e.confidence,[a.tags]:JSON.stringify(e.tags),[a.expiresAt]:e.expiresAt??0,[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToBelief(e){let t=e.metadata;return{id:e.id,type:"belief",content:e.content,confidence:t[a.confidence],tags:this._parseTags(t[a.tags]),expiresAt:t[a.expiresAt]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}reflectionToChunk(e,t){return{id:e.id,content:e.content,metadata:{[a.type]:"reflection",[a.pinned]:e.pinned,[a.tags]:JSON.stringify(e.tags),[a.relatedTo]:e.relatedTo??"",[a.error]:e.error===!0,[a.createdAt]:e.createdAt,[a.updatedAt]:e.updatedAt},vector:t}}chunkToReflection(e){let t=e.metadata;return{id:e.id,type:"reflection",content:e.content,pinned:t[a.pinned],tags:this._parseTags(t[a.tags]),relatedTo:t[a.relatedTo]||void 0,error:t[a.error]||void 0,createdAt:t[a.createdAt],updatedAt:t[a.updatedAt]}}async _getById(e){let t=await this.provider.getAllChunks?.();return t?t.find(n=>n.id===e)??null:null}async _getAllByMeta(e){return(await this.provider.getAllChunks?.()??[]).filter(n=>e(n.metadata))}_parseTags(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}}});function me(r){let e=r.match(/^(\d+)(d|h|m|s)$/);if(!e)throw new Error(`Invalid duration format: "${r}". Expected a number followed by d/h/m/s (e.g., "30d", "24h").`);let t=parseInt(e[1],10),n=e[2];return t*{d:864e5,h:36e5,m:6e4,s:1e3}[n]}function $e(r){if(/^\d{4}-\d{2}-\d{2}/.test(r))return r;let e=me(r);return new Date(Date.now()+e).toISOString().slice(0,10)}function Ge(r,e){let t=0,n=0,i=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],i+=e[o]*e[o];let s=Math.sqrt(n)*Math.sqrt(i);return s===0?0:t/s}function ge(r){return Math.ceil(r.length/4)}var fe=_(()=>{"use strict";y()});var Oe,Z,Le=_(()=>{"use strict";y();Oe=require("crypto");fe();Z=class{constructor(e,t,n,i,s,o,p){this.store=e;this.deduplicationThreshold=t;this.maxGoals=n;this.maxPinnedReflections=i;this.committedGoalCount=s;this.committedPinnedReflectionCount=o;this.inFlightBeliefs=p}store;deduplicationThreshold;maxGoals;maxPinnedReflections;committedGoalCount;committedPinnedReflectionCount;inFlightBeliefs;ops=[];get draftGoalCount(){return this.ops.filter(e=>e.op==="set_goal").length}get draftPinnedReflectionCount(){return this.ops.filter(e=>e.op==="reflect"&&e.pinned).length}get totalGoalCount(){return this.committedGoalCount+this.draftGoalCount}get totalPinnedReflectionCount(){return this.committedPinnedReflectionCount+this.draftPinnedReflectionCount}async addBelieve(e){let t=Date.now(),n=await this.store.embed(e.content),i,s=e.expiresIn??e.ttlDefault;s&&(i=t+me(s));let o=this._findSimilarInDraft(n);if(o!==null){let m=this.ops[o],u=e.confidence,g=m.confidence,d={low:0,medium:1,high:2},w=d[u]>d[g]||e.allowDowngrade&&d[u]<d[g];return this.ops[o]={...m,content:e.content,confidence:w?u:g,tags:e.tags.length>0?e.tags:m.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,vector:n},{action:"updated_draft",id:m.existingId??`draft-${o}`}}let p=e.content.trim().toLowerCase();if(this.inFlightBeliefs.has(p))return{action:"updated_draft",id:"in-flight-dedup"};let c=await this.store.findSimilarBelief(n,this.deduplicationThreshold);if(c){let m=c.belief,u=e.confidence,g=m.confidence,d={low:0,medium:1,high:2},w=d[u]>d[g]||e.allowDowngrade&&d[u]<d[g],f={op:"believe",content:e.content,confidence:w?u:g,tags:e.tags.length>0?e.tags:m.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n,existingId:c.id};return this.ops.push(f),{action:"updated_store",id:c.id}}this.inFlightBeliefs.add(p);let l={op:"believe",content:e.content,confidence:e.confidence,tags:e.tags,expiresAt:i,allowDowngrade:e.allowDowngrade,createdAt:t,vector:n};return this.ops.push(l),{action:"created",id:`draft-${this.ops.length-1}`}}async addReflect(e){let t;if(e.pinned){let o=this.totalPinnedReflectionCount;if(o>=this.maxPinnedReflections)throw new Error(`[AgentMind] Pinned reflection cap reached (${this.maxPinnedReflections}). Call mind_recall with type:'reflection' and pinned:true to list current pinned reflections, then call mind_unpin_reflection to remove one before adding another.`);o>=this.maxPinnedReflections-2&&(t=`Pinned reflection count is ${o+1} of ${this.maxPinnedReflections}. Review and unpin standing rules that are no longer universally applicable.`)}let n=await this.store.embed(e.content),i={op:"reflect",content:e.content,pinned:e.pinned,tags:e.tags,relatedTo:e.relatedTo,createdAt:Date.now(),vector:n},s=`draft-reflect-${this.ops.length}`;return this.ops.push(i),{id:s,warning:t}}addSetGoal(e){if(this.totalGoalCount>=this.maxGoals)throw new Error(`[AgentMind] Active goal cap reached (${this.maxGoals}). Complete or archive an existing goal before setting a new one.`);let t=e.dueBy?$e(e.dueBy):void 0,n={op:"set_goal",tempId:(0,Oe.randomUUID)(),description:e.description,priority:e.priority,tags:e.tags,dueBy:t,createdAt:Date.now()};return this.ops.push(n),{id:n.tempId}}addUpdateGoal(e){let t={op:"update_goal",id:e.id,description:e.description,priority:e.priority,progress:e.progress,updatedAt:Date.now()};this.ops.push(t)}addUnpinReflection(e){let t={op:"unpin_reflection",id:e};this.ops.push(t)}async flushClean(){await this._flush(!1)}async flushOnError(){await this._flush(!0)}async _flush(e){let t=Date.now();for(let n of this.ops)if(n.op==="believe"){let i=n;this.inFlightBeliefs.delete(i.content.trim().toLowerCase()),e?i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,error:!0,createdAt:i.createdAt,updatedAt:t},i.vector):i.existingId?await this.store.updateBelief(i.existingId,{content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt},i.vector):await this.store.addBelief({type:"belief",content:i.content,confidence:i.confidence,tags:i.tags,expiresAt:i.expiresAt,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="reflect"){let i=n;if(i.pinned&&await this.store.getPinnedReflectionCount()>=this.maxPinnedReflections){console.warn(`[AgentMind] pinned reflection cap (${this.maxPinnedReflections}) reached at flush \u2014 dropping`);continue}await this.store.addReflection({type:"reflection",content:i.content,pinned:i.pinned,tags:i.tags,relatedTo:i.relatedTo,error:e||void 0,createdAt:i.createdAt,updatedAt:t},i.vector)}else if(n.op==="set_goal"){if(!e){if(await this.store.getActiveGoalCount()>=this.maxGoals){console.warn(`[AgentMind] goal cap (${this.maxGoals}) reached at flush \u2014 dropping goal`);continue}let s=n;await this.store.addGoal({type:"goal",description:s.description,priority:s.priority,status:"active",tags:s.tags,dueBy:s.dueBy,progress:[],createdAt:s.createdAt,updatedAt:s.createdAt})}}else if(n.op==="update_goal"){if(!e){let i=n;await this.store.updateGoal(i.id,{description:i.description,priority:i.priority,appendProgress:i.progress})}}else if(n.op==="unpin_reflection"&&!e){let i=n;await this.store.updateReflection(i.id,{pinned:!1})}this.ops=[]}_findSimilarInDraft(e){let t=this.ops.map((n,i)=>({op:n,idx:i})).filter(({op:n})=>n.op==="believe");for(let{op:n,idx:i}of t){let s=n;if(s.vector.length===0)continue;if(Ge(e,s.vector)>=this.deduplicationThreshold)return i}return null}}});function Ue(r,e,t){let n=t.kinds.includes("reflection"),i=t.kinds.includes("goal");return[ct(r,t),...t.kinds.includes("belief")?[dt(r,e,t)]:[],...n?[lt(e,t),pt(e)]:[],...i?[ut(e,t),mt(r,e),gt(r)]:[]]}function ct(r,e){return{name:"mind_recall",displayName:"Mind Recall",description:"Search the agent's persistent memory for past beliefs, reflections, and goals. Use mid-task when the current task may have relevant past context not in the header. Reads from committed store only \u2014 writes from the current run are not visible here.",category:"mind",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Free-text search query. Used for semantic search on beliefs/reflections and text matching on goals."},type:{type:"string",enum:[...e.kinds,"all"],description:e.kinds.length===3?"Entry type to search. Default: 'all'":`Entry type to search: ${e.kinds.join(", ")}. Default: 'all' (${e.kinds.join(" and ")}).`},status:{type:"string",enum:["active","completed"],description:"For goal queries only. Default: 'active'"},tags:{type:"array",items:{type:"string"},description:"Filter to entries that have all of these tags."},pinned:{type:"boolean",description:"When true, return only pinned reflections. For type:'all', applies only to the reflection subset."},includeExpired:{type:"boolean",description:"Whether to include archived (expired) beliefs. Default: false"},threshold:{type:"number",description:"Composite score threshold override for this call (0\u20131). Results below this score are excluded. Silently ignored for goal queries."},limit:{type:"number",description:"Max entries to return. Default: 5"}},required:["query"]},execute:async t=>{let n=String(t.query??""),i=t.type??"all",s=f=>e.kinds.includes(f)&&(i===f||i==="all"),o=t.status??"active",p=Array.isArray(t.tags)?t.tags.map(String):void 0,c=typeof t.pinned=="boolean"?t.pinned:void 0,l=t.includeExpired===!0,m=typeof t.threshold=="number"?t.threshold:e.retrievalThreshold,u=typeof t.limit=="number"?Math.max(1,Math.floor(t.limit)):5,g=[],w=(s("belief")||s("reflection"))&&n.trim()?await r.embed(n):null;if(s("goal")){let f=await r.keywordSearchGoals(n,{limit:u,status:o,tags:p});for(let M of f)g.push(ft(M))}if(w&&s("belief")){let f=await r.queryBeliefs(w,{limit:u,threshold:m,tags:p,includeExpired:l});for(let M of f)g.push(ht(M))}if(w&&s("reflection")){let f=await r.queryReflections(w,{limit:u,threshold:m,tags:p,pinned:c});for(let M of f)g.push(yt(M))}return g}}}function dt(r,e,t){return{name:"mind_believe",displayName:"Mind Believe",description:"Record a new belief about the operating environment, or update an existing one. Call at the end of a task when you have learned something that should persist across runs. Deduplicates automatically \u2014 if a similar belief already exists above the similarity threshold it is updated in place. Writes are buffered and committed when the task completes cleanly.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The belief statement."},confidence:{type:"string",enum:["low","medium","high"],description:"Certainty at write time. Default: 'medium'"},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},expiresIn:{type:"string",description:"TTL override, e.g. '30d', '90d'. Overrides the agent default TTL."},allowDowngrade:{type:"boolean",description:"If true, allows confidence downgrade on an existing belief. Default: false."}},required:["content"]},execute:async n=>({status:"ok",...await e.addBelieve({content:String(n.content),confidence:n.confidence??"medium",tags:Array.isArray(n.tags)?n.tags.map(String):[],expiresIn:n.expiresIn?String(n.expiresIn):void 0,allowDowngrade:n.allowDowngrade===!0,ttlDefault:t.ttlDefaults.belief})})}}function lt(r,e){return{name:"mind_reflect",displayName:"Mind Reflect",description:"Log a post-task observation about your own performance. Reflections are append-only and not auto-injected (use pin:true to make a standing rule always shown in the header). Call at the end of a task with something you would do differently next time.",category:"mind",parameters:{type:"object",properties:{content:{type:"string",description:"The post-task observation."},pin:{type:"boolean",description:`If true, marks as a standing rule always shown in the header. Capped at ${e.maxPinnedReflections}. Default: false`},tags:{type:"array",items:{type:"string"},description:"Tags for structured filtering via mind_recall."},relatedTo:{type:"string",description:"Informational context (e.g., a PR number or task ID). Not filterable \u2014 use tags for that."}},required:["content"]},execute:async t=>({status:"ok",...await r.addReflect({content:String(t.content),pinned:t.pin===!0,tags:Array.isArray(t.tags)?t.tags.map(String):[],relatedTo:t.relatedTo?String(t.relatedTo):void 0})})}}function pt(r){return{name:"mind_unpin_reflection",displayName:"Mind Unpin Reflection",description:"Remove the pin flag from a standing rule reflection. The reflection stays in the store as a regular non-pinned reflection. Use when a pinned rule is no longer universally applicable. Requires the reflection id \u2014 call mind_recall with type:reflection and pinned:true first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the pinned reflection to unpin. Obtain via mind_recall."}},required:["id"]},execute:async e=>(r.addUnpinReflection(String(e.id)),{status:"ok"})}}function ut(r,e){return{name:"mind_set_goal",displayName:"Mind Set Goal",description:`Create a new active goal to track across sessions. No deduplication \u2014 call mind_recall with type:goal first to avoid re-creating existing goals. Goal cap is ${e.maxGoals} active goals; the call is rejected if the cap is reached.`,category:"mind",parameters:{type:"object",properties:{description:{type:"string",description:"The goal statement."},priority:{type:"string",enum:["low","normal","high"],description:"Goal priority. Default: 'normal'"},tags:{type:"array",items:{type:"string"},description:"Tags for filtering via mind_recall."},dueBy:{type:"string",description:"Optional deadline. ISO 8601 date (e.g., '2026-06-01') or duration string (e.g., '30d'). Metadata only \u2014 goals are not auto-archived."}},required:["description"]},execute:async t=>({status:"ok",...r.addSetGoal({description:String(t.description),priority:t.priority??"normal",tags:Array.isArray(t.tags)?t.tags.map(String):[],dueBy:t.dueBy?String(t.dueBy):void 0})})}}function mt(r,e){return{name:"mind_update_goal",displayName:"Mind Update Goal",description:"Partially update an active goal \u2014 change priority, description, or append a progress note. Does not complete the goal; use mind_complete_goal for that. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to update. Obtain via mind_recall."},description:{type:"string",description:"Revised goal description."},priority:{type:"string",enum:["low","normal","high"],description:"Updated priority."},progress:{type:"string",description:"A progress note to append to the goal history. Not a replacement."}},required:["id"]},execute:async t=>(e.addUpdateGoal({id:String(t.id),description:t.description?String(t.description):void 0,priority:t.priority,progress:t.progress?String(t.progress):void 0}),{status:"ok"})}}function gt(r){return{name:"mind_complete_goal",displayName:"Mind Complete Goal",description:"Mark an active goal as completed and archive it. Commits immediately (does not go through the draft buffer). Completed goals are excluded from the header but remain queryable via mind_recall with status:completed. Requires the goal id \u2014 call mind_recall with type:goal first.",category:"mind",parameters:{type:"object",properties:{id:{type:"string",description:"ID of the goal to complete. Obtain via mind_recall with type:goal."},outcome:{type:"string",description:"Optional summary of what was accomplished."}},required:["id"]},execute:async e=>(await r.completeGoal(String(e.id),e.outcome?String(e.outcome):void 0),{status:"ok"})}}function ft(r){return{id:r.id,type:"goal",content:r.description,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,priority:r.priority,status:r.status,progress:r.progress,outcome:r.outcome,dueBy:r.dueBy}}function ht(r){return{id:r.id,type:"belief",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,confidence:r.confidence,expiresAt:r.expiresAt,error:r.error}}function yt(r){return{id:r.id,type:"reflection",content:r.content,score:r.score,tags:r.tags,createdAt:r.createdAt,updatedAt:r.updatedAt,pinned:r.pinned,relatedTo:r.relatedTo,error:r.error}}var je=_(()=>{"use strict";y()});async function qe(r,e){let t=e.kinds.includes("goal"),n=e.kinds.includes("reflection"),i=e.kinds.includes("belief"),[s,o,p,c]=await Promise.all([t?r.getActiveGoals():Promise.resolve([]),n?r.getPinnedReflections():Promise.resolve([]),i?r.getHighConfidenceBeliefs(20):Promise.resolve([]),n?r.getRecentReflections(e.recencyWindowDays,3):Promise.resolve([])]),l=s.map(w=>wt(w)),m=o.map(w=>`- ${w.content}`),{beliefLines:u,reflectionLines:g}=At(p,c,e.tokenBudget);if(l.length===0&&m.length===0&&u.length===0&&g.length===0)return"";let d=["--- AGENT MIND ---",""];return l.length>0&&(d.push("## Goals"),d.push(...l),d.push("")),m.length>0&&(d.push("## Standing Rules (Pinned)"),d.push(...m),d.push("")),u.length>0&&(d.push("## Beliefs"),d.push(...u),d.push("")),g.length>0&&(d.push("## Recent Reflections"),d.push(...g),d.push("")),d.push("---"),d.join(`
|
|
2
|
+
`)}function wt(r){let e=r.progress[r.progress.length-1],t=`[${r.priority}] ${r.description}`;return e&&(t+=` \u2014 last progress: ${e}`),r.dueBy&&(t+=` (due: ${r.dueBy})`),t}function At(r,e,t){let n=t,i=[],s=[];for(let o of r){let p=`- ${o.content} (${o.confidence} confidence)`,c=ge(p);if(c>n)break;i.push(p),n-=c}for(let o of e){let c=`- [${new Date(o.createdAt).toISOString().slice(0,10)}] ${o.content}`,l=ge(c);if(l>n)break;s.push(c),n-=l}return{beliefLines:i,reflectionLines:s}}var Fe=_(()=>{"use strict";y();fe()});var He={};ie(He,{AgentMind:()=>he});function Mt(r,e){let t=Math.min(e.maxGoals??bt,St),n=Math.min(e.maxPinnedReflections??It,_t);return{tokenBudget:e.tokenBudget??vt,recencyWindowDays:e.recencyWindowDays??kt,maxGoals:t,maxPinnedReflections:n,deduplicationThreshold:e.deduplicationThreshold??Ct,retrievalThreshold:e.retrievalThreshold??xt,ttlDefaults:{belief:e.ttlDefaults?.belief??Rt,reflection:e.ttlDefaults?.reflection},namespace:e.namespace??`mind/${r}`,kinds:Tt(e.kinds)}}function Tt(r){if(r===void 0)return[...ze];let e=ze.filter(t=>r.includes(t));if(e.length===0)throw new Error("AgentMindConfig.kinds must name at least one of belief, reflection and goal.");return e}var vt,kt,bt,It,Ct,xt,Rt,St,_t,he,ze,We=_(()=>{"use strict";y();Ne();Le();je();Fe();vt=300,kt=7,bt=10,It=10,Ct=.85,xt=.35,Rt="30d",St=10,_t=10,he=class r{constructor(e,t){this.store=e;this.config=t}store;config;_inFlightBeliefs=new Set;static async create(e,t){let n;if(t.provider)n=t.provider;else{let{PersistentKnowledgeProvider:o}=await import("@toolpack-sdk/knowledge"),p=t.namespace??`mind/${e}`;n=new o({namespace:p})}let i=Mt(e,t),s=new Q(n,t.embedder);return await s.initialize(),new r(s,i)}async createRunContext(){let[e,t,n]=await Promise.all([this.config.kinds.includes("goal")?this.store.getActiveGoalCount():Promise.resolve(0),this.config.kinds.includes("reflection")?this.store.getPinnedReflectionCount():Promise.resolve(0),qe(this.store,this.config)]),i=new Z(this.store,this.config.deduplicationThreshold,this.config.maxGoals,this.config.maxPinnedReflections,e,t,this._inFlightBeliefs),s=Ue(this.store,i,this.config),o={manifest:{key:"mind",name:"mind",displayName:"Agent Mind",version:"1.0.0",description:"Agent cognitive tools for beliefs, goals, and reflections.",category:"mind",tools:s.map(c=>c.name)},tools:s};return{mindHeader:n,toolProject:o,flush:async c=>{c?await i.flushOnError():await i.flushClean()}}}async close(){this.store&&await Promise.resolve()}};ze=["belief","reflection","goal"]});var we={};ie(we,{EphemeralAgent:()=>ye});var ye,Ae=_(()=>{"use strict";y();ee();ye=class extends U{name;description;mode;constructor(e,t,n,i){super(i),this.name=e,this.description=t,this.mode=n}async invokeAgent(e){return this.run(e.message??"",void 0,{conversationId:e.conversationId,spawnDepth:e.context?.spawnDepth??0},e.attachments)}}});var Ke,Ve,N,U,ee=_(()=>{"use strict";y();Ke=require("events"),Ve=require("async_hooks"),N=require("toolpack-sdk");Se();Me();Be();Ee();U=class extends Ke.EventEmitter{provider;model;workflow;mind;conversationSearch=!0;delegation;spawn;conversationHistory;assemblerOptions;channels=[];interceptors=[];_registry;_triggeringChannel;_conversationId;_isTriggerChannel;toolpack;_initConfig;_ownedToolpack=!1;_conversationLocks=new Map;_mind;_mindInitPromise;_channelCtx=new Ve.AsyncLocalStorage;_ctx(){return this._channelCtx.getStore()}constructor(e){super(),this.conversationHistory=new N.InMemoryConversationStore,"toolpack"in e?this.toolpack=e.toolpack:this._initConfig=e}async _ensureToolpack(){if(!this.toolpack){if(!this._initConfig)throw new Error(`[${this.name??"agent"}] Cannot start: no apiKey or toolpack provided`);this.toolpack=await N.Toolpack.init(this._initConfig),this._ownedToolpack=!0}}async _ensureMind(){this._mind!==void 0||!this.mind||(this._mindInitPromise||(this._mindInitPromise=(async()=>{let{AgentMind:e}=await Promise.resolve().then(()=>(We(),He));this._mind=await e.create(this.name,this.mind)})().catch(e=>{throw this._mindInitPromise=void 0,e})),await this._mindInitPromise)}async start(){await this._ensureToolpack(),this.mode&&(typeof this.mode=="string"?this.toolpack.setMode(this.mode):(this.toolpack.registerMode(this.mode),this.toolpack.setMode(this.mode.name)));for(let e of this.channels)this._bindChannel(e),e.listen()}async stop(){for(let e of this.channels)"stop"in e&&typeof e.stop=="function"&&await e.stop();this._ownedToolpack&&await this.toolpack.disconnect?.()}isIdle(){return this._conversationLocks.size===0}async run(e,t,n,i){let s=n?.conversationId??this._ctx()?.conversationId??this._conversationId;await this.onBeforeRun({message:e,conversationId:s}),this.emit("agent:start",{message:e}),await this._ensureMind();let o,p="";if(this._mind){let c=await this._mind.createRunContext();p=c.mindHeader,o=c.flush,this.toolpack.loadRequestToolProject(c.toolProject)}try{typeof this.mode!="string"&&this.toolpack.registerMode(this.mode);let c=[];if(p&&c.push({role:"system",content:p}),s)try{let h=await De(this.conversationHistory,s,this.name,this.name,this._resolveAssemblerOptions()),v=h.messages[h.messages.length-1],k=e.trim(),A=k!==""&&v?.role==="user"&&typeof v.content=="string"&&(v.content===k||v.content.endsWith(`: ${k}`))?h.messages.slice(0,-1):h.messages;c.push(...A)}catch{}let l=i&&i.length>0;if(e.trim()||l)if(l){let h=[...e.trim()?[{type:"text",text:e}]:[],...i];c.push({role:"user",content:h})}else c.push({role:"user",content:e});let m=[];if(s&&this.conversationSearch){let h=this.conversationHistory;m.push({name:"conversation_search",displayName:"Conversation Search",description:"Search past conversation history for specific information, questions, or topics mentioned earlier in this conversation.",category:"search",parameters:{type:"object",properties:{query:{type:"string",description:"Keywords or phrases to search for in conversation history."},limit:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},execute:async v=>{let k=await h.search(s,String(v.query??""),{limit:typeof v.limit=="number"?v.limit:5});return{results:k.map(x=>({role:x.participant.kind==="agent"?"assistant":"user",content:x.content,timestamp:x.timestamp})),count:k.length}}})}if(this.delegation?.enabled&&this._registry){let h=this.delegation.allowedAgents,v=this._registry.getAllAgents().filter(k=>k.name!==this.name&&(h===void 0||h.includes(k.name)));if(v.length>0){let k=v.map(A=>A.name),x=v.map(A=>`- ${A.name}: ${A.description}`).join(`
|
|
3
|
+
`);this.delegation.mode==="forget"?m.push({name:"delegate_and_forget",displayName:"Delegate and Forget",description:`Hand off the current task to a peer agent. The agent will handle its own delivery (e.g. posting to Slack or GitHub) \u2014 you do not need to relay its response. Call this ONCE, then output an empty string.
|
|
4
4
|
|
|
5
5
|
Available agents:
|
|
6
|
-
${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async
|
|
6
|
+
${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async A=>{let b=String(A.agent),I=String(A.message??"");return this._registry.invoke(b,{message:I,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal}).catch(T=>{console.error(`[${this.name}] delegate_and_forget to ${b} failed:`,T)}),{status:"delegated",agent:b}}}):m.push({name:"delegate_to_agent",displayName:"Delegate to Agent",description:`Hand off the current task to a peer agent and return its result. Use when the task falls outside your own specialisation.
|
|
7
7
|
|
|
8
8
|
Available agents:
|
|
9
|
-
${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async
|
|
9
|
+
${x}`,category:"agent",parameters:{type:"object",properties:{agent:{type:"string",enum:k,description:"Name of the agent to delegate to."},message:{type:"string",description:"The task or message to pass to the agent."}},required:["agent","message"]},execute:async A=>{let b=String(A.agent),I=String(A.message??""),T=await this._registry.invoke(b,{message:I,conversationId:s,context:{delegatedBy:this.name},signal:t?.signal});return{...T,output:`[Response from ${b} \u2014 task complete]
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`),
|
|
13
|
-
`:""
|
|
11
|
+
${T.output}`}}})}}if(this.spawn?.enabled&&this.spawn.templates.length>0){let h=n?.spawnDepth??0,v=this.spawn,k=v.maxDepth??3;if(h<k){let x=v.templates,A=x.some(C=>C.name==="self"),b=x.some(C=>C.allowPromptAddition),I=x.filter(C=>C.name!=="self").map(C=>`- ${C.name}: ${C.description}`).join(`
|
|
12
|
+
`),T=A?`Use template name "self" to spawn a replica of the current agent.
|
|
13
|
+
`:"",$=b?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{};m.push({name:"spawn_agent",displayName:"Spawn Agent",description:`Instantiate a temporary helper agent for a focused sub-task. The agent runs once, returns its result, then is discarded.
|
|
14
14
|
|
|
15
15
|
Available templates:
|
|
16
16
|
${I}
|
|
17
|
-
`+
|
|
17
|
+
`+T+`Spawn depth: ${h}/${k}`,category:"agent",parameters:{type:"object",properties:{template:{type:"string",description:A?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for the spawned agent."},...$},required:["template","task"]},execute:async C=>{let D=String(C.template),j=String(C.task??""),V,G,O,L,R=x.find(B=>B.name===D);if(!R)throw new Error(`Unknown spawn template: "${D}"`);let H=R.allowPromptAddition&&C.systemPromptAddition?`
|
|
18
18
|
|
|
19
|
-
${String(C.systemPromptAddition)}`:"";if(
|
|
19
|
+
${String(C.systemPromptAddition)}`:"";if(D==="self"){let B=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,z=R.systemPrompt(j);V={...B,name:`${B.name}-replica-${Date.now()}`,systemPrompt:(B.systemPrompt??"")+(z?`
|
|
20
20
|
|
|
21
|
-
${z}`:"")+H}
|
|
21
|
+
${z}`:"")+H},G=`${this.name}-replica`,O=this.description,L=this.model}else V={...N.AGENT_MODE,name:`ephemeral-${R.name}-${Date.now()}`,systemPrompt:R.systemPrompt(j)+H},G=R.name,O=R.description,L=R.model;let{EphemeralAgent:W}=await Promise.resolve().then(()=>(Ae(),we)),q=new W(G,O,V,{toolpack:this.toolpack});L&&(q.model=L),q.spawn={...v};let F=await q.invokeAgent({message:j,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:F.output,spawnedTemplate:D,depth:h+1,metadata:F.metadata}}}),m.push({name:"spawn_agents_parallel",displayName:"Spawn Agents in Parallel",description:`Instantiate multiple helper agents simultaneously and wait for all to finish. Use when sub-tasks are independent and can run concurrently.
|
|
22
22
|
|
|
23
23
|
Available templates:
|
|
24
24
|
${I}
|
|
25
|
-
`+
|
|
25
|
+
`+T+`Spawn depth: ${h}/${k}`,category:"agent",parameters:{type:"object",properties:{tasks:{type:"array",description:"List of agents to spawn in parallel.",items:{type:"object",properties:{template:{type:"string",description:A?'Template name to spawn, or "self" for a self-replica.':"Template name to spawn."},task:{type:"string",description:"The specific task message for this agent."},...b?{systemPromptAddition:{type:"string",description:"Optional extra instructions appended to the template's system prompt (only honoured by templates that allow it)."}}:{}},required:["template","task"]}}},required:["tasks"]},execute:async C=>{let D=C.tasks;if(!Array.isArray(D)||D.length===0)throw new Error("spawn_agents_parallel requires at least one task.");let{EphemeralAgent:j}=await Promise.resolve().then(()=>(Ae(),we));return{results:await Promise.all(D.map(async G=>{let O=String(G.template),L=String(G.task??""),R=x.find(K=>K.name===O);if(!R)throw new Error(`Unknown spawn template: "${O}"`);let H=R.allowPromptAddition&&G.systemPromptAddition?`
|
|
26
26
|
|
|
27
|
-
${String(
|
|
27
|
+
${String(G.systemPromptAddition)}`:"",W,q,F,B;if(O==="self"){let K=typeof this.mode=="string"?{...N.AGENT_MODE,name:this.mode}:this.mode,ke=R.systemPrompt(L);W={...K,name:`${K.name}-replica-${Date.now()}`,systemPrompt:(K.systemPrompt??"")+(ke?`
|
|
28
28
|
|
|
29
|
-
${ke}`:"")+H},q=`${this.name}-replica`,F=this.description,
|
|
29
|
+
${ke}`:"")+H},q=`${this.name}-replica`,F=this.description,B=this.model}else W={...N.AGENT_MODE,name:`ephemeral-${R.name}-${Date.now()}`,systemPrompt:R.systemPrompt(L)+H},q=R.name,F=R.description,B=R.model;let z=new j(q,F,W,{toolpack:this.toolpack});B&&(z.model=B),z.spawn={...v};let ve=await z.invokeAgent({message:L,conversationId:`spawn-${Date.now()}`,context:{spawnedBy:this.name,spawnDepth:h+1}});return{output:ve.output,spawnedTemplate:O,depth:h+1,metadata:ve.metadata}}))}}})}}let u={messages:c,model:this.model||"",requestTools:m.length>0?m:void 0,maxToolRounds:t?.maxToolRounds,...t?.interceptTool?{interceptTool:t.interceptTool}:{},mode:this.mode,signal:t?.signal,...t?.maxTokens?{max_tokens:t.maxTokens}:{}},g=null,d,w,f=!1;if(typeof this.mode!="string"&&this.mode?.streaming||!!t?.onChunk){let h="";for await(let v of this.toolpack.stream(u,this.provider))v.delta&&(h+=v.delta,t?.onChunk?.(v.delta)),v.usage&&(d=v.usage),v.finish_reason==="aborted"&&(f=!0);g=h||null,w={content:g,usage:d}}else{let h=await this.toolpack.generate(u,this.provider);g=h.content??null,d=h.usage,w=h}let P={output:g||"",steps:this.extractSteps(w),metadata:d?{usage:d}:void 0};if(f&&(P.metadata={...P.metadata,aborted:!0}),await this.onComplete(P),o)try{await o(f)}catch(h){console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush failed; the reply is kept:`,h),P.metadata={...P.metadata,mindSaveError:h instanceof Error?h.message:String(h)}}return this.emit("agent:complete",P),P}catch(c){throw o&&o(!0).catch(l=>{console.error(`[${this.name??"agent"}][AgentMind] Draft buffer flush on error failed:`,l)}),await this.onError(c),this.emit("agent:error",c),c}}getAgentAliases(){let e=[];for(let t of this.channels){let n=t.botUserId;n&&e.push(n)}return e}async sendTo(e,t){if(!this._registry)throw new Error("Agent not registered - _registry not set");await this._registry.sendTo(e,{output:t})}async ask(e,t){if(!this._registry)throw new E("Agent not registered - cannot use ask()");let n=this._ctx()?.conversationId??this._conversationId,i=this._ctx()?.isTriggerChannel??this._isTriggerChannel,s=this._ctx()?.triggeringChannel??this._triggeringChannel;if(!n)throw new E("No conversationId available - ask() requires a conversation channel");if(i)throw new E("this.ask() called from a trigger channel (ScheduledChannel). Trigger channels have no human recipient \u2014 use a conversation channel (Slack, Telegram, Webhook) instead.");if(!s||s.trim()==="")throw new E("Cannot use ask() - no triggering channel available. The channel must have a name registered with AgentRegistry.");let o=this._registry.addPendingAsk({conversationId:n,agentName:this.name,question:e,context:t?.context??{},maxRetries:t?.maxRetries??2,expiresAt:t?.expiresIn?new Date(Date.now()+t.expiresIn):void 0,channelName:s});return await this.sendTo(s,e),{output:e,metadata:{waitingForHuman:!0,askId:o.id}}}getPendingAsk(e){if(!this._registry)return null;let t=e??this._ctx()?.conversationId??this._conversationId;return t?this._registry.getPendingAsk(t)??null:null}async resolvePendingAsk(e,t){if(!this._registry)throw new E("Agent not registered - cannot resolve ask");await this._registry.resolvePendingAsk(e,t)}async evaluateAnswer(e,t,n){if(n?.simpleValidation)return n.simpleValidation(t);let i=this._ctx()?.conversationId??this._conversationId;return(await this.run(`Evaluate if this answer sufficiently addresses the question.
|
|
30
30
|
|
|
31
31
|
Question: "${e}"
|
|
32
32
|
Answer: "${t}"
|
|
33
33
|
|
|
34
|
-
Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new
|
|
35
|
-
`)},te=class extends
|
|
36
|
-
Recent conversation:`);for(let
|
|
34
|
+
Is this answer sufficient? Reply with ONLY "yes" or "no".`,{workflow:{mode:"single-shot"}},{conversationId:i})).output.toLowerCase().trim().startsWith("yes")}async handlePendingAsk(e,t,n,i){if(await this.evaluateAnswer(e.question,t,{simpleValidation:o=>o.trim().length>3}))return await this.resolvePendingAsk(e.id,t),n(t);if(e.retries>=e.maxRetries){await this.resolvePendingAsk(e.id,"__insufficient__");let o=this._ctx()?.triggeringChannel??this._triggeringChannel;return o&&await this.sendTo(o,"I was unable to get enough information to proceed. Skipping this step."),i?i():{output:"Step skipped due to insufficient input.",metadata:{skipped:!0,askId:e.id}}}return this._registry?.incrementRetries(e.id),this.ask(`I need a bit more clarity on: "${e.question}". Could you provide more details?`,{context:e.context,maxRetries:e.maxRetries})}async delegateAndWait(e,t){if(!this._registry)throw new E("Agent not registered - cannot use delegateAndWait()");let n={message:t.message,intent:t.intent,data:t.data,context:{...t.context||{},delegatedBy:this.name},conversationId:t.conversationId||this._ctx()?.conversationId||this._conversationId||`delegation-${Date.now()}`};return await this._registry.invoke(e,n)}async onBeforeRun(e){}async onComplete(e){}async onError(e){}_resolveAssemblerOptions(){let e=this.channels.map(i=>i.botUserId).filter(i=>typeof i=="string"&&i.length>0),t=this.assemblerOptions?.agentAliases??[];if(e.length===0&&t.length===0)return this.assemblerOptions;let n=Array.from(new Set([...t,...e]));return{...this.assemblerOptions,agentAliases:n}}_getEffectiveInterceptors(){return this.interceptors.some(t=>t[ae]===!0)?this.interceptors:[_e({store:this.conversationHistory}),...this.interceptors]}_bindChannel(e){e.onMessage(async t=>{if(!t.conversationId){console.warn(`[${this.name}] Message received without conversationId \u2014 skipping`);return}let n=await this._acquireConversationLock(t.conversationId);await this._channelCtx.run({conversationId:t.conversationId,triggeringChannel:e.name??"",isTriggerChannel:e.isTriggerChannel},async()=>{try{let i=xe(this._getEffectiveInterceptors(),this,e,this._registry??null),s=await Re(i,t);if(s===null)return;let o={output:s.output,metadata:s.metadata};await e.send({output:o.output,metadata:{...o.metadata,conversationId:t.conversationId,...t.context}})}catch(i){let s=i instanceof Error?i.message:"Unknown error occurred";console.error(`[${this.name}] Error in agent invocation: ${s}`);try{await e.send({output:`Error: ${s}`,metadata:{conversationId:t.conversationId,error:!0,...t.context}})}catch(o){console.error(`[${this.name}] Failed to send error to channel: ${o}`)}}finally{n()}})})}async _acquireConversationLock(e){for(;this._conversationLocks.has(e);)try{await this._conversationLocks.get(e)}catch{}let t,n=new Promise(i=>{t=i});return this._conversationLocks.set(e,n),()=>{this._conversationLocks.delete(e),t()}}extractSteps(e){let t=e;if(t.plan&&typeof t.plan=="object"){let n=t.plan;if(Array.isArray(n.steps))return n.steps.map(i=>({number:i.number||0,description:i.description||"",status:i.status||"completed",result:i.result}))}if(Array.isArray(t.steps))return t.steps}}});var Bt={};ie(Bt,{IntentClassifierAgent:()=>te,SummarizerAgent:()=>ne});module.exports=it(Bt);y();y();ee();var Je=require("toolpack-sdk"),Pt={...Je.CHAT_MODE,name:"intent-classifier-mode",systemPrompt:["You classify whether a message is asking an agent to respond.","","Categories:","direct = Message uses @mention, name in greeting, possessive, or commands the agent to act","indirect = Agent is mentioned but unclear if response wanted (talking ABOUT, not TO them)","passive = No addressing detected; agent should only listen, not reply","ignore = Definitely not for this agent (noise, code blocks, other bots)","","Response must start with one of: direct, indirect, passive, ignore"].join(`
|
|
35
|
+
`)},te=class extends U{name="intent-classifier";description="Classifies whether a message is directly addressing an agent for response";mode=Pt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(t?.isDirectMessage)return{output:"direct",metadata:{classification:"direct",shortCircuit:"dm"}};if(!t?.message)return{output:"ignore",metadata:{error:"No message provided for classification"}};let n=[];if(n.push(`Context: Public channel #${t.channelName}`),n.push(`Target agent: "${t.agentName}" (ID: ${t.agentId})`),n.push(`Message sender: ${t.senderName}`),t.recentContext&&t.recentContext.length>0){n.push(`
|
|
36
|
+
Recent conversation:`);for(let p of t.recentContext)n.push(` ${p.sender}: ${p.content.substring(0,100)}`)}n.push(`
|
|
37
37
|
Message to classify: "${t.message}"`),t.includeExamples&&(n.push(`
|
|
38
38
|
Examples of classifications:`),n.push(` "@${t.agentName} help me" \u2192 direct`),n.push(` "Can someone ask ${t.agentName} about this?" \u2192 indirect`),n.push(` "I was talking to ${t.agentName} earlier" \u2192 passive`),n.push(' "Check the logs" \u2192 ignore')),n.push(`
|
|
39
39
|
Classification (start with direct, indirect, passive, or ignore):`);let i=n.join(`
|
|
40
|
-
`),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:n.includes("indirect")||n.includes("mention")?"indirect":n.includes("passive")||n.includes("listen")?"passive":n.includes("ignore")||n.includes("skip")?"ignore":n.includes("direct")||n.includes("addressed")?"direct":"ignore"}};y();ee();var
|
|
41
|
-
`)},ne=class extends
|
|
42
|
-
`),
|
|
40
|
+
`),s=await this.run(i),o=this.normalizeClassification(s.output);return{output:o,metadata:{rawOutput:s.output,classification:o,confidence:"high"}}}normalizeClassification(e){let t=e.toLowerCase().trim().split(/\s+/)[0],n=e.toLowerCase();return["direct","indirect","passive","ignore"].includes(t)?t:n.includes("indirect")||n.includes("mention")?"indirect":n.includes("passive")||n.includes("listen")?"passive":n.includes("ignore")||n.includes("skip")?"ignore":n.includes("direct")||n.includes("addressed")?"direct":"ignore"}};y();ee();var Ye=require("toolpack-sdk"),Dt={...Ye.CHAT_MODE,name:"summarizer-mode",systemPrompt:["You are a conversation summarizer for multi-participant chat histories.","Your job is to compress older conversation turns into a dense summary that preserves:","","1. Key facts and information shared","2. Decisions made or action items assigned","3. Context relevant to the target agent's perspective","4. Important questions asked or problems raised","","Summarize from the perspective of the target agent.","If the agent was not addressed in a turn, note it as observed context.","Use bullet points for clarity. Be concise but complete.","","Output format: Return ONLY a JSON object with these fields:","- summary: string (the summary text)","- turnsSummarized: number (count of turns processed)","- hasDecisions: boolean (whether any decisions/action items were found)","- estimatedTokens: number (rough estimate: characters / 4)","","Do not include markdown code blocks, just the raw JSON."].join(`
|
|
41
|
+
`)},ne=class extends U{name="summarizer";description="Compresses conversation history into compact summaries for prompt assembly";mode=Dt;constructor(e){super(e)}async invokeAgent(e){let t=e.data;if(!t?.turns||t.turns.length===0)return{output:JSON.stringify({summary:"(No history to summarize)",turnsSummarized:0,hasDecisions:!1,estimatedTokens:5}),metadata:{emptyInput:!0}};let n=t.maxTokens??800,i=t.extractDecisions??!0,s=[`Target agent: "${t.agentName}" (ID: ${t.agentId})`,`Maximum summary length: ~${n} tokens`,`Extract decisions/action items: ${i?"yes":"no"}`,"",`Conversation turns to summarize (${t.turns.length} turns):`,""];for(let l of t.turns){let m=new Date(l.timestamp).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),u=l.participant.displayName??l.participant.id,g=l.participant.kind==="agent"?`[BOT] ${u}`:u,d=`[${m}] ${g}: ${l.content.substring(0,200)}`;l.content.length>200&&(d+="..."),l.metadata?.isToolCall&&l.metadata.toolName&&(d+=` [tool: ${l.metadata.toolName}]`),s.push(d)}s.push("","Generate a JSON summary object:");let o=s.join(`
|
|
42
|
+
`),p=await this.run(o),c=this.parseSummarizerOutput(p.output,t.turns.length);return{output:JSON.stringify(c),metadata:{turnsProcessed:t.turns.length,rawOutputLength:p.output.length}}}parseSummarizerOutput(e,t){let n=e.trim(),i=n.match(/```(?:json)?\s*([\s\S]*?)\s*```/);i&&(n=i[1].trim());try{let s=JSON.parse(n);return{summary:typeof s.summary=="string"&&s.summary.length>0?s.summary:this.generateFallbackSummary(t),turnsSummarized:typeof s.turnsSummarized=="number"?s.turnsSummarized:t,hasDecisions:typeof s.hasDecisions=="boolean"?s.hasDecisions:!1,estimatedTokens:typeof s.estimatedTokens=="number"&&s.estimatedTokens>0?s.estimatedTokens:Math.ceil(e.length/4)}}catch{return{summary:this.generateFallbackSummary(t),turnsSummarized:t,hasDecisions:e.toLowerCase().includes("decision")||e.toLowerCase().includes("action"),estimatedTokens:Math.ceil(e.length/4)}}}generateFallbackSummary(e){return`(Summary of ${e} conversation turns - key details preserved in full context)`}};0&&(module.exports={IntentClassifierAgent,SummarizerAgent});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-
|
|
2
|
-
import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-
|
|
3
|
-
import { B as BaseAgent } from '../base-agent-
|
|
1
|
+
export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-A4thJQ0z.cjs';
|
|
2
|
+
import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C_2Rkpio.cjs';
|
|
3
|
+
import { B as BaseAgent } from '../base-agent-YX0G2Ur3.cjs';
|
|
4
4
|
import { Participant, ModeConfig } from 'toolpack-sdk';
|
|
5
5
|
export { Participant } from 'toolpack-sdk';
|
|
6
6
|
import 'events';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-
|
|
2
|
-
import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-
|
|
3
|
-
import { B as BaseAgent } from '../base-agent-
|
|
1
|
+
export { I as IntentClassification, a as IntentClassifierAgent, b as IntentClassifierInput } from '../intent-classifier-agent-DXlxbZ_r.js';
|
|
2
|
+
import { B as BaseAgentOptions, A as AgentInput, a as AgentResult } from '../types-C_2Rkpio.js';
|
|
3
|
+
import { B as BaseAgent } from '../base-agent-5Dbq8iQi.js';
|
|
4
4
|
import { Participant, ModeConfig } from 'toolpack-sdk';
|
|
5
5
|
export { Participant } from 'toolpack-sdk';
|
|
6
6
|
import 'events';
|