Repository navigation
Expand file tree
/
Copy pathagentChatStore.js
More file actions
271 lines (239 loc) · 7.37 KB
/
Copy pathagentChatStore.js
File metadata and controls
271 lines (239 loc) · 7.37 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const fs = require('fs')
const path = require('path')
const { app } = require('electron')
const { randomUUID } = require('crypto')
const { repairPersistedMessages } = require('./agentMessageFormat')
function getAgentDir() {
const dir = path.join(app.getPath('userData'), 'agent')
fs.mkdirSync(dir, { recursive: true })
return dir
}
function getChatsDir() {
const dir = path.join(getAgentDir(), 'chats')
fs.mkdirSync(dir, { recursive: true })
return dir
}
function getChatPath(sessionId) {
return path.join(getChatsDir(), `${sessionId}.json`)
}
function readChat(sessionId) {
const filePath = getChatPath(sessionId)
if (!fs.existsSync(filePath)) return null
try {
const chat = JSON.parse(fs.readFileSync(filePath, 'utf8'))
if (!Array.isArray(chat?.messages)) return chat
const repaired = repairPersistedMessages(chat.messages)
const changed = JSON.stringify(repaired) !== JSON.stringify(chat.messages)
if (changed) {
chat.messages = repaired
writeChat(chat)
}
return chat
} catch {
return null
}
}
function writeChat(chat) {
if (!chat?.id) throw new Error('Chat must have an id')
fs.writeFileSync(getChatPath(chat.id), JSON.stringify(chat, null, 2))
return chat
}
function createChat({ title = 'New chat', capabilities = null, provider = null, model = null } = {}) {
const now = new Date().toISOString()
const chat = {
id: randomUUID(),
title,
titleGenerated: false,
createdAt: now,
updatedAt: now,
capabilities: capabilities || {
knowledgeBase: false,
deskMasterTools: false,
composioIntegrations: false
},
provider: provider || null,
model: model || null,
messages: []
}
return writeChat(chat)
}
function listChats() {
const dir = getChatsDir()
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'))
const chats = files.map((f) => {
try {
const chat = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'))
const messageCount = Array.isArray(chat.messages) ? chat.messages.length : 0
if (messageCount === 0) {
try {
fs.unlinkSync(path.join(dir, f))
} catch {}
return null
}
return {
id: chat.id,
title: chat.title || 'Untitled',
updatedAt: chat.updatedAt,
createdAt: chat.createdAt,
messageCount,
capabilities: chat.capabilities,
provider: chat.provider,
model: chat.model
}
} catch {
return null
}
}).filter(Boolean)
chats.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
return chats
}
function deleteChat(sessionId) {
const filePath = getChatPath(sessionId)
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath)
return true
}
return false
}
function appendMessage(sessionId, message) {
const chat = readChat(sessionId)
if (!chat) throw new Error('Chat session not found')
chat.messages.push(message)
chat.updatedAt = new Date().toISOString()
return writeChat(chat)
}
function updateChatMeta(sessionId, patch) {
const chat = readChat(sessionId)
if (!chat) throw new Error('Chat session not found')
Object.assign(chat, patch, { updatedAt: new Date().toISOString() })
return writeChat(chat)
}
function replaceMessages(sessionId, messages) {
const chat = readChat(sessionId)
if (!chat) throw new Error('Chat session not found')
chat.messages = messages
chat.updatedAt = new Date().toISOString()
return writeChat(chat)
}
function removePendingConfirmations(sessionId, toolCallIds = []) {
const chat = readChat(sessionId)
if (!chat?.messages?.length) return chat
const ids = new Set(toolCallIds.filter(Boolean))
if (!ids.size) return chat
chat.messages = chat.messages.filter((msg) => {
if (!msg?.pendingConfirmation?.toolCallId) return true
return !ids.has(msg.pendingConfirmation.toolCallId)
})
chat.updatedAt = new Date().toISOString()
return writeChat(chat)
}
function findAssistantMessageWithToolCalls(chat, toolCallIds) {
const ids = new Set(toolCallIds.filter(Boolean))
if (!ids.size || !chat?.messages?.length) return null
for (let i = chat.messages.length - 1; i >= 0; i--) {
const msg = chat.messages[i]
if (msg.role !== 'assistant' || !msg.tool_calls?.length) continue
const matching = msg.tool_calls.filter((tc) => ids.has(tc.id))
if (matching.length) {
return { ...msg, tool_calls: matching }
}
}
return null
}
function normalizeSearchQuery(query) {
return String(query || '').trim().toLowerCase()
}
function messageMatchesQuery(message, query) {
if (!query) return false
const content = String(message?.content || '').toLowerCase()
return content.includes(query)
}
function searchChats(query) {
const q = normalizeSearchQuery(query)
if (!q) return listChats()
const dir = getChatsDir()
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'))
const results = []
for (const f of files) {
try {
const chat = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'))
const messages = Array.isArray(chat.messages) ? chat.messages : []
if (messages.length === 0) continue
const title = String(chat.title || '').toLowerCase()
const titleMatch = title.includes(q)
const matchingMessages = messages.filter((m) => messageMatchesQuery(m, q))
if (!titleMatch && matchingMessages.length === 0) continue
let matchSnippet = ''
if (!titleMatch && matchingMessages.length > 0) {
const snippetSource = String(matchingMessages[0].content || '').trim()
const idx = snippetSource.toLowerCase().indexOf(q)
const start = Math.max(0, idx - 24)
const end = Math.min(snippetSource.length, idx + q.length + 48)
matchSnippet = snippetSource.slice(start, end).trim()
}
results.push({
id: chat.id,
title: chat.title || 'Untitled',
updatedAt: chat.updatedAt,
createdAt: chat.createdAt,
messageCount: messages.length,
capabilities: chat.capabilities,
provider: chat.provider,
model: chat.model,
matchSnippet: matchSnippet || null,
matchInTitle: titleMatch
})
} catch {}
}
results.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
return results
}
function exportAllChats() {
const dir = getChatsDir()
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'))
const chats = []
for (const f of files) {
try {
const chat = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'))
if (!chat?.id || !Array.isArray(chat.messages) || chat.messages.length === 0) continue
chats.push(chat)
} catch {}
}
chats.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
return chats
}
function clearAllChats() {
const dir = getChatsDir()
if (!fs.existsSync(dir)) return
for (const f of fs.readdirSync(dir)) {
if (!f.endsWith('.json')) continue
try {
fs.unlinkSync(path.join(dir, f))
} catch {}
}
}
function importChats(chats) {
clearAllChats()
if (!Array.isArray(chats)) return
for (const chat of chats) {
if (!chat?.id || !Array.isArray(chat.messages)) continue
try {
writeChat(chat)
} catch {}
}
}
module.exports = {
createChat,
listChats,
readChat,
deleteChat,
appendMessage,
updateChatMeta,
replaceMessages,
searchChats,
exportAllChats,
clearAllChats,
importChats,
removePendingConfirmations,
findAssistantMessageWithToolCalls
}