@ai-setting/roy-agent-core 1.5.14-test → 1.5.15-test

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/package.json +1 -1
  2. package/dist/config/index.d.ts +0 -1250
  3. package/dist/config/index.js +0 -32
  4. package/dist/env/agent/index.d.ts +0 -2279
  5. package/dist/env/agent/index.js +0 -24
  6. package/dist/env/commands/index.d.ts +0 -1131
  7. package/dist/env/commands/index.js +0 -14
  8. package/dist/env/debug/formatters/index.d.ts +0 -236
  9. package/dist/env/debug/formatters/index.js +0 -11
  10. package/dist/env/debug/index.d.ts +0 -1652
  11. package/dist/env/debug/index.js +0 -26
  12. package/dist/env/hook/index.d.ts +0 -279
  13. package/dist/env/hook/index.js +0 -29
  14. package/dist/env/index.d.ts +0 -3481
  15. package/dist/env/index.js +0 -82
  16. package/dist/env/llm/index.d.ts +0 -1760
  17. package/dist/env/llm/index.js +0 -40
  18. package/dist/env/log-trace/index.d.ts +0 -1574
  19. package/dist/env/log-trace/index.js +0 -83
  20. package/dist/env/mcp/index.d.ts +0 -1331
  21. package/dist/env/mcp/index.js +0 -39
  22. package/dist/env/mcp/tool/index.d.ts +0 -183
  23. package/dist/env/mcp/tool/index.js +0 -14
  24. package/dist/env/memory/built-in/index.d.ts +0 -232
  25. package/dist/env/memory/built-in/index.js +0 -11
  26. package/dist/env/memory/index.d.ts +0 -1799
  27. package/dist/env/memory/index.js +0 -56
  28. package/dist/env/memory/plugin/index.d.ts +0 -747
  29. package/dist/env/memory/plugin/index.js +0 -36
  30. package/dist/env/prompt/index.d.ts +0 -1164
  31. package/dist/env/prompt/index.js +0 -20
  32. package/dist/env/session/index.d.ts +0 -1908
  33. package/dist/env/session/index.js +0 -25
  34. package/dist/env/session/storage/index.d.ts +0 -564
  35. package/dist/env/session/storage/index.js +0 -18
  36. package/dist/env/skill/index.d.ts +0 -1266
  37. package/dist/env/skill/index.js +0 -34
  38. package/dist/env/skill/tool/index.d.ts +0 -193
  39. package/dist/env/skill/tool/index.js +0 -9
  40. package/dist/env/task/delegate/index.d.ts +0 -1612
  41. package/dist/env/task/delegate/index.js +0 -18
  42. package/dist/env/task/events/index.d.ts +0 -171
  43. package/dist/env/task/events/index.js +0 -7
  44. package/dist/env/task/hooks/index.d.ts +0 -624
  45. package/dist/env/task/hooks/index.js +0 -7
  46. package/dist/env/task/index.d.ts +0 -1553
  47. package/dist/env/task/index.js +0 -34
  48. package/dist/env/task/plugins/index.d.ts +0 -466
  49. package/dist/env/task/plugins/index.js +0 -23
  50. package/dist/env/task/storage/index.d.ts +0 -241
  51. package/dist/env/task/storage/index.js +0 -14
  52. package/dist/env/task/tools/index.d.ts +0 -1485
  53. package/dist/env/task/tools/index.js +0 -17
  54. package/dist/env/task/tools/operation/index.d.ts +0 -1484
  55. package/dist/env/task/tools/operation/index.js +0 -15
  56. package/dist/env/tool/built-in/index.d.ts +0 -218
  57. package/dist/env/tool/built-in/index.js +0 -25
  58. package/dist/env/tool/index.d.ts +0 -1396
  59. package/dist/env/tool/index.js +0 -39
  60. package/dist/env/workflow/decorators/index.d.ts +0 -2161
  61. package/dist/env/workflow/decorators/index.js +0 -27
  62. package/dist/env/workflow/engine/index.d.ts +0 -3453
  63. package/dist/env/workflow/engine/index.js +0 -28
  64. package/dist/env/workflow/index.d.ts +0 -3546
  65. package/dist/env/workflow/index.js +0 -136
  66. package/dist/env/workflow/nodes/index.d.ts +0 -2092
  67. package/dist/env/workflow/nodes/index.js +0 -19
  68. package/dist/env/workflow/service/index.d.ts +0 -227
  69. package/dist/env/workflow/service/index.js +0 -13
  70. package/dist/env/workflow/storage/index.d.ts +0 -165
  71. package/dist/env/workflow/storage/index.js +0 -27
  72. package/dist/env/workflow/tools/index.d.ts +0 -416
  73. package/dist/env/workflow/tools/index.js +0 -159
  74. package/dist/env/workflow/types/index.d.ts +0 -2255
  75. package/dist/env/workflow/types/index.js +0 -98
  76. package/dist/env/workflow/utils/index.d.ts +0 -2031
  77. package/dist/env/workflow/utils/index.js +0 -637
  78. package/dist/index.d.ts +0 -7858
  79. package/dist/index.js +0 -399
  80. package/dist/shared/@ai-setting/roy-agent-core-0rtxwr28.js +0 -258
  81. package/dist/shared/@ai-setting/roy-agent-core-0vbdz0x7.js +0 -36
  82. package/dist/shared/@ai-setting/roy-agent-core-1akcqxj9.js +0 -349
  83. package/dist/shared/@ai-setting/roy-agent-core-1ce3fqrk.js +0 -117
  84. package/dist/shared/@ai-setting/roy-agent-core-2dhd60aw.js +0 -11
  85. package/dist/shared/@ai-setting/roy-agent-core-3jywqmdd.js +0 -393
  86. package/dist/shared/@ai-setting/roy-agent-core-3rr5k71j.js +0 -200
  87. package/dist/shared/@ai-setting/roy-agent-core-44hnfb02.js +0 -299
  88. package/dist/shared/@ai-setting/roy-agent-core-4t40mkpv.js +0 -206
  89. package/dist/shared/@ai-setting/roy-agent-core-4txzpsbt.js +0 -393
  90. package/dist/shared/@ai-setting/roy-agent-core-5x94xmt6.js +0 -350
  91. package/dist/shared/@ai-setting/roy-agent-core-69jskqjg.js +0 -180
  92. package/dist/shared/@ai-setting/roy-agent-core-6kvtahqv.js +0 -408
  93. package/dist/shared/@ai-setting/roy-agent-core-7fgf85wc.js +0 -284
  94. package/dist/shared/@ai-setting/roy-agent-core-81w1963m.js +0 -762
  95. package/dist/shared/@ai-setting/roy-agent-core-8gxth0eh.js +0 -10
  96. package/dist/shared/@ai-setting/roy-agent-core-92z6t4he.js +0 -14
  97. package/dist/shared/@ai-setting/roy-agent-core-93zfb3r1.js +0 -922
  98. package/dist/shared/@ai-setting/roy-agent-core-9yxb3ty9.js +0 -15
  99. package/dist/shared/@ai-setting/roy-agent-core-b0x5dda6.js +0 -1130
  100. package/dist/shared/@ai-setting/roy-agent-core-bcbqy27c.js +0 -14
  101. package/dist/shared/@ai-setting/roy-agent-core-bvr1761x.js +0 -653
  102. package/dist/shared/@ai-setting/roy-agent-core-ctdhjv68.js +0 -93
  103. package/dist/shared/@ai-setting/roy-agent-core-d7cyjkf7.js +0 -872
  104. package/dist/shared/@ai-setting/roy-agent-core-dh9d7a3m.js +0 -11
  105. package/dist/shared/@ai-setting/roy-agent-core-e25xkv53.js +0 -64
  106. package/dist/shared/@ai-setting/roy-agent-core-eajcvp4e.js +0 -378
  107. package/dist/shared/@ai-setting/roy-agent-core-f7q2x5z6.js +0 -492
  108. package/dist/shared/@ai-setting/roy-agent-core-fs0mn2jk.js +0 -52
  109. package/dist/shared/@ai-setting/roy-agent-core-g1s2h0e5.js +0 -171
  110. package/dist/shared/@ai-setting/roy-agent-core-g99pxzn5.js +0 -862
  111. package/dist/shared/@ai-setting/roy-agent-core-gbqcyegm.js +0 -1387
  112. package/dist/shared/@ai-setting/roy-agent-core-gjq1yk68.js +0 -208
  113. package/dist/shared/@ai-setting/roy-agent-core-gq20wsgv.js +0 -139
  114. package/dist/shared/@ai-setting/roy-agent-core-gwc4h96n.js +0 -534
  115. package/dist/shared/@ai-setting/roy-agent-core-jfh9q2qh.js +0 -204
  116. package/dist/shared/@ai-setting/roy-agent-core-jvatggbb.js +0 -603
  117. package/dist/shared/@ai-setting/roy-agent-core-kkbwepqb.js +0 -97
  118. package/dist/shared/@ai-setting/roy-agent-core-pjr12nnd.js +0 -587
  119. package/dist/shared/@ai-setting/roy-agent-core-psv4v63c.js +0 -176
  120. package/dist/shared/@ai-setting/roy-agent-core-psvxt4c9.js +0 -60
  121. package/dist/shared/@ai-setting/roy-agent-core-qqceba6k.js +0 -442
  122. package/dist/shared/@ai-setting/roy-agent-core-qxhq8ven.js +0 -57
  123. package/dist/shared/@ai-setting/roy-agent-core-qxnbvgwe.js +0 -66
  124. package/dist/shared/@ai-setting/roy-agent-core-r9ezzemr.js +0 -10
  125. package/dist/shared/@ai-setting/roy-agent-core-rhmtwnw1.js +0 -267
  126. package/dist/shared/@ai-setting/roy-agent-core-rvv6ydff.js +0 -584
  127. package/dist/shared/@ai-setting/roy-agent-core-rvxg1wps.js +0 -102
  128. package/dist/shared/@ai-setting/roy-agent-core-satmq6sh.js +0 -549
  129. package/dist/shared/@ai-setting/roy-agent-core-sx7wsvnn.js +0 -15
  130. package/dist/shared/@ai-setting/roy-agent-core-t94ktchq.js +0 -213
  131. package/dist/shared/@ai-setting/roy-agent-core-vf215qfv.js +0 -812
  132. package/dist/shared/@ai-setting/roy-agent-core-vkz81f7v.js +0 -1316
  133. package/dist/shared/@ai-setting/roy-agent-core-vn2bc59q.js +0 -1205
  134. package/dist/shared/@ai-setting/roy-agent-core-wa1kzqky.js +0 -328
  135. package/dist/shared/@ai-setting/roy-agent-core-wft9ra24.js +0 -20
  136. package/dist/shared/@ai-setting/roy-agent-core-wrcy0h6z.js +0 -2098
  137. package/dist/shared/@ai-setting/roy-agent-core-xq8hhqb8.js +0 -419
  138. package/dist/shared/@ai-setting/roy-agent-core-xs5rsgat.js +0 -368
  139. package/dist/shared/@ai-setting/roy-agent-core-zbkpc41z.js +0 -377
  140. package/dist/shared/@ai-setting/roy-agent-core-zgypchmt.js +0 -172
  141. package/dist/shared/@ai-setting/roy-agent-core-zpn0bqa8.js +0 -103
@@ -1,872 +0,0 @@
1
- import {
2
- SessionMessageConverter
3
- } from "./roy-agent-core-jfh9q2qh.js";
4
- import {
5
- __require
6
- } from "./roy-agent-core-fs0mn2jk.js";
7
-
8
- // src/env/session/storage/memory.ts
9
- import { randomUUID } from "crypto";
10
- function generateSessionId() {
11
- return `session_${randomUUID()}`;
12
- }
13
- function generateMessageId() {
14
- return `msg_${randomUUID()}`;
15
- }
16
-
17
- class MemorySessionStore {
18
- sessions = new Map;
19
- messages = new Map;
20
- checkpoints = new Map;
21
- messageConverter = new SessionMessageConverter;
22
- async create(options) {
23
- const now = Date.now();
24
- const session = {
25
- id: options.id ?? generateSessionId(),
26
- title: options.title ?? "Session",
27
- directory: options.directory ?? "/tmp",
28
- parentID: options.parentID,
29
- createdAt: now,
30
- updatedAt: now,
31
- messageCount: 0,
32
- metadata: {
33
- ...options.metadata,
34
- messageCount: 0,
35
- checkpoints: { checkpoints: [] }
36
- }
37
- };
38
- if (this.sessions.has(session.id)) {
39
- throw new Error(`Session with ID '${session.id}' already exists`);
40
- }
41
- this.sessions.set(session.id, session);
42
- this.messages.set(session.id, []);
43
- this.checkpoints.set(session.id, []);
44
- return session;
45
- }
46
- async get(id) {
47
- return this.sessions.get(id);
48
- }
49
- async list(options) {
50
- let sessions = Array.from(this.sessions.values());
51
- if (options?.filter?.metadata) {
52
- sessions = sessions.filter((s) => {
53
- for (const [key, value] of Object.entries(options.filter.metadata)) {
54
- if (s.metadata?.[key] !== value)
55
- return false;
56
- }
57
- return true;
58
- });
59
- }
60
- if (options?.filter?.startTime) {
61
- sessions = sessions.filter((s) => s.createdAt >= options.filter.startTime);
62
- }
63
- if (options?.filter?.endTime) {
64
- sessions = sessions.filter((s) => s.createdAt <= options.filter.endTime);
65
- }
66
- const sortField = options?.sort?.field ?? "updatedAt";
67
- const sortOrder = options?.sort?.order ?? "desc";
68
- sessions.sort((a, b) => {
69
- let aVal;
70
- let bVal;
71
- if (sortField === "title") {
72
- aVal = a.title;
73
- bVal = b.title;
74
- } else if (sortField === "createdAt") {
75
- aVal = a.createdAt;
76
- bVal = b.createdAt;
77
- } else {
78
- aVal = a.updatedAt;
79
- bVal = b.updatedAt;
80
- }
81
- if (aVal < bVal)
82
- return sortOrder === "asc" ? -1 : 1;
83
- if (aVal > bVal)
84
- return sortOrder === "asc" ? 1 : -1;
85
- return 0;
86
- });
87
- const offset = options?.offset ?? 0;
88
- const limit = options?.limit ?? 100;
89
- return sessions.slice(offset, offset + limit);
90
- }
91
- async update(id, updates) {
92
- const session = this.sessions.get(id);
93
- if (!session)
94
- return false;
95
- if (updates.title !== undefined) {
96
- session.title = updates.title;
97
- }
98
- if (updates.metadata !== undefined) {
99
- session.metadata = { ...session.metadata, ...updates.metadata };
100
- }
101
- session.updatedAt = Date.now();
102
- return true;
103
- }
104
- async delete(id) {
105
- const deleted = this.sessions.delete(id);
106
- if (deleted) {
107
- this.messages.delete(id);
108
- this.checkpoints.delete(id);
109
- }
110
- return deleted;
111
- }
112
- async getCount() {
113
- return this.sessions.size;
114
- }
115
- async addMessage(sessionId, message) {
116
- const session = this.sessions.get(sessionId);
117
- if (!session) {
118
- throw new Error(`Session not found: ${sessionId}`);
119
- }
120
- const rawMessage = {
121
- sessionID: sessionId,
122
- role: message.role,
123
- content: message.content,
124
- parts: message.parts,
125
- metadata: message.metadata
126
- };
127
- const msg = this.messageConverter.migrateMessage(rawMessage);
128
- msg.id = generateMessageId();
129
- msg.timestamp = Date.now();
130
- const sessionMessages = this.messages.get(sessionId) ?? [];
131
- sessionMessages.push(msg);
132
- this.messages.set(sessionId, sessionMessages);
133
- session.messageCount = sessionMessages.filter((m) => !m.isArchived).length;
134
- session.metadata = {
135
- ...session.metadata,
136
- messageCount: session.messageCount
137
- };
138
- session.updatedAt = Date.now();
139
- return msg.id;
140
- }
141
- async getMessages(sessionId, offset = 0, limit = 50, options) {
142
- let messages = this.messages.get(sessionId) ?? [];
143
- if (!options?.includeArchived) {
144
- messages = messages.filter((m) => !m.isArchived);
145
- }
146
- if (options?.fromCheckpointId) {
147
- const checkpoint = await this.getCheckpoint(sessionId, options.fromCheckpointId);
148
- if (checkpoint) {
149
- const checkpointIndex = messages.findIndex((m) => m.metadata?.checkpointId === options.fromCheckpointId);
150
- if (checkpointIndex >= 0) {
151
- messages = messages.slice(checkpointIndex);
152
- }
153
- }
154
- }
155
- let actualOffset = offset;
156
- if (offset < 0) {
157
- const total = messages.length;
158
- actualOffset = Math.max(0, total + offset * limit);
159
- }
160
- if (options?.reverse) {
161
- messages = messages.reverse();
162
- }
163
- return messages.slice(actualOffset, actualOffset + limit);
164
- }
165
- async getMessageCount(sessionId, includeArchived = false) {
166
- const messages = this.messages.get(sessionId) ?? [];
167
- if (includeArchived) {
168
- return messages.length;
169
- }
170
- return messages.filter((m) => !m.isArchived).length;
171
- }
172
- async getMessageIndexes(sessionId, role) {
173
- const messages = this.messages.get(sessionId) ?? [];
174
- const indexes = [];
175
- messages.filter((m) => !m.isArchived).forEach((msg, filteredIdx) => {
176
- if (msg.role === role) {
177
- indexes.push(filteredIdx);
178
- }
179
- });
180
- return indexes;
181
- }
182
- async saveCheckpoint(sessionId, checkpoint) {
183
- const session = this.sessions.get(sessionId);
184
- if (!session) {
185
- throw new Error(`Session not found: ${sessionId}`);
186
- }
187
- const cps = this.checkpoints.get(sessionId) ?? [];
188
- cps.push(checkpoint);
189
- this.checkpoints.set(sessionId, cps);
190
- const meta = session.metadata || {};
191
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
192
- checkpointsMeta.checkpoints.push({
193
- id: checkpoint.id,
194
- messageIndex: checkpoint.messageIndex,
195
- title: checkpoint.title,
196
- createdAt: checkpoint.createdAt,
197
- type: checkpoint.type
198
- });
199
- checkpointsMeta.latestCheckpointId = checkpoint.id;
200
- meta.checkpoints = checkpointsMeta;
201
- if (!meta.checkpointDetails) {
202
- meta.checkpointDetails = {};
203
- }
204
- meta.checkpointDetails[checkpoint.id] = checkpoint;
205
- session.metadata = meta;
206
- session.updatedAt = Date.now();
207
- }
208
- async getCheckpoints(sessionId) {
209
- return this.checkpoints.get(sessionId) ?? [];
210
- }
211
- async getCheckpoint(sessionId, checkpointId) {
212
- const cps = this.checkpoints.get(sessionId) ?? [];
213
- return cps.find((cp) => cp.id === checkpointId);
214
- }
215
- async deleteCheckpoint(sessionId, checkpointId) {
216
- const session = this.sessions.get(sessionId);
217
- if (!session)
218
- return false;
219
- const cps = this.checkpoints.get(sessionId) ?? [];
220
- const index = cps.findIndex((cp) => cp.id === checkpointId);
221
- if (index === -1)
222
- return false;
223
- cps.splice(index, 1);
224
- this.checkpoints.set(sessionId, cps);
225
- const messages = this.messages.get(sessionId) ?? [];
226
- for (const msg of messages) {
227
- if (msg.checkpointId === checkpointId) {
228
- msg.isArchived = false;
229
- msg.archivedAt = undefined;
230
- msg.checkpointId = undefined;
231
- }
232
- }
233
- const meta = session.metadata || {};
234
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
235
- checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
236
- checkpointsMeta.latestCheckpointId = cps[cps.length - 1]?.id;
237
- if (meta.checkpointDetails) {
238
- delete meta.checkpointDetails[checkpointId];
239
- }
240
- session.metadata = meta;
241
- session.messageCount = messages.filter((m) => !m.isArchived).length;
242
- session.updatedAt = Date.now();
243
- return true;
244
- }
245
- async archiveMessages(sessionId, checkpointId, beforeIndex) {
246
- const session = this.sessions.get(sessionId);
247
- if (!session)
248
- return 0;
249
- const messages = this.messages.get(sessionId) ?? [];
250
- let archivedCount = 0;
251
- for (let i = 0;i < beforeIndex; i++) {
252
- if (!messages[i].isArchived) {
253
- messages[i].isArchived = true;
254
- messages[i].archivedAt = Date.now();
255
- messages[i].checkpointId = checkpointId;
256
- archivedCount++;
257
- }
258
- }
259
- session.messageCount = messages.filter((m) => !m.isArchived).length;
260
- session.updatedAt = Date.now();
261
- return archivedCount;
262
- }
263
- async getActiveMessages(sessionId, offset = 0, limit = 50) {
264
- const messages = this.messages.get(sessionId) ?? [];
265
- const activeMessages = messages.filter((m) => !m.isArchived);
266
- return activeMessages.slice(offset, offset + limit);
267
- }
268
- async searchMessages(options) {
269
- const matches = [];
270
- const {
271
- query,
272
- sessionId,
273
- limit = 10,
274
- beforeTime,
275
- afterTime,
276
- includeArchived = false
277
- } = options;
278
- let sessionsToSearch;
279
- if (sessionId) {
280
- const session = await this.get(sessionId);
281
- sessionsToSearch = session ? [session] : [];
282
- } else {
283
- sessionsToSearch = Array.from(this.sessions.values());
284
- }
285
- const queryTerms = this.parseQuery(query);
286
- for (const session of sessionsToSearch) {
287
- if (beforeTime && session.updatedAt > beforeTime)
288
- continue;
289
- if (afterTime && session.updatedAt < afterTime)
290
- continue;
291
- let messages = this.messages.get(session.id) ?? [];
292
- if (!includeArchived) {
293
- messages = messages.filter((m) => !m.isArchived);
294
- }
295
- for (const msg of messages) {
296
- if (beforeTime && msg.timestamp > beforeTime)
297
- continue;
298
- if (afterTime && msg.timestamp < afterTime)
299
- continue;
300
- const content = msg.content.toLowerCase();
301
- let matchesQuery = true;
302
- for (const term of queryTerms.required) {
303
- if (!content.includes(term.toLowerCase())) {
304
- matchesQuery = false;
305
- break;
306
- }
307
- }
308
- for (const term of queryTerms.excluded) {
309
- if (content.includes(term.toLowerCase())) {
310
- matchesQuery = false;
311
- break;
312
- }
313
- }
314
- if (matchesQuery) {
315
- matches.push({
316
- messageId: msg.id,
317
- sessionId: session.id,
318
- role: msg.role,
319
- content: msg.content,
320
- timestamp: msg.timestamp
321
- });
322
- if (matches.length >= limit) {
323
- return matches;
324
- }
325
- }
326
- }
327
- }
328
- return matches;
329
- }
330
- parseQuery(query) {
331
- const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
332
- const required = [];
333
- const excluded = [];
334
- for (const term of terms) {
335
- if (term.startsWith("-") || term.startsWith("NOT ")) {
336
- excluded.push(term.replace(/^-|^NOT /i, ""));
337
- } else {
338
- required.push(term);
339
- }
340
- }
341
- return { required, excluded };
342
- }
343
- async close() {
344
- this.sessions.clear();
345
- this.messages.clear();
346
- this.checkpoints.clear();
347
- }
348
- }
349
- // src/env/session/storage/sqlite.ts
350
- import { join } from "path";
351
- import { randomUUID as randomUUID2 } from "crypto";
352
- function getDatabaseClass() {
353
- if (typeof Bun !== "undefined") {
354
- const { Database } = __require("bun:sqlite");
355
- return Database;
356
- } else {
357
- return __require("better-sqlite3");
358
- }
359
- }
360
- function createCompatibleDatabase(path) {
361
- const Database = getDatabaseClass();
362
- const db = new Database(path);
363
- if (typeof db.run !== "function") {
364
- db.run = function(sql, ...params) {
365
- if (params.length > 0) {
366
- return this.prepare(sql).run(...params);
367
- } else {
368
- return this.exec(sql);
369
- }
370
- };
371
- }
372
- return db;
373
- }
374
- function generateSessionId2() {
375
- return `session_${randomUUID2()}`;
376
- }
377
- function generateMessageId2() {
378
- return `msg_${randomUUID2()}`;
379
- }
380
- function getDefaultDataDir() {
381
- const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
382
- return join(home, ".local", "share");
383
- }
384
- function getDefaultSessionDbPath() {
385
- return join(getDefaultDataDir(), "roy-agent", "sessions.db");
386
- }
387
-
388
- class SQLiteSessionStore {
389
- db = null;
390
- dbPath;
391
- initialized = false;
392
- sessionsCache = new Map;
393
- messagesCache = new Map;
394
- checkpointsCache = new Map;
395
- messageConverter = new SessionMessageConverter;
396
- constructor(dbPath) {
397
- this.dbPath = dbPath || getDefaultSessionDbPath();
398
- }
399
- async initialize() {
400
- if (this.initialized)
401
- return;
402
- if (this.dbPath !== ":memory:") {
403
- const fs = __require("fs");
404
- const path = __require("path");
405
- const dir = path.dirname(this.dbPath);
406
- if (!fs.existsSync(dir)) {
407
- fs.mkdirSync(dir, { recursive: true });
408
- }
409
- }
410
- this.db = createCompatibleDatabase(this.dbPath);
411
- this.db.run(`
412
- CREATE TABLE IF NOT EXISTS session (
413
- id TEXT PRIMARY KEY,
414
- title TEXT NOT NULL,
415
- directory TEXT NOT NULL,
416
- parent_id TEXT,
417
- created_at INTEGER NOT NULL,
418
- updated_at INTEGER NOT NULL,
419
- message_count INTEGER DEFAULT 0,
420
- metadata TEXT
421
- )
422
- `);
423
- this.db.run(`
424
- CREATE TABLE IF NOT EXISTS message (
425
- id TEXT PRIMARY KEY,
426
- session_id TEXT NOT NULL,
427
- role TEXT NOT NULL,
428
- content TEXT NOT NULL,
429
- timestamp INTEGER NOT NULL,
430
- parts TEXT,
431
- is_archived INTEGER DEFAULT 0,
432
- archived_at INTEGER,
433
- checkpoint_id TEXT,
434
- metadata TEXT,
435
- FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE
436
- )
437
- `);
438
- this.db.run("CREATE INDEX IF NOT EXISTS idx_message_session ON message(session_id)");
439
- this.db.run("CREATE INDEX IF NOT EXISTS idx_message_checkpoint ON message(checkpoint_id)");
440
- this.initialized = true;
441
- }
442
- async create(options) {
443
- await this.initialize();
444
- const now = Date.now();
445
- const session = {
446
- id: options.id ?? generateSessionId2(),
447
- title: options.title ?? "Session",
448
- directory: options.directory ?? "/tmp",
449
- parentID: options.parentID,
450
- createdAt: now,
451
- updatedAt: now,
452
- messageCount: 0,
453
- metadata: {
454
- ...options.metadata,
455
- messageCount: 0,
456
- checkpoints: { checkpoints: [] }
457
- }
458
- };
459
- const existing = this.db.prepare("SELECT id FROM session WHERE id = ?").get(session.id);
460
- if (existing) {
461
- throw new Error(`Session with ID '${session.id}' already exists`);
462
- }
463
- const stmt = this.db.prepare(`
464
- INSERT INTO session (id, title, directory, parent_id, created_at, updated_at, message_count, metadata)
465
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
466
- `);
467
- stmt.run(session.id, session.title, session.directory, session.parentID || null, session.createdAt, session.updatedAt, session.messageCount, JSON.stringify(session.metadata));
468
- this.sessionsCache.set(session.id, session);
469
- this.messagesCache.set(session.id, []);
470
- this.checkpointsCache.set(session.id, []);
471
- return session;
472
- }
473
- async get(id) {
474
- await this.initialize();
475
- const cached = this.sessionsCache.get(id);
476
- if (cached)
477
- return cached;
478
- const row = this.db.prepare("SELECT * FROM session WHERE id = ?").get(id);
479
- if (!row)
480
- return;
481
- const session = this.rowToSession(row);
482
- this.sessionsCache.set(session.id, session);
483
- return session;
484
- }
485
- async list(options) {
486
- await this.initialize();
487
- let sql = "SELECT * FROM session";
488
- const params = [];
489
- const conditions = [];
490
- if (options?.filter?.metadata) {
491
- for (const [key, value] of Object.entries(options.filter.metadata)) {
492
- conditions.push(`json_extract(metadata, '$.${key}') = ?`);
493
- params.push(JSON.stringify(value));
494
- }
495
- }
496
- if (options?.filter?.startTime) {
497
- conditions.push("created_at >= ?");
498
- params.push(options.filter.startTime);
499
- }
500
- if (options?.filter?.endTime) {
501
- conditions.push("created_at <= ?");
502
- params.push(options.filter.endTime);
503
- }
504
- if (conditions.length > 0) {
505
- sql += " WHERE " + conditions.join(" AND ");
506
- }
507
- const sortField = options?.sort?.field ?? "updatedAt";
508
- const sortOrder = options?.sort?.order ?? "desc";
509
- const orderColumn = sortField === "title" ? "title" : sortField === "createdAt" ? "created_at" : "updated_at";
510
- sql += ` ORDER BY ${orderColumn} ${sortOrder.toUpperCase()}`;
511
- const offset = options?.offset ?? 0;
512
- const limit = options?.limit ?? 100;
513
- sql += " LIMIT ? OFFSET ?";
514
- params.push(limit, offset);
515
- const rows = this.db.prepare(sql).all(...params);
516
- return rows.map((row) => this.rowToSession(row));
517
- }
518
- async getCount() {
519
- await this.initialize();
520
- const result = this.db.prepare("SELECT COUNT(*) as count FROM session").get();
521
- return result.count;
522
- }
523
- async update(id, updates) {
524
- await this.initialize();
525
- const session = await this.get(id);
526
- if (!session)
527
- return false;
528
- if (updates.title !== undefined) {
529
- session.title = updates.title;
530
- }
531
- if (updates.metadata !== undefined) {
532
- session.metadata = { ...session.metadata, ...updates.metadata };
533
- }
534
- session.updatedAt = Date.now();
535
- const stmt = this.db.prepare(`
536
- UPDATE session
537
- SET title = ?, metadata = ?, updated_at = ?
538
- WHERE id = ?
539
- `);
540
- stmt.run(session.title, JSON.stringify(session.metadata), session.updatedAt, id);
541
- this.sessionsCache.set(id, session);
542
- return true;
543
- }
544
- async delete(id) {
545
- await this.initialize();
546
- const session = await this.get(id);
547
- if (!session)
548
- return false;
549
- this.db.prepare("DELETE FROM session WHERE id = ?").run(id);
550
- this.sessionsCache.delete(id);
551
- this.messagesCache.delete(id);
552
- this.checkpointsCache.delete(id);
553
- return true;
554
- }
555
- async addMessage(sessionId, message) {
556
- await this.initialize();
557
- const session = await this.get(sessionId);
558
- if (!session) {
559
- throw new Error(`Session not found: ${sessionId}`);
560
- }
561
- const now = Date.now();
562
- const msg = {
563
- id: generateMessageId2(),
564
- sessionID: sessionId,
565
- role: message.role,
566
- content: message.content,
567
- timestamp: now,
568
- parts: message.parts,
569
- metadata: message.metadata
570
- };
571
- const stmt = this.db.prepare(`
572
- INSERT INTO message (id, session_id, role, content, timestamp, parts, metadata)
573
- VALUES (?, ?, ?, ?, ?, ?, ?)
574
- `);
575
- stmt.run(msg.id, msg.sessionID, msg.role, msg.content, msg.timestamp, msg.parts ? JSON.stringify(msg.parts) : null, msg.metadata ? JSON.stringify(msg.metadata) : null);
576
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
577
- session.messageCount = countResult?.count || 0;
578
- session.updatedAt = now;
579
- session.metadata = {
580
- ...session.metadata,
581
- messageCount: session.messageCount
582
- };
583
- this.db.prepare(`
584
- UPDATE session SET message_count = ?, metadata = ?, updated_at = ? WHERE id = ?
585
- `).run(session.messageCount, JSON.stringify(session.metadata), session.updatedAt, sessionId);
586
- const messages = this.messagesCache.get(sessionId) ?? [];
587
- messages.push(msg);
588
- this.messagesCache.set(sessionId, messages);
589
- this.sessionsCache.set(sessionId, session);
590
- return msg.id;
591
- }
592
- async getMessages(sessionId, offset = 0, limit = 50, options) {
593
- await this.initialize();
594
- let sql = "SELECT * FROM message WHERE session_id = ?";
595
- let countSql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
596
- const params = [sessionId];
597
- const countParams = [sessionId];
598
- if (!options?.includeArchived) {
599
- sql += " AND is_archived = 0";
600
- countSql += " AND is_archived = 0";
601
- }
602
- if (options?.fromCheckpointId) {
603
- sql += " AND timestamp >= (SELECT MIN(timestamp) FROM message WHERE session_id = ? AND json_extract(metadata, '$.checkpointId') = ?)";
604
- params.push(sessionId, options.fromCheckpointId);
605
- }
606
- let actualOffset = offset;
607
- if (offset < 0) {
608
- const totalResult = this.db.prepare(countSql).get(...countParams);
609
- const total = totalResult?.count || 0;
610
- actualOffset = Math.max(0, total + offset * limit);
611
- }
612
- if (options?.reverse) {
613
- sql += " ORDER BY timestamp DESC";
614
- } else {
615
- sql += " ORDER BY timestamp ASC";
616
- }
617
- sql += " LIMIT ? OFFSET ?";
618
- params.push(limit, actualOffset);
619
- const rows = this.db.prepare(sql).all(...params);
620
- return rows.map((row) => this.rowToMessage(row));
621
- }
622
- async getMessageCount(sessionId, includeArchived = false) {
623
- await this.initialize();
624
- let sql = "SELECT COUNT(*) as count FROM message WHERE session_id = ?";
625
- if (!includeArchived) {
626
- sql += " AND is_archived = 0";
627
- }
628
- const result = this.db.prepare(sql).get(sessionId);
629
- return result?.count || 0;
630
- }
631
- async getMessageIndexes(sessionId, role) {
632
- await this.initialize();
633
- const sql = `
634
- SELECT idx FROM (
635
- SELECT
636
- ROW_NUMBER() OVER (ORDER BY timestamp ASC) - 1 as idx,
637
- role
638
- FROM message
639
- WHERE session_id = ? AND is_archived = 0
640
- ) ranked
641
- WHERE role = ?
642
- `;
643
- const rows = this.db.prepare(sql).all(sessionId, role);
644
- return rows.map((row) => row.idx);
645
- }
646
- async saveCheckpoint(sessionId, checkpoint) {
647
- await this.initialize();
648
- const session = await this.get(sessionId);
649
- if (!session) {
650
- throw new Error(`Session not found: ${sessionId}`);
651
- }
652
- const cps = this.checkpointsCache.get(sessionId) ?? [];
653
- cps.push(checkpoint);
654
- this.checkpointsCache.set(sessionId, cps);
655
- const meta = session.metadata || {};
656
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
657
- checkpointsMeta.checkpoints.push({
658
- id: checkpoint.id,
659
- messageIndex: checkpoint.messageIndex,
660
- title: checkpoint.title,
661
- createdAt: checkpoint.createdAt,
662
- type: checkpoint.type
663
- });
664
- checkpointsMeta.latestCheckpointId = checkpoint.id;
665
- meta.checkpoints = checkpointsMeta;
666
- if (!meta.checkpointDetails) {
667
- meta.checkpointDetails = {};
668
- }
669
- meta.checkpointDetails[checkpoint.id] = checkpoint;
670
- session.metadata = meta;
671
- session.updatedAt = Date.now();
672
- const stmt = this.db.prepare(`
673
- UPDATE session SET metadata = ?, updated_at = ? WHERE id = ?
674
- `);
675
- stmt.run(JSON.stringify(session.metadata), session.updatedAt, sessionId);
676
- this.sessionsCache.set(sessionId, session);
677
- }
678
- async getCheckpoints(sessionId) {
679
- await this.initialize();
680
- const session = await this.get(sessionId);
681
- if (!session)
682
- return [];
683
- const meta = session.metadata;
684
- const checkpointDetails = meta?.checkpointDetails;
685
- if (!checkpointDetails)
686
- return [];
687
- return Object.values(checkpointDetails);
688
- }
689
- async getCheckpoint(sessionId, checkpointId) {
690
- await this.initialize();
691
- const checkpoints = await this.getCheckpoints(sessionId);
692
- return checkpoints.find((cp) => cp.id === checkpointId);
693
- }
694
- async deleteCheckpoint(sessionId, checkpointId) {
695
- await this.initialize();
696
- const session = await this.get(sessionId);
697
- if (!session)
698
- return false;
699
- const checkpoints = this.checkpointsCache.get(sessionId) ?? [];
700
- const index = checkpoints.findIndex((cp) => cp.id === checkpointId);
701
- if (index === -1)
702
- return false;
703
- checkpoints.splice(index, 1);
704
- this.checkpointsCache.set(sessionId, checkpoints);
705
- this.db.prepare(`
706
- UPDATE message SET is_archived = 0, archived_at = NULL, checkpoint_id = NULL
707
- WHERE session_id = ? AND checkpoint_id = ?
708
- `).run(sessionId, checkpointId);
709
- const meta = session.metadata || {};
710
- const checkpointsMeta = meta.checkpoints || { checkpoints: [] };
711
- checkpointsMeta.checkpoints = checkpointsMeta.checkpoints.filter((cp) => cp.id !== checkpointId);
712
- checkpointsMeta.latestCheckpointId = checkpoints[checkpoints.length - 1]?.id;
713
- if (meta.checkpointDetails) {
714
- delete meta.checkpointDetails[checkpointId];
715
- }
716
- session.metadata = meta;
717
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
718
- session.messageCount = countResult?.count || 0;
719
- session.updatedAt = Date.now();
720
- this.db.prepare(`
721
- UPDATE session SET metadata = ?, message_count = ?, updated_at = ? WHERE id = ?
722
- `).run(JSON.stringify(session.metadata), session.messageCount, session.updatedAt, sessionId);
723
- this.sessionsCache.set(sessionId, session);
724
- return true;
725
- }
726
- async archiveMessages(sessionId, checkpointId, beforeIndex) {
727
- await this.initialize();
728
- const session = await this.get(sessionId);
729
- if (!session)
730
- return 0;
731
- const now = Date.now();
732
- const result = this.db.prepare(`
733
- UPDATE message
734
- SET is_archived = 1, archived_at = ?, checkpoint_id = ?
735
- WHERE session_id = ? AND id IN (
736
- SELECT id FROM message WHERE session_id = ? AND is_archived = 0
737
- ORDER BY timestamp ASC LIMIT ?
738
- )
739
- `).run(now, checkpointId, sessionId, sessionId, beforeIndex);
740
- const countResult = this.db.prepare("SELECT COUNT(*) as count FROM message WHERE session_id = ? AND is_archived = 0").get(sessionId);
741
- session.messageCount = countResult?.count || 0;
742
- session.updatedAt = now;
743
- this.db.prepare(`
744
- UPDATE session SET message_count = ?, updated_at = ? WHERE id = ?
745
- `).run(session.messageCount, session.updatedAt, sessionId);
746
- this.sessionsCache.set(sessionId, session);
747
- this.messagesCache.delete(sessionId);
748
- return result.changes;
749
- }
750
- async getActiveMessages(sessionId, offset = 0, limit = 50) {
751
- return this.getMessages(sessionId, offset, limit, { includeArchived: false });
752
- }
753
- async searchMessages(options) {
754
- await this.initialize();
755
- const matches = [];
756
- const {
757
- query,
758
- sessionId,
759
- limit = 10,
760
- beforeTime,
761
- afterTime,
762
- includeArchived = false
763
- } = options;
764
- let sql = "SELECT * FROM message WHERE 1=1";
765
- const params = [];
766
- if (sessionId) {
767
- sql += " AND session_id = ?";
768
- params.push(sessionId);
769
- }
770
- if (!includeArchived) {
771
- sql += " AND is_archived = 0";
772
- }
773
- if (beforeTime) {
774
- sql += " AND timestamp <= ?";
775
- params.push(beforeTime);
776
- }
777
- if (afterTime) {
778
- sql += " AND timestamp >= ?";
779
- params.push(afterTime);
780
- }
781
- sql += " ORDER BY timestamp DESC";
782
- sql += " LIMIT ?";
783
- params.push(limit * 10);
784
- const rows = this.db.prepare(sql).all(...params);
785
- const queryTerms = this.parseQuery(query);
786
- const lowerQuery = query.toLowerCase();
787
- for (const row of rows) {
788
- const content = row.content.toLowerCase();
789
- let matchesQuery = true;
790
- for (const term of queryTerms.excluded) {
791
- if (content.includes(term.toLowerCase())) {
792
- matchesQuery = false;
793
- break;
794
- }
795
- }
796
- if (matchesQuery && queryTerms.required.length > 0) {
797
- for (const term of queryTerms.required) {
798
- if (!content.includes(term.toLowerCase())) {
799
- matchesQuery = false;
800
- break;
801
- }
802
- }
803
- }
804
- if (!matchesQuery && lowerQuery && content.includes(lowerQuery)) {
805
- matchesQuery = true;
806
- }
807
- if (matchesQuery) {
808
- matches.push({
809
- messageId: row.id,
810
- sessionId: row.session_id,
811
- role: row.role,
812
- content: row.content,
813
- timestamp: row.timestamp
814
- });
815
- if (matches.length >= limit)
816
- break;
817
- }
818
- }
819
- return matches;
820
- }
821
- parseQuery(query) {
822
- const terms = query.split(/\s+/).filter((t) => !t.startsWith('"') && !t.endsWith('"'));
823
- const required = [];
824
- const excluded = [];
825
- for (const term of terms) {
826
- if (term.startsWith("-") || term.toUpperCase().startsWith("NOT ")) {
827
- excluded.push(term.replace(/^-|^NOT /i, ""));
828
- } else {
829
- required.push(term);
830
- }
831
- }
832
- return { required, excluded };
833
- }
834
- async close() {
835
- if (this.db) {
836
- this.db.close();
837
- this.db = null;
838
- }
839
- this.sessionsCache.clear();
840
- this.messagesCache.clear();
841
- this.checkpointsCache.clear();
842
- this.initialized = false;
843
- }
844
- rowToSession(row) {
845
- return {
846
- id: row.id,
847
- title: row.title,
848
- directory: row.directory,
849
- parentID: row.parent_id,
850
- createdAt: row.created_at,
851
- updatedAt: row.updated_at,
852
- messageCount: row.message_count,
853
- metadata: row.metadata ? JSON.parse(row.metadata) : undefined
854
- };
855
- }
856
- rowToMessage(row) {
857
- const rawMessage = {
858
- id: row.id,
859
- sessionID: row.session_id,
860
- role: row.role,
861
- content: row.content,
862
- timestamp: row.timestamp,
863
- parts: row.parts ? JSON.parse(row.parts) : undefined,
864
- isArchived: row.is_archived === 1,
865
- archivedAt: row.archived_at || undefined,
866
- checkpointId: row.checkpoint_id || undefined,
867
- metadata: row.metadata ? JSON.parse(row.metadata) : undefined
868
- };
869
- return this.messageConverter.migrateMessage(rawMessage);
870
- }
871
- }
872
- export { MemorySessionStore, getDefaultDataDir, getDefaultSessionDbPath, SQLiteSessionStore };