@simulacra-ai/session 0.0.3 → 0.0.5

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,693 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DrizzleSessionStore: () => DrizzleSessionStore,
34
+ FileSessionStore: () => FileSessionStore,
35
+ InMemorySessionStore: () => InMemorySessionStore,
36
+ SessionManager: () => SessionManager
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/session-manager.ts
41
+ var import_node_crypto = require("crypto");
42
+ var import_node_events = __toESM(require("events"), 1);
43
+ var SessionManager = class _SessionManager {
44
+ #store;
45
+ #conversation;
46
+ #auto_save;
47
+ #auto_slug;
48
+ #event_emitter = new import_node_events.default();
49
+ #child_sessions = [];
50
+ #session_id;
51
+ #fork_offset = 0;
52
+ #has_label = false;
53
+ #disposed = false;
54
+ /**
55
+ * Creates a new SessionManager instance.
56
+ *
57
+ * @param store - The storage backend to use for persisting sessions.
58
+ * @param conversation - The conversation instance to manage.
59
+ * @param options - Optional configuration for session management behavior.
60
+ */
61
+ constructor(store, conversation, options) {
62
+ this.#store = store;
63
+ this.#conversation = conversation;
64
+ this.#auto_save = options?.auto_save ?? true;
65
+ this.#auto_slug = options?.auto_slug ?? true;
66
+ if (this.#auto_save) {
67
+ this.#conversation.on("message_complete", this.#on_message_complete);
68
+ }
69
+ this.#conversation.on("create_child", this.#on_create_child);
70
+ this.#conversation.once("dispose", this.#on_conversation_dispose);
71
+ }
72
+ /**
73
+ * The ID of the currently active session.
74
+ *
75
+ * @returns The session ID if a session is active, otherwise undefined.
76
+ */
77
+ get current_session_id() {
78
+ return this.#session_id;
79
+ }
80
+ /**
81
+ * Whether a session is currently loaded.
82
+ *
83
+ * @returns True if a session is active, false otherwise.
84
+ */
85
+ get is_loaded() {
86
+ return !!this.#session_id;
87
+ }
88
+ /**
89
+ * Disposes of the SessionManager and cleans up resources.
90
+ *
91
+ * This method removes event listeners, disposes child sessions, and emits the dispose event.
92
+ * It is called automatically when the associated conversation is disposed or when using
93
+ * explicit resource management.
94
+ */
95
+ [Symbol.dispose]() {
96
+ if (this.#disposed) {
97
+ return;
98
+ }
99
+ this.#disposed = true;
100
+ for (const child of this.#child_sessions) {
101
+ child[Symbol.dispose]();
102
+ }
103
+ this.#child_sessions.length = 0;
104
+ this.#conversation.off("message_complete", this.#on_message_complete);
105
+ this.#conversation.off("create_child", this.#on_create_child);
106
+ this.#conversation.off("dispose", this.#on_conversation_dispose);
107
+ this.#event_emitter.emit("dispose");
108
+ this.#event_emitter.removeAllListeners();
109
+ }
110
+ /**
111
+ * Starts a new session with a freshly generated ID.
112
+ *
113
+ * This method clears the conversation history and creates a new session. If auto_save
114
+ * is enabled or a label is provided, the session is immediately saved to the store.
115
+ *
116
+ * @param label - Optional label to assign to the new session.
117
+ * @returns The generated session ID.
118
+ */
119
+ start_new(label) {
120
+ this.#session_id = (0, import_node_crypto.randomUUID)();
121
+ this.#fork_offset = 0;
122
+ this.#has_label = !!label;
123
+ if (this.#conversation.messages.length > 0) {
124
+ this.#conversation.clear();
125
+ }
126
+ if (label || this.#auto_save) {
127
+ this.save({ label }).catch((error) => {
128
+ this.#event_emitter.emit("lifecycle_error", {
129
+ error,
130
+ operation: "save",
131
+ context: { session_id: this.#session_id }
132
+ });
133
+ });
134
+ }
135
+ return this.#session_id;
136
+ }
137
+ /**
138
+ * Creates a new session as a fork of an existing parent session.
139
+ *
140
+ * A fork creates a new session that inherits messages from the parent session up to
141
+ * the fork point. If detached, the fork does not inherit any messages from the parent
142
+ * but still maintains a parent reference for organizational purposes.
143
+ *
144
+ * @param parent_session_id - The ID of the session to fork from.
145
+ * @param options - Optional configuration for the fork operation.
146
+ * @param options.detached - Whether to create a detached fork that does not inherit parent messages.
147
+ * @returns A promise that resolves to the generated session ID for the fork.
148
+ */
149
+ async fork(parent_session_id, options) {
150
+ const detached = options?.detached ?? false;
151
+ this.#session_id = (0, import_node_crypto.randomUUID)();
152
+ this.#has_label = false;
153
+ if (!detached) {
154
+ this.#conversation.clear();
155
+ }
156
+ let fork_message_id;
157
+ if (!detached) {
158
+ const messages = await this.#resolve_messages(parent_session_id);
159
+ if (messages.length > 0) {
160
+ this.#conversation.load(messages);
161
+ this.#fork_offset = messages.length;
162
+ fork_message_id = messages.at(-1)?.id;
163
+ } else {
164
+ this.#fork_offset = 0;
165
+ }
166
+ } else {
167
+ this.#fork_offset = 0;
168
+ }
169
+ const parent_result = await this.#store.load(parent_session_id);
170
+ if (parent_result?.metadata.checkpoint_state) {
171
+ this.#conversation.checkpoint_state = parent_result.metadata.checkpoint_state;
172
+ }
173
+ await this.save({
174
+ parent_id: parent_session_id,
175
+ fork_message_id,
176
+ detached
177
+ });
178
+ return this.#session_id;
179
+ }
180
+ /**
181
+ * Loads a session by ID or loads the most recent session if no ID is provided.
182
+ *
183
+ * If no session ID is provided and no sessions exist in the store, this method
184
+ * starts a new session automatically. Loading a session resolves its full message
185
+ * history by recursively following parent references.
186
+ *
187
+ * @param id - The ID of the session to load, or undefined to load the most recent session.
188
+ * @returns A promise that resolves when the session is loaded.
189
+ * @throws {Error} If the specified session ID is not found in the store.
190
+ */
191
+ async load(id) {
192
+ if (id) {
193
+ const messages = await this.#resolve_messages(id);
194
+ const result = await this.#store.load(id);
195
+ if (!result) {
196
+ throw new Error(`session not found: ${id}`);
197
+ }
198
+ this.#session_id = id;
199
+ this.#has_label = !!result.metadata.label;
200
+ this.#conversation.clear();
201
+ this.#fork_offset = messages.length - result.messages.length;
202
+ this.#conversation.load(messages);
203
+ this.#conversation.checkpoint_state = result.metadata.checkpoint_state;
204
+ this.#emit_load(messages);
205
+ return;
206
+ }
207
+ const sessions = await this.#store.list();
208
+ if (!sessions.length) {
209
+ this.start_new();
210
+ return;
211
+ }
212
+ const latest = sessions[0];
213
+ return this.load(latest.id);
214
+ }
215
+ /**
216
+ * Saves the current session to the store.
217
+ *
218
+ * This method persists only the messages owned by this session, excluding any messages
219
+ * inherited from parent sessions. If auto_slug is enabled and no label has been set,
220
+ * a label is automatically generated from the first user message.
221
+ *
222
+ * @param metadata - Optional partial metadata to update on the session.
223
+ * @returns A promise that resolves when the save operation is complete.
224
+ * @throws {Error} If no session is currently active.
225
+ */
226
+ async save(metadata) {
227
+ if (!this.#session_id) {
228
+ throw new Error("no active session");
229
+ }
230
+ const all_messages = this.#conversation.messages;
231
+ const owned_messages = [...all_messages].slice(this.#fork_offset);
232
+ if (this.#auto_slug && !metadata?.label && !this.#has_label) {
233
+ const slug = _SessionManager.#derive_slug(all_messages);
234
+ if (slug) {
235
+ metadata = { ...metadata, label: slug };
236
+ this.#has_label = true;
237
+ }
238
+ }
239
+ const conversation_metadata = { ...metadata };
240
+ if (this.#conversation.is_checkpoint) {
241
+ conversation_metadata.is_checkpoint = true;
242
+ }
243
+ const checkpoint_state = this.#conversation.checkpoint_state;
244
+ if (checkpoint_state) {
245
+ conversation_metadata.checkpoint_state = { ...checkpoint_state };
246
+ }
247
+ await this.#store.save(this.#session_id, owned_messages, conversation_metadata);
248
+ this.#event_emitter.emit("save", {
249
+ id: this.#session_id,
250
+ messages: Object.freeze([...all_messages])
251
+ });
252
+ }
253
+ /**
254
+ * Lists all sessions stored in the store.
255
+ *
256
+ * @returns A promise that resolves to an array of session metadata, typically sorted by last update time.
257
+ */
258
+ async list() {
259
+ return this.#store.list();
260
+ }
261
+ /**
262
+ * Deletes a session from the store.
263
+ *
264
+ * If the deleted session is currently active, the conversation is cleared and the
265
+ * current session is unset.
266
+ *
267
+ * @param id - The ID of the session to delete.
268
+ * @returns A promise that resolves to true if the session was deleted, false if it was not found.
269
+ */
270
+ async delete(id) {
271
+ if (id === this.#session_id) {
272
+ this.#session_id = void 0;
273
+ this.#conversation.clear();
274
+ }
275
+ return this.#store.delete(id);
276
+ }
277
+ /**
278
+ * Renames a session by updating its label.
279
+ *
280
+ * @param id - The ID of the session to rename.
281
+ * @param label - The new label to assign to the session.
282
+ * @returns A promise that resolves when the rename operation is complete.
283
+ * @throws {Error} If the specified session ID is not found in the store.
284
+ */
285
+ async rename(id, label) {
286
+ const result = await this.#store.load(id);
287
+ if (!result) {
288
+ throw new Error(`session not found: ${id}`);
289
+ }
290
+ await this.#store.save(id, result.messages, { label });
291
+ if (id === this.#session_id) {
292
+ this.#has_label = true;
293
+ }
294
+ }
295
+ /**
296
+ * Registers an event listener for the specified event.
297
+ *
298
+ * @param event - The name of the event to listen for.
299
+ * @param listener - The callback function to invoke when the event is emitted.
300
+ * @returns This SessionManager instance for method chaining.
301
+ */
302
+ on(event, listener) {
303
+ this.#event_emitter.on(event, listener);
304
+ return this;
305
+ }
306
+ /**
307
+ * Removes an event listener for the specified event.
308
+ *
309
+ * @param event - The name of the event to stop listening for.
310
+ * @param listener - The callback function to remove.
311
+ * @returns This SessionManager instance for method chaining.
312
+ */
313
+ off(event, listener) {
314
+ this.#event_emitter.off(event, listener);
315
+ return this;
316
+ }
317
+ #emit_load(messages) {
318
+ this.#event_emitter.emit("load", {
319
+ id: this.#session_id,
320
+ messages: Object.freeze([...messages])
321
+ });
322
+ }
323
+ async #resolve_messages(id) {
324
+ const result = await this.#store.load(id);
325
+ if (!result) {
326
+ return [];
327
+ }
328
+ const { metadata, messages } = result;
329
+ if (metadata.parent_id && !metadata.detached) {
330
+ const parent_messages = await this.#resolve_messages(metadata.parent_id);
331
+ if (metadata.fork_message_id) {
332
+ const cut = parent_messages.findIndex((m) => m.id === metadata.fork_message_id);
333
+ if (cut >= 0) {
334
+ return [...parent_messages.slice(0, cut + 1), ...messages];
335
+ }
336
+ }
337
+ return [...parent_messages, ...messages];
338
+ }
339
+ return messages;
340
+ }
341
+ static #derive_slug(messages) {
342
+ const first_user = messages.find((m) => m.role === "user");
343
+ if (!first_user) {
344
+ return void 0;
345
+ }
346
+ const text_content = first_user.content.find((c) => c.type === "text");
347
+ if (!text_content || text_content.type !== "text" || !text_content.text) {
348
+ return void 0;
349
+ }
350
+ const raw = text_content.text.trim();
351
+ if (!raw) {
352
+ return void 0;
353
+ }
354
+ const truncated = raw.slice(0, 60);
355
+ const at_boundary = truncated.replace(/\s+\S*$/, "");
356
+ return (at_boundary || truncated).slice(0, 50);
357
+ }
358
+ #on_create_child = (child) => {
359
+ if (!this.#session_id) {
360
+ return;
361
+ }
362
+ const child_session = new _SessionManager(this.#store, child, {
363
+ auto_save: this.#auto_save,
364
+ auto_slug: !child.is_checkpoint && this.#auto_slug
365
+ });
366
+ child_session.fork(this.#session_id, { detached: true }).catch((error) => {
367
+ this.#event_emitter.emit("lifecycle_error", { error, operation: "fork" });
368
+ });
369
+ this.#child_sessions.push(child_session);
370
+ child.once("dispose", () => {
371
+ child_session[Symbol.dispose]();
372
+ const idx = this.#child_sessions.indexOf(child_session);
373
+ if (idx >= 0) {
374
+ this.#child_sessions.splice(idx, 1);
375
+ }
376
+ });
377
+ };
378
+ #on_message_complete = () => {
379
+ if (this.#session_id) {
380
+ this.save().catch((error) => {
381
+ this.#event_emitter.emit("lifecycle_error", {
382
+ error,
383
+ operation: "save",
384
+ context: { session_id: this.#session_id }
385
+ });
386
+ });
387
+ }
388
+ };
389
+ #on_conversation_dispose = () => this[Symbol.dispose]();
390
+ };
391
+
392
+ // src/file-session-store.ts
393
+ var import_promises = __toESM(require("fs/promises"), 1);
394
+ var import_node_path = __toESM(require("path"), 1);
395
+ var FileSessionStore = class {
396
+ #root;
397
+ /**
398
+ * Creates a new FileSessionStore instance.
399
+ *
400
+ * @param root - The absolute path to the directory where session files will be stored.
401
+ */
402
+ constructor(root) {
403
+ this.#root = root;
404
+ }
405
+ /**
406
+ * Lists all sessions stored in the file system.
407
+ *
408
+ * Reads all JSON files from the root directory and parses their metadata.
409
+ *
410
+ * @returns A promise that resolves to an array of session metadata, sorted by most recently updated first.
411
+ */
412
+ async list() {
413
+ await this.#ensure_dir();
414
+ const sessions = [];
415
+ const entries = await import_promises.default.readdir(this.#root, { withFileTypes: true });
416
+ for (const entry of entries) {
417
+ if (!entry.isFile() || !entry.name.endsWith(".json")) {
418
+ continue;
419
+ }
420
+ const session = await this.#read_session(
421
+ import_node_path.default.join(this.#root, entry.name),
422
+ entry.name.replace(/\.json$/, "")
423
+ );
424
+ if (session) {
425
+ sessions.push(session);
426
+ }
427
+ }
428
+ return sessions.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
429
+ }
430
+ /**
431
+ * Loads a session from the file system.
432
+ *
433
+ * @param id - The unique identifier of the session to load.
434
+ * @returns A promise that resolves to the session metadata and messages, or undefined if not found.
435
+ */
436
+ async load(id) {
437
+ return this.#read_file(import_node_path.default.join(this.#root, `${id}.json`), id);
438
+ }
439
+ /**
440
+ * Saves a session to the file system.
441
+ *
442
+ * Creates a new session file if the ID does not exist, or updates an existing file.
443
+ * Automatically updates the updated_at timestamp and message_count. If the session
444
+ * has a parent, creates a hard link in the parent's fork directory for efficient querying.
445
+ *
446
+ * @param id - The unique identifier of the session.
447
+ * @param messages - The messages to store for this session.
448
+ * @param metadata - Optional partial metadata to merge with existing metadata.
449
+ * @returns A promise that resolves when the save operation is complete.
450
+ */
451
+ async save(id, messages, metadata) {
452
+ const now = (/* @__PURE__ */ new Date()).toISOString();
453
+ await this.#ensure_dir();
454
+ const file_path = import_node_path.default.join(this.#root, `${id}.json`);
455
+ const existing = await this.#read_file(file_path, id);
456
+ const existing_metadata = existing?.metadata ?? {};
457
+ const parent_id = metadata?.parent_id ?? existing_metadata.parent_id;
458
+ const file = {
459
+ metadata: {
460
+ ...existing_metadata,
461
+ created_at: existing_metadata.created_at ?? now,
462
+ updated_at: now,
463
+ message_count: messages.length,
464
+ ...metadata
465
+ },
466
+ messages
467
+ };
468
+ await import_promises.default.writeFile(file_path, JSON.stringify(file, null, 2), "utf8");
469
+ if (parent_id) {
470
+ await this.#ensure_fork_link(parent_id, id);
471
+ }
472
+ }
473
+ /**
474
+ * Deletes a session from the file system.
475
+ *
476
+ * Removes the session file, any hard links in parent fork directories, and the session's
477
+ * own fork directory if it exists.
478
+ *
479
+ * @param id - The unique identifier of the session to delete.
480
+ * @returns A promise that resolves to true if the session was deleted, false if it was not found.
481
+ */
482
+ async delete(id) {
483
+ const file_path = import_node_path.default.join(this.#root, `${id}.json`);
484
+ try {
485
+ const result = await this.#read_file(file_path, id);
486
+ await import_promises.default.unlink(file_path);
487
+ if (result?.metadata.parent_id) {
488
+ const link = import_node_path.default.join(this.#root, `${result.metadata.parent_id}-forks`, `${id}.json`);
489
+ try {
490
+ await import_promises.default.unlink(link);
491
+ } catch {
492
+ }
493
+ }
494
+ const fork_dir = import_node_path.default.join(this.#root, `${id}-forks`);
495
+ try {
496
+ await import_promises.default.rm(fork_dir, { recursive: true });
497
+ } catch {
498
+ }
499
+ return true;
500
+ } catch {
501
+ return false;
502
+ }
503
+ }
504
+ async #ensure_fork_link(parent_id, fork_id) {
505
+ const fork_dir = import_node_path.default.join(this.#root, `${parent_id}-forks`);
506
+ await import_promises.default.mkdir(fork_dir, { recursive: true });
507
+ const canonical = import_node_path.default.join(this.#root, `${fork_id}.json`);
508
+ const link = import_node_path.default.join(fork_dir, `${fork_id}.json`);
509
+ try {
510
+ await import_promises.default.unlink(link);
511
+ } catch {
512
+ }
513
+ try {
514
+ await import_promises.default.link(canonical, link);
515
+ } catch {
516
+ }
517
+ }
518
+ async #read_file(file_path, id) {
519
+ try {
520
+ const content = await import_promises.default.readFile(file_path, "utf8");
521
+ const data = JSON.parse(content);
522
+ return {
523
+ metadata: { id, ...data.metadata },
524
+ messages: data.messages
525
+ };
526
+ } catch {
527
+ return void 0;
528
+ }
529
+ }
530
+ async #read_session(file_path, id) {
531
+ try {
532
+ const content = await import_promises.default.readFile(file_path, "utf8");
533
+ const data = JSON.parse(content);
534
+ return { id, ...data.metadata };
535
+ } catch {
536
+ return void 0;
537
+ }
538
+ }
539
+ async #ensure_dir() {
540
+ await import_promises.default.mkdir(this.#root, { recursive: true });
541
+ }
542
+ };
543
+
544
+ // src/in-memory-session-store.ts
545
+ var InMemorySessionStore = class {
546
+ #sessions = /* @__PURE__ */ new Map();
547
+ /**
548
+ * Lists all sessions stored in memory.
549
+ *
550
+ * @returns A promise that resolves to an array of session metadata, sorted by most recently updated first.
551
+ */
552
+ async list() {
553
+ return [...this.#sessions.values()].map((s) => s.metadata).sort((a, b) => b.updated_at.localeCompare(a.updated_at));
554
+ }
555
+ /**
556
+ * Loads a session from memory.
557
+ *
558
+ * Returns a deep clone of the stored data to prevent external mutations.
559
+ *
560
+ * @param id - The unique identifier of the session to load.
561
+ * @returns A promise that resolves to the session metadata and messages, or undefined if not found.
562
+ */
563
+ async load(id) {
564
+ const entry = this.#sessions.get(id);
565
+ if (!entry) {
566
+ return void 0;
567
+ }
568
+ return {
569
+ metadata: { ...entry.metadata },
570
+ messages: structuredClone(entry.messages)
571
+ };
572
+ }
573
+ /**
574
+ * Saves a session to memory.
575
+ *
576
+ * Creates a new session if the ID does not exist, or updates an existing session.
577
+ * Automatically updates the updated_at timestamp and message_count.
578
+ *
579
+ * @param id - The unique identifier of the session.
580
+ * @param messages - The messages to store for this session.
581
+ * @param metadata - Optional partial metadata to merge with existing metadata.
582
+ * @returns A promise that resolves when the save operation is complete.
583
+ */
584
+ async save(id, messages, metadata) {
585
+ const now = (/* @__PURE__ */ new Date()).toISOString();
586
+ const existing = this.#sessions.get(id);
587
+ this.#sessions.set(id, {
588
+ metadata: {
589
+ id,
590
+ ...existing?.metadata,
591
+ created_at: existing?.metadata.created_at ?? now,
592
+ updated_at: now,
593
+ message_count: messages.length,
594
+ ...metadata
595
+ },
596
+ messages: structuredClone(messages)
597
+ });
598
+ }
599
+ /**
600
+ * Deletes a session from memory.
601
+ *
602
+ * @param id - The unique identifier of the session to delete.
603
+ * @returns A promise that resolves to true if the session was deleted, false if it was not found.
604
+ */
605
+ async delete(id) {
606
+ return this.#sessions.delete(id);
607
+ }
608
+ };
609
+
610
+ // src/drizzle-session-store.ts
611
+ var DrizzleSessionStore = class {
612
+ #adapter;
613
+ constructor(adapter) {
614
+ this.#adapter = adapter;
615
+ }
616
+ /**
617
+ * Lists all sessions, sorted by most recently updated first.
618
+ *
619
+ * @returns A promise that resolves to an array of session metadata.
620
+ */
621
+ async list() {
622
+ const rows = await this.#adapter.list();
623
+ return rows.map((row) => ({
624
+ id: row.id,
625
+ ...row.metadata
626
+ }));
627
+ }
628
+ /**
629
+ * Loads a session by its ID.
630
+ *
631
+ * @param id - The unique identifier of the session to load.
632
+ * @returns A promise that resolves to the session metadata and messages, or undefined if not found.
633
+ */
634
+ async load(id) {
635
+ const row = await this.#adapter.load(id);
636
+ if (!row) {
637
+ return void 0;
638
+ }
639
+ return {
640
+ metadata: {
641
+ id,
642
+ ...row.metadata
643
+ },
644
+ messages: row.messages
645
+ };
646
+ }
647
+ /**
648
+ * Saves a session with the given messages and metadata.
649
+ *
650
+ * Creates a new session if the ID does not exist, or updates the existing session.
651
+ * Automatically updates the `updated_at` timestamp and `message_count`.
652
+ *
653
+ * @param id - The unique identifier of the session.
654
+ * @param messages - The messages to store for this session.
655
+ * @param metadata - Optional partial metadata to merge with existing metadata.
656
+ * @returns A promise that resolves when the save operation is complete.
657
+ */
658
+ async save(id, messages, metadata) {
659
+ const now = (/* @__PURE__ */ new Date()).toISOString();
660
+ const existing = await this.#adapter.load(id);
661
+ const existing_metadata = existing?.metadata;
662
+ const merged = {
663
+ ...existing_metadata,
664
+ created_at: existing_metadata?.created_at ?? now,
665
+ updated_at: now,
666
+ message_count: messages.length,
667
+ ...metadata
668
+ };
669
+ await this.#adapter.upsert({
670
+ id,
671
+ metadata: merged,
672
+ messages,
673
+ updated_at: now
674
+ });
675
+ }
676
+ /**
677
+ * Deletes a session by its ID.
678
+ *
679
+ * @param id - The unique identifier of the session to delete.
680
+ * @returns A promise that resolves to true if the session was deleted, false if it was not found.
681
+ */
682
+ async delete(id) {
683
+ return this.#adapter.delete(id);
684
+ }
685
+ };
686
+ // Annotate the CommonJS export names for ESM import in node:
687
+ 0 && (module.exports = {
688
+ DrizzleSessionStore,
689
+ FileSessionStore,
690
+ InMemorySessionStore,
691
+ SessionManager
692
+ });
693
+ //# sourceMappingURL=index.cjs.map