Repository navigation
Expand file tree
/
Copy pathmemory.js
More file actions
227 lines (193 loc) · 7.46 KB
/
Copy pathmemory.js
File metadata and controls
227 lines (193 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// memory.js - Memory extraction and matching for OpenAgent
// Extracts key facts from conversations and matches relevant memories
// ─── Fact Extraction ───────────────────────────────────────────────────────────
function extractFactsFromMessages(messages) {
const facts = [];
const conversationText = messages
.filter((m) => m.role === 'user' || m.role === 'assistant')
.map((m) => m.content)
.join(' ');
// Extract URLs
const urlRegex = /https?:\/\/[^\s<>"{}|\\^`\[\]]+/g;
const urls = conversationText.match(urlRegex) || [];
if (urls.length > 0) {
facts.push({
type: 'url',
fact: `Links discussed: ${urls.join(', ')}`,
topics: ['urls', 'links'],
});
}
// Extract code snippets (simple heuristic)
const codeRegex = /`{1,3}[\s\S]*?`{1,3}/g;
const codeMatches = conversationText.match(codeRegex) || [];
if (codeMatches.length > 0) {
const codeSummary = codeMatches.slice(0, 3).map((c) => c.slice(0, 80)).join('; ');
facts.push({
type: 'code',
fact: `Code snippets: ${codeSummary}`,
topics: ['code', 'programming'],
});
}
// Extract emails
const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
const emails = conversationText.match(emailRegex) || [];
if (emails.length > 0) {
facts.push({
type: 'email',
fact: `Emails: ${emails.join(', ')}`,
topics: ['contact', 'email'],
});
}
// Extract numbers (prices, versions, counts)
const numberRegex = /\$\d+[\d,]*|\d+\.\d+ version|version \d+[\d.]*|\d+ (items?|entries?|results?)/gi;
const numbers = conversationText.match(numberRegex) || [];
if (numbers.length > 0) {
facts.push({
type: 'numbers',
fact: `Numbers: ${[...new Set(numbers)].slice(0, 5).join(', ')}`,
topics: ['data', 'numbers'],
});
}
return facts;
}
// ─── Topic Extraction ────────────────────────────────────────────────────────────
function extractTopicsFromMessages(messages) {
const text = messages
.filter((m) => m.role === 'user')
.map((m) => m.content)
.join(' ')
.toLowerCase();
const topicKeywords = {
coding: ['code', 'function', 'variable', 'debug', 'bug', 'api', '编程', 'код', 'codigo'],
design: ['design', 'ui', 'ux', 'layout', 'color', 'font', 'дизайн', 'diseño'],
research: ['research', 'study', 'paper', 'article', 'findings', 'badania', 'исследование'],
shopping: ['buy', 'price', 'order', 'product', 'cart', 'купить', 'comprar', 'kaufen'],
travel: ['flight', 'hotel', 'trip', 'travel', 'booking', 'путешествие', 'viaje'],
news: ['news', 'update', 'release', 'announcement', 'новины', 'noticias'],
config: ['settings', 'config', 'setup', 'install', 'configuration', 'настройка'],
};
const foundTopics = [];
for (const [topic, keywords] of Object.entries(topicKeywords)) {
if (keywords.some((kw) => text.includes(kw))) {
foundTopics.push(topic);
}
}
// Extract domain as topic
const domainRegex = /(?:https?:\/\/)?([a-zA-Z0-9-]+\.[a-zA-Z]{2,})/g;
const domains = text.match(domainRegex) || [];
if (domains.length > 0) {
foundTopics.push(...new Set(domains.map((d) => d.replace('www.', ''))));
}
return [...new Set(foundTopics)].slice(0, 5);
}
// ─── Summary Generation ───────────────────────────────────────────────────────
async function generateConversationSummary(messages, pageUrl, apiKey, model, baseUrl) {
if (!apiKey || messages.length === 0) return null;
const conversationText = messages
.filter((m) => m.role === 'user' || m.role === 'assistant')
.map((m) => `${m.role === 'user' ? 'User' : 'Assistant'}: ${m.content}`)
.join('\n\n')
.slice(0, 4000);
const prompt = `Analyze this conversation and create a brief summary (2-3 sentences) covering the main topic and key points discussed. Also extract 3-5 keywords (topics) that describe what this conversation was about.
Return JSON with this exact format:
{
"summary": "...",
"topics": ["topic1", "topic2", "topic3"],
"key_facts": ["fact 1", "fact 2"]
}
Conversation:
${conversationText}`;
try {
const endpoint = (baseUrl || 'https://openrouter.ai/api/v1').replace(/\/+$/, '') + '/chat/completions';
const headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
if (baseUrl && baseUrl.includes('openrouter.ai')) {
headers['HTTP-Referer'] = chrome.runtime.getURL('/');
headers['X-Title'] = 'OpenAgent Chrome Extension';
}
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify({
model: model || 'openai/gpt-4o',
messages: [{ role: 'user', content: prompt }],
max_tokens: 300,
}),
});
if (!response.ok) return null;
const data = await response.json();
const content = data.choices?.[0]?.message?.content || '';
// Try to parse JSON from response
try {
const jsonMatch = content.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
return {
summary: parsed.summary || '',
topics: parsed.topics || [],
keyFacts: parsed.key_facts || [],
};
}
} catch {
// Fallback: treat content as summary
return { summary: content, topics: [], keyFacts: [] };
}
} catch {
return null;
}
}
// ─── Memory Bank Assembly ─────────────────────────────────────────────────────
function buildMemoryContext(summaries, memories) {
const parts = [];
if (summaries.length > 0) {
parts.push('## Previous Conversations\n');
summaries.forEach((s) => {
parts.push(`- [${new Date(s.timestamp).toLocaleDateString()}] ${s.summary}`);
});
}
if (memories.length > 0) {
parts.push('\n## Key Facts Remembered\n');
memories.forEach((m) => {
parts.push(`- ${m.fact}`);
});
}
return parts.join('\n');
}
// ─── Post-Conversation Processing ─────────────────────────────────────────────
async function processConversationEnd(messages, pageUrl, domain, apiKey, model, baseUrl) {
if (messages.length < 2) return null;
// Generate AI summary
const summaryData = await generateConversationSummary(messages, pageUrl, apiKey, model, baseUrl);
// Extract basic facts even without AI summary
const basicFacts = extractFactsFromMessages(messages);
const topics = summaryData?.topics || extractTopicsFromMessages(messages);
// Build memory entries
const memEntries = [];
if (summaryData?.keyFacts) {
for (const fact of summaryData.keyFacts) {
memEntries.push({
domain,
fact,
topics,
timestamp: Date.now(),
source: 'summary',
});
}
}
for (const fact of basicFacts) {
memEntries.push({
domain,
fact: fact.fact,
topics: fact.topics,
timestamp: Date.now(),
source: fact.type,
});
}
return {
summary: summaryData?.summary || '',
topics,
memEntries,
};
}