@positronic/mem0 0.0.57

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.
@@ -0,0 +1,301 @@
1
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
+ try {
3
+ var info = gen[key](arg);
4
+ var value = info.value;
5
+ } catch (error) {
6
+ reject(error);
7
+ return;
8
+ }
9
+ if (info.done) {
10
+ resolve(value);
11
+ } else {
12
+ Promise.resolve(value).then(_next, _throw);
13
+ }
14
+ }
15
+ function _async_to_generator(fn) {
16
+ return function() {
17
+ var self = this, args = arguments;
18
+ return new Promise(function(resolve, reject) {
19
+ var gen = fn.apply(self, args);
20
+ function _next(value) {
21
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
+ }
23
+ function _throw(err) {
24
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
+ }
26
+ _next(undefined);
27
+ });
28
+ };
29
+ }
30
+ function _ts_generator(thisArg, body) {
31
+ var f, y, t, _ = {
32
+ label: 0,
33
+ sent: function() {
34
+ if (t[0] & 1) throw t[1];
35
+ return t[1];
36
+ },
37
+ trys: [],
38
+ ops: []
39
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
40
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
41
+ return this;
42
+ }), g;
43
+ function verb(n) {
44
+ return function(v) {
45
+ return step([
46
+ n,
47
+ v
48
+ ]);
49
+ };
50
+ }
51
+ function step(op) {
52
+ if (f) throw new TypeError("Generator is already executing.");
53
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
54
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
55
+ if (y = 0, t) op = [
56
+ op[0] & 2,
57
+ t.value
58
+ ];
59
+ switch(op[0]){
60
+ case 0:
61
+ case 1:
62
+ t = op;
63
+ break;
64
+ case 4:
65
+ _.label++;
66
+ return {
67
+ value: op[1],
68
+ done: false
69
+ };
70
+ case 5:
71
+ _.label++;
72
+ y = op[1];
73
+ op = [
74
+ 0
75
+ ];
76
+ continue;
77
+ case 7:
78
+ op = _.ops.pop();
79
+ _.trys.pop();
80
+ continue;
81
+ default:
82
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
83
+ _ = 0;
84
+ continue;
85
+ }
86
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
87
+ _.label = op[1];
88
+ break;
89
+ }
90
+ if (op[0] === 6 && _.label < t[1]) {
91
+ _.label = t[1];
92
+ t = op;
93
+ break;
94
+ }
95
+ if (t && _.label < t[2]) {
96
+ _.label = t[2];
97
+ _.ops.push(op);
98
+ break;
99
+ }
100
+ if (t[2]) _.ops.pop();
101
+ _.trys.pop();
102
+ continue;
103
+ }
104
+ op = body.call(thisArg, _);
105
+ } catch (e) {
106
+ op = [
107
+ 6,
108
+ e
109
+ ];
110
+ y = 0;
111
+ } finally{
112
+ f = t = 0;
113
+ }
114
+ if (op[0] & 5) throw op[1];
115
+ return {
116
+ value: op[0] ? op[1] : void 0,
117
+ done: true
118
+ };
119
+ }
120
+ }
121
+ import { BRAIN_EVENTS } from '@positronic/core';
122
+ /**
123
+ * Creates a Mem0 adapter that automatically indexes conversations to memory.
124
+ *
125
+ * The adapter listens to brain events and buffers messages from agent steps.
126
+ * When the brain completes or encounters an error, it flushes the buffered
127
+ * messages to the memory provider.
128
+ *
129
+ * @param config - Configuration for the adapter
130
+ * @returns An Adapter implementation
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * import { createMem0Adapter, createMem0Provider } from '@positronic/mem0';
135
+ * import { BrainRunner } from '@positronic/core';
136
+ *
137
+ * const provider = createMem0Provider({ apiKey: process.env.MEM0_API_KEY! });
138
+ * const adapter = createMem0Adapter({ provider });
139
+ *
140
+ * const runner = new BrainRunner({
141
+ * adapters: [adapter],
142
+ * client,
143
+ * });
144
+ *
145
+ * await runner.run(myBrain);
146
+ * ```
147
+ */ export function createMem0Adapter(config) {
148
+ var provider = config.provider, _config_includeToolCalls = config.includeToolCalls, includeToolCalls = _config_includeToolCalls === void 0 ? false : _config_includeToolCalls;
149
+ // Buffer messages per brainRunId
150
+ var buffers = new Map();
151
+ return {
152
+ dispatch: function dispatch(event) {
153
+ return _async_to_generator(function() {
154
+ var brainRunId, agentId, buffer, buffer1, buffer2, buffer3, buffer4;
155
+ return _ts_generator(this, function(_state) {
156
+ switch(_state.label){
157
+ case 0:
158
+ brainRunId = event.brainRunId;
159
+ // Handle AGENT_START - initialize buffer for this run
160
+ if (event.type === BRAIN_EVENTS.AGENT_START) {
161
+ agentId = event.stepTitle; // Use step title as agentId
162
+ // Initialize buffer if not exists
163
+ if (!buffers.has(brainRunId)) {
164
+ buffers.set(brainRunId, {
165
+ agentId: agentId,
166
+ messages: []
167
+ });
168
+ }
169
+ // Add the initial user prompt as a message
170
+ buffer = buffers.get(brainRunId);
171
+ buffer.messages.push({
172
+ role: 'user',
173
+ content: event.prompt
174
+ });
175
+ }
176
+ // Handle AGENT_USER_MESSAGE - add user message to buffer
177
+ if (event.type === BRAIN_EVENTS.AGENT_USER_MESSAGE) {
178
+ buffer1 = buffers.get(brainRunId);
179
+ if (buffer1) {
180
+ buffer1.messages.push({
181
+ role: 'user',
182
+ content: event.content
183
+ });
184
+ }
185
+ }
186
+ // Handle AGENT_ASSISTANT_MESSAGE - add assistant message to buffer
187
+ if (event.type === BRAIN_EVENTS.AGENT_ASSISTANT_MESSAGE) {
188
+ buffer2 = buffers.get(brainRunId);
189
+ if (buffer2) {
190
+ buffer2.messages.push({
191
+ role: 'assistant',
192
+ content: event.content
193
+ });
194
+ }
195
+ }
196
+ // Handle tool calls if configured
197
+ if (includeToolCalls && event.type === BRAIN_EVENTS.AGENT_TOOL_CALL) {
198
+ buffer3 = buffers.get(brainRunId);
199
+ if (buffer3) {
200
+ buffer3.messages.push({
201
+ role: 'assistant',
202
+ content: "[Tool Call: ".concat(event.toolName, "] ").concat(JSON.stringify(event.input))
203
+ });
204
+ }
205
+ }
206
+ if (includeToolCalls && event.type === BRAIN_EVENTS.AGENT_TOOL_RESULT) {
207
+ buffer4 = buffers.get(brainRunId);
208
+ if (buffer4) {
209
+ buffer4.messages.push({
210
+ role: 'assistant',
211
+ content: "[Tool Result: ".concat(event.toolName, "] ").concat(JSON.stringify(event.result))
212
+ });
213
+ }
214
+ }
215
+ if (!(event.type === BRAIN_EVENTS.AGENT_COMPLETE)) return [
216
+ 3,
217
+ 2
218
+ ];
219
+ return [
220
+ 4,
221
+ flushBuffer(brainRunId)
222
+ ];
223
+ case 1:
224
+ _state.sent();
225
+ _state.label = 2;
226
+ case 2:
227
+ if (!(event.type === BRAIN_EVENTS.COMPLETE)) return [
228
+ 3,
229
+ 4
230
+ ];
231
+ return [
232
+ 4,
233
+ flushBuffer(brainRunId)
234
+ ];
235
+ case 3:
236
+ _state.sent();
237
+ _state.label = 4;
238
+ case 4:
239
+ // Handle ERROR - clean up buffer without flushing
240
+ if (event.type === BRAIN_EVENTS.ERROR) {
241
+ buffers.delete(brainRunId);
242
+ }
243
+ // Handle CANCELLED - clean up buffer without flushing
244
+ if (event.type === BRAIN_EVENTS.CANCELLED) {
245
+ buffers.delete(brainRunId);
246
+ }
247
+ return [
248
+ 2
249
+ ];
250
+ }
251
+ });
252
+ })();
253
+ }
254
+ };
255
+ function flushBuffer(brainRunId) {
256
+ return _async_to_generator(function() {
257
+ var buffer;
258
+ return _ts_generator(this, function(_state) {
259
+ switch(_state.label){
260
+ case 0:
261
+ buffer = buffers.get(brainRunId);
262
+ if (!buffer || buffer.messages.length === 0) {
263
+ buffers.delete(brainRunId);
264
+ return [
265
+ 2
266
+ ];
267
+ }
268
+ _state.label = 1;
269
+ case 1:
270
+ _state.trys.push([
271
+ 1,
272
+ ,
273
+ 3,
274
+ 4
275
+ ]);
276
+ return [
277
+ 4,
278
+ provider.add(buffer.messages, {
279
+ agentId: buffer.agentId
280
+ })
281
+ ];
282
+ case 2:
283
+ _state.sent();
284
+ return [
285
+ 3,
286
+ 4
287
+ ];
288
+ case 3:
289
+ buffers.delete(brainRunId);
290
+ return [
291
+ 7
292
+ ];
293
+ case 4:
294
+ return [
295
+ 2
296
+ ];
297
+ }
298
+ });
299
+ })();
300
+ }
301
+ }
@@ -0,0 +1,275 @@
1
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
+ try {
3
+ var info = gen[key](arg);
4
+ var value = info.value;
5
+ } catch (error) {
6
+ reject(error);
7
+ return;
8
+ }
9
+ if (info.done) {
10
+ resolve(value);
11
+ } else {
12
+ Promise.resolve(value).then(_next, _throw);
13
+ }
14
+ }
15
+ function _async_to_generator(fn) {
16
+ return function() {
17
+ var self = this, args = arguments;
18
+ return new Promise(function(resolve, reject) {
19
+ var gen = fn.apply(self, args);
20
+ function _next(value) {
21
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
+ }
23
+ function _throw(err) {
24
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
+ }
26
+ _next(undefined);
27
+ });
28
+ };
29
+ }
30
+ function _ts_generator(thisArg, body) {
31
+ var f, y, t, _ = {
32
+ label: 0,
33
+ sent: function() {
34
+ if (t[0] & 1) throw t[1];
35
+ return t[1];
36
+ },
37
+ trys: [],
38
+ ops: []
39
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
40
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
41
+ return this;
42
+ }), g;
43
+ function verb(n) {
44
+ return function(v) {
45
+ return step([
46
+ n,
47
+ v
48
+ ]);
49
+ };
50
+ }
51
+ function step(op) {
52
+ if (f) throw new TypeError("Generator is already executing.");
53
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
54
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
55
+ if (y = 0, t) op = [
56
+ op[0] & 2,
57
+ t.value
58
+ ];
59
+ switch(op[0]){
60
+ case 0:
61
+ case 1:
62
+ t = op;
63
+ break;
64
+ case 4:
65
+ _.label++;
66
+ return {
67
+ value: op[1],
68
+ done: false
69
+ };
70
+ case 5:
71
+ _.label++;
72
+ y = op[1];
73
+ op = [
74
+ 0
75
+ ];
76
+ continue;
77
+ case 7:
78
+ op = _.ops.pop();
79
+ _.trys.pop();
80
+ continue;
81
+ default:
82
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
83
+ _ = 0;
84
+ continue;
85
+ }
86
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
87
+ _.label = op[1];
88
+ break;
89
+ }
90
+ if (op[0] === 6 && _.label < t[1]) {
91
+ _.label = t[1];
92
+ t = op;
93
+ break;
94
+ }
95
+ if (t && _.label < t[2]) {
96
+ _.label = t[2];
97
+ _.ops.push(op);
98
+ break;
99
+ }
100
+ if (t[2]) _.ops.pop();
101
+ _.trys.pop();
102
+ continue;
103
+ }
104
+ op = body.call(thisArg, _);
105
+ } catch (e) {
106
+ op = [
107
+ 6,
108
+ e
109
+ ];
110
+ y = 0;
111
+ } finally{
112
+ f = t = 0;
113
+ }
114
+ if (op[0] & 5) throw op[1];
115
+ return {
116
+ value: op[0] ? op[1] : void 0,
117
+ done: true
118
+ };
119
+ }
120
+ }
121
+ /**
122
+ * Formats memories into a readable string format.
123
+ *
124
+ * @param memories - Array of memories to format
125
+ * @param options - Formatting options
126
+ * @returns Formatted string representation of the memories
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * const memories = await memory.search('user preferences');
131
+ * const formatted = formatMemories(memories);
132
+ * // Returns:
133
+ * // 1. User prefers dark mode
134
+ * // 2. User likes concise responses
135
+ *
136
+ * const formattedWithHeader = formatMemories(memories, {
137
+ * header: 'Known user preferences:',
138
+ * includeScores: true,
139
+ * });
140
+ * // Returns:
141
+ * // Known user preferences:
142
+ * // 1. User prefers dark mode (0.95)
143
+ * // 2. User likes concise responses (0.82)
144
+ * ```
145
+ */ export function formatMemories(memories) {
146
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
147
+ var header = options.header, _options_includeScores = options.includeScores, includeScores = _options_includeScores === void 0 ? false : _options_includeScores, _options_emptyText = options.emptyText, emptyText = _options_emptyText === void 0 ? '' : _options_emptyText;
148
+ if (!memories || memories.length === 0) {
149
+ return emptyText;
150
+ }
151
+ var lines = [];
152
+ if (header) {
153
+ lines.push(header);
154
+ }
155
+ memories.forEach(function(memory, index) {
156
+ var line = "".concat(index + 1, ". ").concat(memory.content);
157
+ if (includeScores && memory.score !== undefined) {
158
+ line += " (".concat(memory.score.toFixed(2), ")");
159
+ }
160
+ lines.push(line);
161
+ });
162
+ return lines.join('\n');
163
+ }
164
+ /**
165
+ * Creates a system prompt augmented with relevant memories.
166
+ *
167
+ * This is a convenience function that:
168
+ * 1. Fetches relevant memories using the provided query
169
+ * 2. Formats them nicely
170
+ * 3. Appends them to your base system prompt
171
+ *
172
+ * @param memory - The scoped memory instance
173
+ * @param basePrompt - The base system prompt
174
+ * @param query - The search query for finding relevant memories
175
+ * @param options - Search and formatting options
176
+ * @returns The augmented system prompt
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * const myBrain = brain('my-brain')
181
+ * .withMemory(provider)
182
+ * .brain('agent', async ({ memory }) => {
183
+ * const system = await createMemorySystemPrompt(
184
+ * memory,
185
+ * 'You are a helpful assistant.',
186
+ * 'user preferences',
187
+ * { userId: 'user-123', memoriesHeader: '\n\nUser context:' }
188
+ * );
189
+ *
190
+ * return { system, prompt: 'Help me with my task' };
191
+ * });
192
+ * ```
193
+ */ export function createMemorySystemPrompt(_0, _1, _2) {
194
+ return _async_to_generator(function(memory, basePrompt, query) {
195
+ var options, userId, limit, _options_memoriesHeader, memoriesHeader, _options_includeScores, includeScores, memories, formattedMemories;
196
+ var _arguments = arguments;
197
+ return _ts_generator(this, function(_state) {
198
+ switch(_state.label){
199
+ case 0:
200
+ options = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : {};
201
+ userId = options.userId, limit = options.limit, _options_memoriesHeader = options.memoriesHeader, memoriesHeader = _options_memoriesHeader === void 0 ? '\n\nRelevant context from previous interactions:' : _options_memoriesHeader, _options_includeScores = options.includeScores, includeScores = _options_includeScores === void 0 ? false : _options_includeScores;
202
+ return [
203
+ 4,
204
+ memory.search(query, {
205
+ userId: userId,
206
+ limit: limit
207
+ })
208
+ ];
209
+ case 1:
210
+ memories = _state.sent();
211
+ if (memories.length === 0) {
212
+ return [
213
+ 2,
214
+ basePrompt
215
+ ];
216
+ }
217
+ formattedMemories = formatMemories(memories, {
218
+ header: memoriesHeader,
219
+ includeScores: includeScores
220
+ });
221
+ return [
222
+ 2,
223
+ "".concat(basePrompt).concat(formattedMemories)
224
+ ];
225
+ }
226
+ });
227
+ }).apply(this, arguments);
228
+ }
229
+ /**
230
+ * Creates a memory context block for including in prompts.
231
+ *
232
+ * Similar to createMemorySystemPrompt but returns just the memory
233
+ * context block, not the full system prompt. Useful when you want
234
+ * more control over prompt construction.
235
+ *
236
+ * @param memory - The scoped memory instance
237
+ * @param query - The search query for finding relevant memories
238
+ * @param options - Search and formatting options
239
+ * @returns Formatted memory context block or empty string
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * const context = await getMemoryContext(memory, 'user preferences', {
244
+ * userId: 'user-123',
245
+ * limit: 5,
246
+ * });
247
+ *
248
+ * const system = `You are helpful.
249
+ *
250
+ * ${context ? `User context:\n${context}` : ''}`;
251
+ * ```
252
+ */ export function getMemoryContext(_0, _1) {
253
+ return _async_to_generator(function(memory, query) {
254
+ var options, memories;
255
+ var _arguments = arguments;
256
+ return _ts_generator(this, function(_state) {
257
+ switch(_state.label){
258
+ case 0:
259
+ options = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : {};
260
+ return [
261
+ 4,
262
+ memory.search(query, options)
263
+ ];
264
+ case 1:
265
+ memories = _state.sent();
266
+ return [
267
+ 2,
268
+ formatMemories(memories, {
269
+ emptyText: ''
270
+ })
271
+ ];
272
+ }
273
+ });
274
+ }).apply(this, arguments);
275
+ }
@@ -0,0 +1,8 @@
1
+ // Provider
2
+ export { createMem0Provider } from './provider.js';
3
+ // Tools
4
+ export { createMem0Tools, rememberFact, recallMemories } from './tools.js';
5
+ // Adapter
6
+ export { createMem0Adapter } from './adapter.js';
7
+ // Helpers
8
+ export { formatMemories, createMemorySystemPrompt, getMemoryContext } from './helpers.js';