@ai-setting/roy-agent-core 1.5.15-test → 1.5.16-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/dist/config/index.d.ts +1250 -0
  2. package/dist/config/index.js +32 -0
  3. package/dist/env/agent/index.d.ts +2279 -0
  4. package/dist/env/agent/index.js +24 -0
  5. package/dist/env/commands/index.d.ts +1131 -0
  6. package/dist/env/commands/index.js +14 -0
  7. package/dist/env/debug/formatters/index.d.ts +236 -0
  8. package/dist/env/debug/formatters/index.js +11 -0
  9. package/dist/env/debug/index.d.ts +1652 -0
  10. package/dist/env/debug/index.js +26 -0
  11. package/dist/env/hook/index.d.ts +279 -0
  12. package/dist/env/hook/index.js +29 -0
  13. package/dist/env/index.d.ts +3481 -0
  14. package/dist/env/index.js +82 -0
  15. package/dist/env/llm/index.d.ts +1760 -0
  16. package/dist/env/llm/index.js +40 -0
  17. package/dist/env/log-trace/index.d.ts +1574 -0
  18. package/dist/env/log-trace/index.js +83 -0
  19. package/dist/env/mcp/index.d.ts +1331 -0
  20. package/dist/env/mcp/index.js +39 -0
  21. package/dist/env/mcp/tool/index.d.ts +183 -0
  22. package/dist/env/mcp/tool/index.js +14 -0
  23. package/dist/env/memory/built-in/index.d.ts +232 -0
  24. package/dist/env/memory/built-in/index.js +11 -0
  25. package/dist/env/memory/index.d.ts +1799 -0
  26. package/dist/env/memory/index.js +56 -0
  27. package/dist/env/memory/plugin/index.d.ts +747 -0
  28. package/dist/env/memory/plugin/index.js +36 -0
  29. package/dist/env/prompt/index.d.ts +1164 -0
  30. package/dist/env/prompt/index.js +20 -0
  31. package/dist/env/session/index.d.ts +1908 -0
  32. package/dist/env/session/index.js +25 -0
  33. package/dist/env/session/storage/index.d.ts +564 -0
  34. package/dist/env/session/storage/index.js +18 -0
  35. package/dist/env/skill/index.d.ts +1266 -0
  36. package/dist/env/skill/index.js +34 -0
  37. package/dist/env/skill/tool/index.d.ts +193 -0
  38. package/dist/env/skill/tool/index.js +9 -0
  39. package/dist/env/task/delegate/index.d.ts +1612 -0
  40. package/dist/env/task/delegate/index.js +18 -0
  41. package/dist/env/task/events/index.d.ts +171 -0
  42. package/dist/env/task/events/index.js +7 -0
  43. package/dist/env/task/hooks/index.d.ts +624 -0
  44. package/dist/env/task/hooks/index.js +7 -0
  45. package/dist/env/task/index.d.ts +1553 -0
  46. package/dist/env/task/index.js +34 -0
  47. package/dist/env/task/plugins/index.d.ts +466 -0
  48. package/dist/env/task/plugins/index.js +23 -0
  49. package/dist/env/task/storage/index.d.ts +241 -0
  50. package/dist/env/task/storage/index.js +14 -0
  51. package/dist/env/task/tools/index.d.ts +1485 -0
  52. package/dist/env/task/tools/index.js +17 -0
  53. package/dist/env/task/tools/operation/index.d.ts +1484 -0
  54. package/dist/env/task/tools/operation/index.js +15 -0
  55. package/dist/env/tool/built-in/index.d.ts +218 -0
  56. package/dist/env/tool/built-in/index.js +25 -0
  57. package/dist/env/tool/index.d.ts +1396 -0
  58. package/dist/env/tool/index.js +39 -0
  59. package/dist/env/workflow/decorators/index.d.ts +2161 -0
  60. package/dist/env/workflow/decorators/index.js +27 -0
  61. package/dist/env/workflow/engine/index.d.ts +3453 -0
  62. package/dist/env/workflow/engine/index.js +28 -0
  63. package/dist/env/workflow/index.d.ts +3546 -0
  64. package/dist/env/workflow/index.js +136 -0
  65. package/dist/env/workflow/nodes/index.d.ts +2092 -0
  66. package/dist/env/workflow/nodes/index.js +19 -0
  67. package/dist/env/workflow/service/index.d.ts +227 -0
  68. package/dist/env/workflow/service/index.js +13 -0
  69. package/dist/env/workflow/storage/index.d.ts +165 -0
  70. package/dist/env/workflow/storage/index.js +27 -0
  71. package/dist/env/workflow/tools/index.d.ts +416 -0
  72. package/dist/env/workflow/tools/index.js +159 -0
  73. package/dist/env/workflow/types/index.d.ts +2255 -0
  74. package/dist/env/workflow/types/index.js +98 -0
  75. package/dist/env/workflow/utils/index.d.ts +2031 -0
  76. package/dist/env/workflow/utils/index.js +637 -0
  77. package/dist/index.d.ts +7858 -0
  78. package/dist/index.js +399 -0
  79. package/dist/shared/@ai-setting/roy-agent-core-0rtxwr28.js +258 -0
  80. package/dist/shared/@ai-setting/roy-agent-core-0vbdz0x7.js +36 -0
  81. package/dist/shared/@ai-setting/roy-agent-core-1akcqxj9.js +349 -0
  82. package/dist/shared/@ai-setting/roy-agent-core-1ce3fqrk.js +117 -0
  83. package/dist/shared/@ai-setting/roy-agent-core-2dhd60aw.js +11 -0
  84. package/dist/shared/@ai-setting/roy-agent-core-3jywqmdd.js +393 -0
  85. package/dist/shared/@ai-setting/roy-agent-core-3rr5k71j.js +200 -0
  86. package/dist/shared/@ai-setting/roy-agent-core-44hnfb02.js +299 -0
  87. package/dist/shared/@ai-setting/roy-agent-core-4t40mkpv.js +206 -0
  88. package/dist/shared/@ai-setting/roy-agent-core-4txzpsbt.js +393 -0
  89. package/dist/shared/@ai-setting/roy-agent-core-5x94xmt6.js +350 -0
  90. package/dist/shared/@ai-setting/roy-agent-core-69jskqjg.js +180 -0
  91. package/dist/shared/@ai-setting/roy-agent-core-6kvtahqv.js +408 -0
  92. package/dist/shared/@ai-setting/roy-agent-core-7fgf85wc.js +284 -0
  93. package/dist/shared/@ai-setting/roy-agent-core-81w1963m.js +762 -0
  94. package/dist/shared/@ai-setting/roy-agent-core-8gxth0eh.js +10 -0
  95. package/dist/shared/@ai-setting/roy-agent-core-92z6t4he.js +14 -0
  96. package/dist/shared/@ai-setting/roy-agent-core-93zfb3r1.js +922 -0
  97. package/dist/shared/@ai-setting/roy-agent-core-9yxb3ty9.js +15 -0
  98. package/dist/shared/@ai-setting/roy-agent-core-b0x5dda6.js +1130 -0
  99. package/dist/shared/@ai-setting/roy-agent-core-bcbqy27c.js +14 -0
  100. package/dist/shared/@ai-setting/roy-agent-core-bvr1761x.js +653 -0
  101. package/dist/shared/@ai-setting/roy-agent-core-ctdhjv68.js +93 -0
  102. package/dist/shared/@ai-setting/roy-agent-core-d7cyjkf7.js +872 -0
  103. package/dist/shared/@ai-setting/roy-agent-core-dh9d7a3m.js +11 -0
  104. package/dist/shared/@ai-setting/roy-agent-core-e25xkv53.js +64 -0
  105. package/dist/shared/@ai-setting/roy-agent-core-eajcvp4e.js +378 -0
  106. package/dist/shared/@ai-setting/roy-agent-core-f7q2x5z6.js +492 -0
  107. package/dist/shared/@ai-setting/roy-agent-core-fs0mn2jk.js +52 -0
  108. package/dist/shared/@ai-setting/roy-agent-core-g1s2h0e5.js +171 -0
  109. package/dist/shared/@ai-setting/roy-agent-core-g99pxzn5.js +862 -0
  110. package/dist/shared/@ai-setting/roy-agent-core-gbqcyegm.js +1387 -0
  111. package/dist/shared/@ai-setting/roy-agent-core-gjq1yk68.js +208 -0
  112. package/dist/shared/@ai-setting/roy-agent-core-gq20wsgv.js +139 -0
  113. package/dist/shared/@ai-setting/roy-agent-core-gwc4h96n.js +534 -0
  114. package/dist/shared/@ai-setting/roy-agent-core-jfh9q2qh.js +204 -0
  115. package/dist/shared/@ai-setting/roy-agent-core-jvatggbb.js +603 -0
  116. package/dist/shared/@ai-setting/roy-agent-core-kkbwepqb.js +97 -0
  117. package/dist/shared/@ai-setting/roy-agent-core-pjr12nnd.js +587 -0
  118. package/dist/shared/@ai-setting/roy-agent-core-psv4v63c.js +176 -0
  119. package/dist/shared/@ai-setting/roy-agent-core-psvxt4c9.js +60 -0
  120. package/dist/shared/@ai-setting/roy-agent-core-qqceba6k.js +442 -0
  121. package/dist/shared/@ai-setting/roy-agent-core-qxhq8ven.js +57 -0
  122. package/dist/shared/@ai-setting/roy-agent-core-qxnbvgwe.js +66 -0
  123. package/dist/shared/@ai-setting/roy-agent-core-r9ezzemr.js +10 -0
  124. package/dist/shared/@ai-setting/roy-agent-core-rhmtwnw1.js +267 -0
  125. package/dist/shared/@ai-setting/roy-agent-core-rvv6ydff.js +584 -0
  126. package/dist/shared/@ai-setting/roy-agent-core-rvxg1wps.js +102 -0
  127. package/dist/shared/@ai-setting/roy-agent-core-satmq6sh.js +549 -0
  128. package/dist/shared/@ai-setting/roy-agent-core-sx7wsvnn.js +15 -0
  129. package/dist/shared/@ai-setting/roy-agent-core-t94ktchq.js +213 -0
  130. package/dist/shared/@ai-setting/roy-agent-core-vf215qfv.js +812 -0
  131. package/dist/shared/@ai-setting/roy-agent-core-vkz81f7v.js +1316 -0
  132. package/dist/shared/@ai-setting/roy-agent-core-vn2bc59q.js +1205 -0
  133. package/dist/shared/@ai-setting/roy-agent-core-wa1kzqky.js +328 -0
  134. package/dist/shared/@ai-setting/roy-agent-core-wft9ra24.js +20 -0
  135. package/dist/shared/@ai-setting/roy-agent-core-wrcy0h6z.js +2098 -0
  136. package/dist/shared/@ai-setting/roy-agent-core-xq8hhqb8.js +419 -0
  137. package/dist/shared/@ai-setting/roy-agent-core-xs5rsgat.js +368 -0
  138. package/dist/shared/@ai-setting/roy-agent-core-zbkpc41z.js +377 -0
  139. package/dist/shared/@ai-setting/roy-agent-core-zgypchmt.js +172 -0
  140. package/dist/shared/@ai-setting/roy-agent-core-zpn0bqa8.js +103 -0
  141. package/package.json +1 -1
@@ -0,0 +1,872 @@
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 };