@raisindb/client 0.1.16 → 0.1.18

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 (44) hide show
  1. package/README.md +281 -70
  2. package/dist/chunk-DJDP5CX6.mjs +866 -0
  3. package/dist/chunk-DJDP5CX6.mjs.map +1 -0
  4. package/dist/chunk-JRFBP4WK.mjs +170 -0
  5. package/dist/chunk-JRFBP4WK.mjs.map +1 -0
  6. package/dist/chunk-OLJOZIIU.mjs +1348 -0
  7. package/dist/chunk-OLJOZIIU.mjs.map +1 -0
  8. package/dist/chunk-T2ZSNYFG.mjs +248 -0
  9. package/dist/chunk-T2ZSNYFG.mjs.map +1 -0
  10. package/dist/chunk-VZX3ACSO.mjs +190 -0
  11. package/dist/chunk-VZX3ACSO.mjs.map +1 -0
  12. package/dist/chunk-WFBAWOVM.mjs +532 -0
  13. package/dist/chunk-WFBAWOVM.mjs.map +1 -0
  14. package/dist/conversation-list-store-CNcVagmw.d.mts +6120 -0
  15. package/dist/conversation-list-store-CNcVagmw.d.ts +6120 -0
  16. package/dist/index-DQjE-4Oj.d.ts +301 -0
  17. package/dist/index-FkFH4HHQ.d.mts +301 -0
  18. package/dist/index.d.mts +66 -6108
  19. package/dist/index.d.ts +66 -6108
  20. package/dist/index.js +859 -109
  21. package/dist/index.js.map +1 -0
  22. package/dist/index.mjs +639 -3108
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/react.d.mts +4 -0
  25. package/dist/react.d.ts +4 -0
  26. package/dist/react.js +2500 -0
  27. package/dist/react.js.map +1 -0
  28. package/dist/react.mjs +9 -0
  29. package/dist/react.mjs.map +1 -0
  30. package/dist/svelte-sql-62EaYoeM.d.ts +52 -0
  31. package/dist/svelte-sql-CgT-Ij-P.d.mts +52 -0
  32. package/dist/svelte.d.mts +288 -0
  33. package/dist/svelte.d.ts +288 -0
  34. package/dist/svelte.js +2413 -0
  35. package/dist/svelte.js.map +1 -0
  36. package/dist/svelte.mjs +25 -0
  37. package/dist/svelte.mjs.map +1 -0
  38. package/dist/vue.d.mts +197 -0
  39. package/dist/vue.d.ts +197 -0
  40. package/dist/vue.js +1441 -0
  41. package/dist/vue.js.map +1 -0
  42. package/dist/vue.mjs +9 -0
  43. package/dist/vue.mjs.map +1 -0
  44. package/package.json +18 -3
@@ -0,0 +1,1348 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/utils/reconnect.ts
9
+ var ReconnectManager = class {
10
+ constructor(options = {}) {
11
+ this.attempts = 0;
12
+ this.isReconnecting = false;
13
+ this.initialDelay = options.initialDelay ?? 1e3;
14
+ this.maxDelay = options.maxDelay ?? 3e4;
15
+ this.backoffMultiplier = options.backoffMultiplier ?? 2;
16
+ this.maxAttempts = options.maxAttempts ?? Infinity;
17
+ this.jitter = options.jitter ?? true;
18
+ this.currentDelay = this.initialDelay;
19
+ }
20
+ /**
21
+ * Schedule a reconnection attempt
22
+ *
23
+ * @param callback - Function to call when it's time to reconnect
24
+ * @returns true if reconnection was scheduled, false if max attempts reached
25
+ */
26
+ scheduleReconnect(callback) {
27
+ if (this.attempts >= this.maxAttempts) {
28
+ return false;
29
+ }
30
+ this.cancelReconnect();
31
+ this.isReconnecting = true;
32
+ this.attempts++;
33
+ let delay = this.currentDelay;
34
+ if (this.jitter) {
35
+ const jitterRange = delay * 0.25;
36
+ delay += (Math.random() * 2 - 1) * jitterRange;
37
+ delay = Math.max(0, Math.round(delay));
38
+ }
39
+ this.reconnectTimeout = setTimeout(async () => {
40
+ try {
41
+ await callback();
42
+ this.reset();
43
+ } catch (error) {
44
+ this.currentDelay = Math.min(
45
+ this.currentDelay * this.backoffMultiplier,
46
+ this.maxDelay
47
+ );
48
+ }
49
+ }, delay);
50
+ return true;
51
+ }
52
+ /**
53
+ * Cancel any pending reconnection attempt
54
+ */
55
+ cancelReconnect() {
56
+ if (this.reconnectTimeout) {
57
+ clearTimeout(this.reconnectTimeout);
58
+ this.reconnectTimeout = void 0;
59
+ }
60
+ this.isReconnecting = false;
61
+ }
62
+ /**
63
+ * Reset the reconnection state (call after successful connection)
64
+ */
65
+ reset() {
66
+ this.cancelReconnect();
67
+ this.currentDelay = this.initialDelay;
68
+ this.attempts = 0;
69
+ }
70
+ /**
71
+ * Check if currently in reconnection mode
72
+ */
73
+ isActive() {
74
+ return this.isReconnecting;
75
+ }
76
+ /**
77
+ * Get the current number of reconnection attempts
78
+ */
79
+ getAttempts() {
80
+ return this.attempts;
81
+ }
82
+ /**
83
+ * Get the current delay in milliseconds
84
+ */
85
+ getCurrentDelay() {
86
+ return this.currentDelay;
87
+ }
88
+ /**
89
+ * Check if max attempts have been reached
90
+ */
91
+ hasReachedMaxAttempts() {
92
+ return this.attempts >= this.maxAttempts;
93
+ }
94
+ };
95
+
96
+ // src/logger.ts
97
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
98
+ LogLevel2[LogLevel2["Silent"] = 0] = "Silent";
99
+ LogLevel2[LogLevel2["Error"] = 1] = "Error";
100
+ LogLevel2[LogLevel2["Warn"] = 2] = "Warn";
101
+ LogLevel2[LogLevel2["Info"] = 3] = "Info";
102
+ LogLevel2[LogLevel2["Debug"] = 4] = "Debug";
103
+ return LogLevel2;
104
+ })(LogLevel || {});
105
+ var config = {
106
+ level: 1 /* Error */,
107
+ prefix: "[RaisinDB]"
108
+ };
109
+ function configureLogger(options) {
110
+ config = { ...config, ...options };
111
+ }
112
+ function getLoggerConfig() {
113
+ return { ...config };
114
+ }
115
+ function setLogLevel(level) {
116
+ config.level = level;
117
+ }
118
+ function getLogLevel() {
119
+ return config.level;
120
+ }
121
+ var logger = {
122
+ /**
123
+ * Log debug message (only shown when level >= Debug)
124
+ */
125
+ debug(...args) {
126
+ if (config.level >= 4 /* Debug */) {
127
+ console.log(config.prefix, ...args);
128
+ }
129
+ },
130
+ /**
131
+ * Log info message (only shown when level >= Info)
132
+ */
133
+ info(...args) {
134
+ if (config.level >= 3 /* Info */) {
135
+ console.log(config.prefix, ...args);
136
+ }
137
+ },
138
+ /**
139
+ * Log warning message (only shown when level >= Warn)
140
+ */
141
+ warn(...args) {
142
+ if (config.level >= 2 /* Warn */) {
143
+ console.warn(config.prefix, ...args);
144
+ }
145
+ },
146
+ /**
147
+ * Log error message (only shown when level >= Error)
148
+ */
149
+ error(...args) {
150
+ if (config.level >= 1 /* Error */) {
151
+ console.error(config.prefix, ...args);
152
+ }
153
+ }
154
+ };
155
+ if (typeof globalThis !== "undefined") {
156
+ globalThis.__raisinDebug = (enable = true) => {
157
+ setLogLevel(enable ? 4 /* Debug */ : 1 /* Error */);
158
+ console.log(`[RaisinDB] Debug logging ${enable ? "ENABLED" : "DISABLED"} (includes server handler logs)`);
159
+ };
160
+ }
161
+
162
+ // src/connection.ts
163
+ import { EventEmitter } from "events";
164
+ var ConnectionState = /* @__PURE__ */ ((ConnectionState2) => {
165
+ ConnectionState2["Disconnected"] = "disconnected";
166
+ ConnectionState2["Connecting"] = "connecting";
167
+ ConnectionState2["Connected"] = "connected";
168
+ ConnectionState2["Reconnecting"] = "reconnecting";
169
+ ConnectionState2["Closed"] = "closed";
170
+ return ConnectionState2;
171
+ })(ConnectionState || {});
172
+ function getWebSocketImpl() {
173
+ if (typeof WebSocket !== "undefined") {
174
+ return WebSocket;
175
+ }
176
+ try {
177
+ const ws = __require("ws");
178
+ return ws.WebSocket || ws.default || ws;
179
+ } catch (error) {
180
+ throw new Error(
181
+ 'WebSocket implementation not found. In Node.js, please install the "ws" package: npm install ws'
182
+ );
183
+ }
184
+ }
185
+ var Connection = class extends EventEmitter {
186
+ constructor(url, options = {}) {
187
+ super();
188
+ this.state = "disconnected" /* Disconnected */;
189
+ this.manualClose = false;
190
+ this.url = url.replace(/^raisin:\/\//, "ws://").replace(/^raisins:\/\//, "wss://");
191
+ this.options = {
192
+ autoReconnect: options.autoReconnect ?? true,
193
+ heartbeatInterval: options.heartbeatInterval ?? 3e4,
194
+ heartbeatTimeout: options.heartbeatTimeout ?? 5e3,
195
+ protocols: options.protocols,
196
+ headers: options.headers
197
+ };
198
+ this.reconnectManager = new ReconnectManager(options.reconnectOptions);
199
+ this.WebSocketImpl = getWebSocketImpl();
200
+ }
201
+ /**
202
+ * Connect to the WebSocket server
203
+ */
204
+ async connect() {
205
+ if (this.state === "connected" /* Connected */ || this.state === "connecting" /* Connecting */) {
206
+ return;
207
+ }
208
+ this.manualClose = false;
209
+ this.setState("connecting" /* Connecting */);
210
+ return new Promise((resolve, reject) => {
211
+ try {
212
+ const isBrowserWebSocket = typeof WebSocket !== "undefined" && this.WebSocketImpl === WebSocket;
213
+ this.ws = isBrowserWebSocket || !this.options.headers ? new this.WebSocketImpl(this.url, this.options.protocols) : new this.WebSocketImpl(this.url, this.options.protocols, {
214
+ headers: this.options.headers
215
+ });
216
+ this.ws.binaryType = "arraybuffer";
217
+ this.ws.onopen = () => {
218
+ this.setState("connected" /* Connected */);
219
+ this.reconnectManager.reset();
220
+ this.startHeartbeat();
221
+ resolve();
222
+ };
223
+ this.ws.onmessage = (event) => {
224
+ logger.debug(`WebSocket onmessage fired - data type: ${typeof event.data}, is ArrayBuffer: ${event.data instanceof ArrayBuffer}`);
225
+ this.resetHeartbeat();
226
+ const data = event.data;
227
+ logger.debug(`Received binary message - size: ${data.byteLength} bytes`);
228
+ logger.debug(`Emitting 'message' event to client handlers`);
229
+ this.emit("message", data);
230
+ };
231
+ this.ws.onerror = () => {
232
+ const error = new Error("WebSocket error occurred");
233
+ this.emit("error", error);
234
+ if (this.state === "connecting" /* Connecting */) {
235
+ reject(error);
236
+ }
237
+ };
238
+ this.ws.onclose = (event) => {
239
+ this.stopHeartbeat();
240
+ this.emit("close", event);
241
+ if (!this.manualClose && this.options.autoReconnect) {
242
+ this.setState("reconnecting" /* Reconnecting */);
243
+ this.reconnect();
244
+ } else {
245
+ this.setState("disconnected" /* Disconnected */);
246
+ }
247
+ if (this.state === "connecting" /* Connecting */) {
248
+ reject(new Error(`Connection closed: ${event.reason || "Unknown reason"}`));
249
+ }
250
+ };
251
+ } catch (error) {
252
+ this.setState("disconnected" /* Disconnected */);
253
+ reject(error);
254
+ }
255
+ });
256
+ }
257
+ /**
258
+ * Disconnect from the WebSocket server
259
+ */
260
+ disconnect() {
261
+ this.manualClose = true;
262
+ this.reconnectManager.cancelReconnect();
263
+ this.stopHeartbeat();
264
+ if (this.ws) {
265
+ this.ws.close(1e3, "Client disconnect");
266
+ this.ws = void 0;
267
+ }
268
+ this.setState("closed" /* Closed */);
269
+ }
270
+ /**
271
+ * Send data through the WebSocket
272
+ *
273
+ * @param data - Data to send (Uint8Array for MessagePack)
274
+ */
275
+ send(data) {
276
+ if (this.state !== "connected" /* Connected */ || !this.ws) {
277
+ throw new Error("Cannot send data: not connected");
278
+ }
279
+ if (this.ws.readyState !== 1) {
280
+ logger.error(`WebSocket not open - readyState: ${this.ws.readyState} (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED)`);
281
+ throw new Error(`Cannot send data: WebSocket not open (readyState: ${this.ws.readyState})`);
282
+ }
283
+ logger.debug(`Sending message - size: ${data.length} bytes, readyState: ${this.ws.readyState}`);
284
+ try {
285
+ this.ws.send(data);
286
+ logger.debug(`Message sent successfully`);
287
+ } catch (error) {
288
+ logger.error(`Failed to send message:`, error);
289
+ throw new Error(`Failed to send data: ${error}`);
290
+ }
291
+ }
292
+ /**
293
+ * Get current connection state
294
+ */
295
+ getState() {
296
+ return this.state;
297
+ }
298
+ /**
299
+ * Check if connected
300
+ */
301
+ isConnected() {
302
+ return this.state === "connected" /* Connected */;
303
+ }
304
+ /**
305
+ * Whether auto-reconnect is enabled for this connection.
306
+ *
307
+ * Used by the client to decide whether requests issued while the
308
+ * connection is down can be queued (the connection will come back) or
309
+ * should fail immediately.
310
+ */
311
+ isAutoReconnectEnabled() {
312
+ return this.options.autoReconnect;
313
+ }
314
+ /**
315
+ * Reconnect to the server
316
+ */
317
+ reconnect() {
318
+ const success = this.reconnectManager.scheduleReconnect(async () => {
319
+ try {
320
+ await this.connect();
321
+ } catch (error) {
322
+ }
323
+ });
324
+ if (!success) {
325
+ this.setState("disconnected" /* Disconnected */);
326
+ this.emit("error", new Error("Max reconnection attempts reached"));
327
+ }
328
+ }
329
+ /**
330
+ * Set connection state and emit event
331
+ */
332
+ setState(state) {
333
+ if (this.state !== state) {
334
+ this.state = state;
335
+ this.emit("stateChange", state);
336
+ }
337
+ }
338
+ /**
339
+ * Start heartbeat mechanism
340
+ */
341
+ startHeartbeat() {
342
+ if (this.options.heartbeatInterval <= 0) {
343
+ return;
344
+ }
345
+ this.stopHeartbeat();
346
+ }
347
+ /**
348
+ * Stop heartbeat mechanism
349
+ */
350
+ stopHeartbeat() {
351
+ if (this.heartbeatTimer) {
352
+ clearInterval(this.heartbeatTimer);
353
+ this.heartbeatTimer = void 0;
354
+ }
355
+ if (this.heartbeatTimeoutTimer) {
356
+ clearTimeout(this.heartbeatTimeoutTimer);
357
+ this.heartbeatTimeoutTimer = void 0;
358
+ }
359
+ }
360
+ /**
361
+ * Reset heartbeat timeout (called when message received)
362
+ */
363
+ resetHeartbeat() {
364
+ if (this.heartbeatTimeoutTimer) {
365
+ clearTimeout(this.heartbeatTimeoutTimer);
366
+ this.heartbeatTimeoutTimer = void 0;
367
+ }
368
+ }
369
+ };
370
+
371
+ // src/utils/home-path.ts
372
+ var ACCESS_CONTROL_PREFIX = "/raisin:access_control";
373
+ function normalizeHomePath(home) {
374
+ if (home === null || home === void 0) return null;
375
+ let path = home.trim();
376
+ if (path.length === 0) return null;
377
+ if (path === ACCESS_CONTROL_PREFIX) return "/";
378
+ if (path.startsWith(`${ACCESS_CONTROL_PREFIX}/`)) {
379
+ path = path.slice(ACCESS_CONTROL_PREFIX.length);
380
+ }
381
+ while (path.length > 1 && path.endsWith("/")) {
382
+ path = path.slice(0, -1);
383
+ }
384
+ return path;
385
+ }
386
+
387
+ // src/utils/plan-projection.ts
388
+ function asRecord(value) {
389
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
390
+ return value;
391
+ }
392
+ function asString(value) {
393
+ return typeof value === "string" && value.length > 0 ? value : void 0;
394
+ }
395
+ function parsePlanTasks(rawTasks) {
396
+ if (!Array.isArray(rawTasks)) return [];
397
+ return rawTasks.map((rawTask, index) => {
398
+ if (typeof rawTask === "string") {
399
+ return {
400
+ title: rawTask,
401
+ status: "pending"
402
+ };
403
+ }
404
+ const task = asRecord(rawTask);
405
+ if (!task) return null;
406
+ return {
407
+ taskId: asString(task.task_id) ?? asString(task.id),
408
+ title: asString(task.title) ?? `Task ${index + 1}`,
409
+ status: asString(task.status) ?? "pending",
410
+ description: asString(task.description),
411
+ priority: asString(task.priority)
412
+ };
413
+ }).filter((task) => task !== null);
414
+ }
415
+ function upsertTask(plan, nextTask) {
416
+ const existingIndex = plan.tasks.findIndex(
417
+ (task) => nextTask.taskId && task.taskId === nextTask.taskId || !nextTask.taskId && task.title === nextTask.title
418
+ );
419
+ if (existingIndex === -1) {
420
+ plan.tasks.push(nextTask);
421
+ return;
422
+ }
423
+ plan.tasks[existingIndex] = {
424
+ ...plan.tasks[existingIndex],
425
+ ...nextTask
426
+ };
427
+ }
428
+ function ensurePlan(plans, key, fallbackTitle, timestamp) {
429
+ const existing = plans.get(key);
430
+ if (existing) {
431
+ if (timestamp) existing.updatedAt = timestamp;
432
+ return existing;
433
+ }
434
+ const created = {
435
+ key,
436
+ title: fallbackTitle,
437
+ status: "pending_approval",
438
+ requiresApproval: true,
439
+ tasks: [],
440
+ updatedAt: timestamp
441
+ };
442
+ plans.set(key, created);
443
+ return created;
444
+ }
445
+ function projectPlansFromMessages(messages) {
446
+ const ordered = [...messages].sort((a, b) => {
447
+ const aTime = Date.parse(a.timestamp || "");
448
+ const bTime = Date.parse(b.timestamp || "");
449
+ return (Number.isNaN(aTime) ? 0 : aTime) - (Number.isNaN(bTime) ? 0 : bTime);
450
+ });
451
+ const plans = /* @__PURE__ */ new Map();
452
+ for (const message of ordered) {
453
+ const timestamp = message.timestamp;
454
+ const data = asRecord(message.data);
455
+ if (message.messageType === "ai_plan" && data) {
456
+ const planPath = asString(data.plan_path);
457
+ const planId = asString(data.plan_id);
458
+ const key = planPath || planId || message.path || message.id || `plan:${timestamp}`;
459
+ const plan = ensurePlan(
460
+ plans,
461
+ key,
462
+ asString(data.title) || message.content || "Plan",
463
+ timestamp
464
+ );
465
+ plan.planPath = planPath ?? plan.planPath;
466
+ plan.planId = planId ?? plan.planId;
467
+ plan.title = asString(data.title) || plan.title;
468
+ plan.status = asString(data.status) || plan.status;
469
+ plan.requiresApproval = Boolean(data.requires_approval) || plan.status === "pending_approval";
470
+ plan.sourceMessagePath = message.path ?? plan.sourceMessagePath;
471
+ const parsedTasks = parsePlanTasks(data.tasks);
472
+ if (parsedTasks.length > 0) {
473
+ plan.tasks = parsedTasks;
474
+ }
475
+ }
476
+ if (message.messageType === "ai_task_update" && data) {
477
+ const planPath = asString(data.plan_path);
478
+ const planId = asString(data.plan_id);
479
+ const key = planPath || planId;
480
+ if (!key) continue;
481
+ const plan = ensurePlan(plans, key, "Plan", timestamp);
482
+ plan.planPath = planPath ?? plan.planPath;
483
+ plan.planId = planId ?? plan.planId;
484
+ plan.status = asString(data.plan_status) || plan.status;
485
+ plan.requiresApproval = plan.status === "pending_approval";
486
+ const taskUpdate = {
487
+ taskId: asString(data.task_id),
488
+ title: asString(data.task_title) || asString(data.title) || "Task",
489
+ status: asString(data.status) || "pending"
490
+ };
491
+ upsertTask(plan, taskUpdate);
492
+ }
493
+ if (Array.isArray(message.children)) {
494
+ for (const child of message.children) {
495
+ if (child.type !== "plan") continue;
496
+ const key = child.path || message.path || message.id || `plan-child:${child.id}:${timestamp}`;
497
+ const plan = ensurePlan(plans, key, child.planTitle || message.content || "Plan", timestamp);
498
+ plan.title = child.planTitle || plan.title;
499
+ plan.status = child.status || plan.status;
500
+ plan.requiresApproval = plan.status === "pending_approval";
501
+ if (Array.isArray(child.tasks) && child.tasks.length > 0) {
502
+ plan.tasks = child.tasks.map((task) => ({
503
+ taskId: task.id,
504
+ title: task.title,
505
+ status: task.status
506
+ }));
507
+ }
508
+ }
509
+ }
510
+ }
511
+ return [...plans.values()].sort((a, b) => {
512
+ const aTime = Date.parse(a.updatedAt || "");
513
+ const bTime = Date.parse(b.updatedAt || "");
514
+ return (Number.isNaN(bTime) ? 0 : bTime) - (Number.isNaN(aTime) ? 0 : aTime);
515
+ });
516
+ }
517
+
518
+ // src/utils/chat-events.ts
519
+ function isRecoveredDoneEvent(event) {
520
+ if (event.type !== "done") return false;
521
+ const done = event;
522
+ if (done.recovered !== true) return false;
523
+ return typeof done.content !== "string" || done.content.trim().length === 0;
524
+ }
525
+
526
+ // src/stores/conversation-store.ts
527
+ var ConversationStore = class {
528
+ constructor(options) {
529
+ this.subscribers = /* @__PURE__ */ new Set();
530
+ // Persistent SSE subscription
531
+ this.subscription = null;
532
+ this._messages = [];
533
+ this._isStreaming = false;
534
+ this._isWaiting = false;
535
+ this._streamingText = "";
536
+ this._error = null;
537
+ this._activeToolCalls = [];
538
+ this._isLoading = false;
539
+ this._conversationType = null;
540
+ this._streamingTimer = null;
541
+ this._watchdogTimer = null;
542
+ this.manager = options.database.conversations;
543
+ this._conversationPath = options.conversationPath ?? null;
544
+ this.createOptions = options.createOptions;
545
+ this.onEvent = options.onEvent;
546
+ this._streamingTimeoutMs = options.streamingTimeoutMs ?? 12e4;
547
+ this._watchdogIntervalMs = options.watchdogIntervalMs ?? 3e4;
548
+ if (this._conversationPath) {
549
+ this.ensureSubscription();
550
+ }
551
+ }
552
+ // ==========================================================================
553
+ // Subscription
554
+ // ==========================================================================
555
+ /**
556
+ * Subscribe to state changes.
557
+ * Returns an unsubscribe function.
558
+ */
559
+ subscribe(callback) {
560
+ this.subscribers.add(callback);
561
+ callback(this.getSnapshot());
562
+ return () => {
563
+ this.subscribers.delete(callback);
564
+ };
565
+ }
566
+ /**
567
+ * Get the current state snapshot.
568
+ */
569
+ getSnapshot() {
570
+ return {
571
+ conversation: this._conversationPath ? { conversationPath: this._conversationPath, type: this._conversationType || "ai_chat" } : null,
572
+ messages: [...this._messages],
573
+ isStreaming: this._isStreaming,
574
+ isWaiting: this._isWaiting,
575
+ streamingText: this._streamingText,
576
+ error: this._error,
577
+ activeToolCalls: [...this._activeToolCalls],
578
+ plans: projectPlansFromMessages(this._messages),
579
+ isLoading: this._isLoading,
580
+ conversationPath: this._conversationPath
581
+ };
582
+ }
583
+ // ==========================================================================
584
+ // Actions
585
+ // ==========================================================================
586
+ /**
587
+ * Send a user message and stream the AI response.
588
+ *
589
+ * If no conversation exists yet and `createOptions` was provided,
590
+ * the conversation is created automatically on the first call.
591
+ */
592
+ async sendMessage(content) {
593
+ if (this._isStreaming) {
594
+ logger.warn("[ConversationStore] Cannot send message while streaming");
595
+ return;
596
+ }
597
+ logger.info("[ConversationStore] Sending message", { path: this._conversationPath });
598
+ this._error = null;
599
+ if (!this._conversationPath) {
600
+ if (!this.createOptions) {
601
+ throw new Error("No conversationPath and no createOptions provided");
602
+ }
603
+ try {
604
+ const convo = await this.manager.create({
605
+ participant: this.createOptions.participant,
606
+ input: this.createOptions.input
607
+ });
608
+ this._conversationPath = convo.conversationPath;
609
+ this._conversationType = convo.type;
610
+ for (const event of convo.initialEvents ?? []) {
611
+ this.onEvent?.(event);
612
+ this.handleEvent(event);
613
+ }
614
+ this.notify();
615
+ } catch (err) {
616
+ this._error = err instanceof Error ? err.message : String(err);
617
+ this.notify();
618
+ return;
619
+ }
620
+ }
621
+ const userMessage = {
622
+ role: "user",
623
+ content,
624
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
625
+ };
626
+ this._messages.push(userMessage);
627
+ this._isStreaming = true;
628
+ this._isWaiting = false;
629
+ this._streamingText = "";
630
+ this._activeToolCalls = [];
631
+ this.resetStreamingTimer();
632
+ this.startWatchdog();
633
+ this.notify();
634
+ try {
635
+ this.ensureSubscription();
636
+ await this.subscription.waitUntilConnected();
637
+ await this.manager.createUserMessage(this._conversationPath, content);
638
+ } catch (err) {
639
+ logger.error("[ConversationStore] Send failed", err);
640
+ this._error = err instanceof Error ? err.message : String(err);
641
+ this._isStreaming = false;
642
+ this.clearStreamingTimer();
643
+ this.stopWatchdog();
644
+ this.notify();
645
+ }
646
+ }
647
+ /**
648
+ * Load messages from the persisted node tree.
649
+ * Useful for loading history on page reload.
650
+ */
651
+ async loadMessages() {
652
+ if (!this._conversationPath) return [];
653
+ this._isLoading = true;
654
+ this.notify();
655
+ try {
656
+ const messages = await this.manager.getMessages(this._conversationPath);
657
+ logger.debug(`[ConversationStore] Loaded ${messages.length} messages`);
658
+ if (messages.length > 0) {
659
+ this._messages = messages;
660
+ this._activeToolCalls = [];
661
+ }
662
+ return messages;
663
+ } finally {
664
+ this._isLoading = false;
665
+ this.notify();
666
+ }
667
+ }
668
+ /**
669
+ * Approve a pending plan.
670
+ */
671
+ async approvePlan(planPath) {
672
+ await this.manager.approvePlan(planPath);
673
+ }
674
+ /**
675
+ * Reject a pending plan.
676
+ */
677
+ async rejectPlan(planPath, feedback) {
678
+ await this.manager.rejectPlan(planPath, feedback);
679
+ }
680
+ /**
681
+ * Mark a single message as read.
682
+ */
683
+ async markMessageAsRead(messagePath) {
684
+ await this.manager.markMessageAsRead(messagePath);
685
+ }
686
+ /**
687
+ * Stop the current streaming response.
688
+ */
689
+ stop() {
690
+ this._isStreaming = false;
691
+ this.clearStreamingTimer();
692
+ this.stopWatchdog();
693
+ this.notify();
694
+ }
695
+ /**
696
+ * Clean up the store and release resources.
697
+ */
698
+ destroy() {
699
+ this.stop();
700
+ this.clearStreamingTimer();
701
+ this.stopWatchdog();
702
+ this.subscription?.unsubscribe();
703
+ this.subscription = null;
704
+ this.subscribers.clear();
705
+ }
706
+ /**
707
+ * Get the conversation path.
708
+ */
709
+ getConversationPath() {
710
+ return this._conversationPath;
711
+ }
712
+ // ==========================================================================
713
+ // Internal
714
+ // ==========================================================================
715
+ ensureSubscription() {
716
+ if (this.subscription) return;
717
+ if (!this._conversationPath) return;
718
+ this.subscription = this.manager.subscribe(
719
+ this._conversationPath,
720
+ (event) => {
721
+ this.onEvent?.(event);
722
+ this.handleEvent(event);
723
+ }
724
+ );
725
+ }
726
+ handleEvent(event) {
727
+ logger.debug("[ConversationStore] SSE:", event.type);
728
+ if (this._isStreaming) {
729
+ this.resetStreamingTimer();
730
+ }
731
+ switch (event.type) {
732
+ case "text_chunk":
733
+ this.markStreamingActivity();
734
+ this._streamingText += event.text;
735
+ this.notify();
736
+ break;
737
+ case "thought_chunk":
738
+ this.markStreamingActivity();
739
+ this.notify();
740
+ break;
741
+ case "assistant_message":
742
+ this._messages.push(event.message);
743
+ this._streamingText = "";
744
+ this.notify();
745
+ break;
746
+ case "tool_call_started": {
747
+ this.markStreamingActivity();
748
+ logger.debug("[ConversationStore] Tool started:", event.functionName);
749
+ const info = {
750
+ id: event.toolCallId,
751
+ functionName: event.functionName,
752
+ arguments: event.arguments,
753
+ status: "running"
754
+ };
755
+ this._activeToolCalls.push(info);
756
+ this.notify();
757
+ break;
758
+ }
759
+ case "tool_call_completed": {
760
+ this.markStreamingActivity();
761
+ logger.debug("[ConversationStore] Tool completed:", event.toolCallId);
762
+ const idx = this._activeToolCalls.findIndex((tc) => tc.id === event.toolCallId);
763
+ if (idx >= 0) {
764
+ this._activeToolCalls[idx] = {
765
+ ...this._activeToolCalls[idx],
766
+ status: event.error ? "failed" : "completed",
767
+ result: event.result,
768
+ durationMs: event.durationMs
769
+ };
770
+ }
771
+ this.notify();
772
+ break;
773
+ }
774
+ case "waiting": {
775
+ logger.info("[ConversationStore] Waiting for input");
776
+ this.flushStreamingText(event.timestamp);
777
+ this._isStreaming = false;
778
+ this._isWaiting = true;
779
+ this._activeToolCalls = [];
780
+ this.clearStreamingTimer();
781
+ this.stopWatchdog();
782
+ this.notify();
783
+ this.deferredReload();
784
+ break;
785
+ }
786
+ case "done": {
787
+ if (isRecoveredDoneEvent(event)) {
788
+ logger.debug("[ConversationStore] Ignoring recovered done event");
789
+ this.reconcileRecoveredDone();
790
+ break;
791
+ }
792
+ const doneEvent = event;
793
+ if (doneEvent.dispatchPhase && doneEvent.dispatchPhase !== "terminal") {
794
+ logger.debug("[ConversationStore] Ignoring non-terminal done event");
795
+ break;
796
+ }
797
+ logger.info("[ConversationStore] Turn done");
798
+ this.flushStreamingText(event.timestamp);
799
+ if (doneEvent.content && !this.lastMessageIsAssistant()) {
800
+ this._messages.push({
801
+ role: doneEvent.role || "assistant",
802
+ content: doneEvent.content,
803
+ timestamp: event.timestamp,
804
+ senderDisplayName: doneEvent.senderDisplayName,
805
+ finishReason: doneEvent.finishReason
806
+ });
807
+ }
808
+ this._isStreaming = false;
809
+ this._isWaiting = true;
810
+ this._activeToolCalls = [];
811
+ this.clearStreamingTimer();
812
+ this.stopWatchdog();
813
+ this.notify();
814
+ this.deferredReload();
815
+ break;
816
+ }
817
+ case "completed": {
818
+ this.flushStreamingText(event.timestamp);
819
+ if (event.messages && event.messages.length > 0) {
820
+ this._messages = event.messages;
821
+ }
822
+ this._isStreaming = false;
823
+ this._isWaiting = false;
824
+ this._activeToolCalls = [];
825
+ this.clearStreamingTimer();
826
+ this.stopWatchdog();
827
+ this.notify();
828
+ this.deferredReload();
829
+ break;
830
+ }
831
+ case "failed":
832
+ logger.error("[ConversationStore] Turn failed", event.error);
833
+ this._error = event.error;
834
+ this._isStreaming = false;
835
+ this._isWaiting = false;
836
+ this._streamingText = "";
837
+ this._activeToolCalls = [];
838
+ this.clearStreamingTimer();
839
+ this.stopWatchdog();
840
+ this.notify();
841
+ break;
842
+ case "conversation_created":
843
+ this._conversationPath = event.conversationPath;
844
+ this.notify();
845
+ break;
846
+ case "message_saved":
847
+ this.silentReload().catch(() => {
848
+ });
849
+ this.notify();
850
+ break;
851
+ case "message_delivered":
852
+ this._messages.push(event.message);
853
+ this.notify();
854
+ break;
855
+ case "log": {
856
+ const logEvent = event;
857
+ const currentLevel = getLogLevel();
858
+ const levelMap = {
859
+ debug: 4 /* Debug */,
860
+ info: 3 /* Info */,
861
+ warn: 2 /* Warn */,
862
+ error: 1 /* Error */
863
+ };
864
+ const eventLevel = levelMap[logEvent.level] ?? 4 /* Debug */;
865
+ if (currentLevel >= eventLevel) {
866
+ const fn = logEvent.level === "error" ? console.error : logEvent.level === "warn" ? console.warn : logEvent.level === "debug" ? console.debug : console.info;
867
+ fn("[server]", logEvent.message);
868
+ }
869
+ break;
870
+ }
871
+ }
872
+ }
873
+ /**
874
+ * Agent activity observed while the store thought the turn was over.
875
+ *
876
+ * This happens when execution continues WITHOUT a user message — plan
877
+ * approval in approve_then_auto / step_by_step (approvePlan() returns an
878
+ * enqueue receipt and the agent starts executing), or agent-initiated
879
+ * follow-ups. The events arrive over the persistent live subscription
880
+ * (no history replay), so activity is always "now": re-enter streaming
881
+ * state so UIs show progress and the end-of-turn handling (done/waiting
882
+ * → deferred reload) runs again for this continuation.
883
+ */
884
+ markStreamingActivity() {
885
+ if (this._isStreaming) return;
886
+ logger.debug("[ConversationStore] Agent activity while idle \u2014 re-entering streaming state");
887
+ this._isStreaming = true;
888
+ this._isWaiting = false;
889
+ this._streamingText = "";
890
+ this.resetStreamingTimer();
891
+ this.startWatchdog();
892
+ }
893
+ /**
894
+ * If accumulated streaming text hasn't been captured in an assistant_message,
895
+ * synthesize one.
896
+ */
897
+ flushStreamingText(timestamp) {
898
+ if (this._streamingText && !this.lastMessageIsAssistant()) {
899
+ this._messages.push({
900
+ role: "assistant",
901
+ content: this._streamingText,
902
+ timestamp
903
+ });
904
+ }
905
+ this._streamingText = "";
906
+ }
907
+ lastMessageIsAssistant() {
908
+ const last = this._messages[this._messages.length - 1];
909
+ return last?.role === "assistant";
910
+ }
911
+ /**
912
+ * After a turn completes, reload canonical messages from the node tree
913
+ * to catch any events missed during SSE gaps.
914
+ */
915
+ deferredReload() {
916
+ if (!this._conversationPath) return;
917
+ logger.debug("[ConversationStore] Scheduling deferred reload");
918
+ const attemptReload = (delay, retriesLeft) => {
919
+ setTimeout(async () => {
920
+ try {
921
+ const prevCount = this._messages.length;
922
+ await this.silentReload();
923
+ if (this._messages.length === prevCount && retriesLeft > 0) {
924
+ attemptReload(delay * 2, retriesLeft - 1);
925
+ }
926
+ } catch {
927
+ }
928
+ }, delay);
929
+ };
930
+ attemptReload(500, 2);
931
+ }
932
+ async silentReload() {
933
+ if (!this._conversationPath) return;
934
+ try {
935
+ const fresh = await this.manager.getMessages(this._conversationPath);
936
+ if (fresh.length === 0) return;
937
+ let matchCount = 0;
938
+ const limit = Math.min(this._messages.length, fresh.length);
939
+ for (let i = 0; i < limit; i++) {
940
+ if (this._messages[i].role !== fresh[i].role || this._messages[i].content !== fresh[i].content) break;
941
+ matchCount++;
942
+ }
943
+ if (matchCount === this._messages.length && fresh.length === matchCount) {
944
+ for (let i = 0; i < matchCount; i++) {
945
+ const f = fresh[i];
946
+ const e = this._messages[i];
947
+ if (f.id) e.id = f.id;
948
+ if (f.path) e.path = f.path;
949
+ if (f.messageType) e.messageType = f.messageType;
950
+ if (f.data) e.data = f.data;
951
+ if (f.children) e.children = f.children;
952
+ if (f.finishReason) e.finishReason = f.finishReason;
953
+ }
954
+ await this.rebuildToolCallState();
955
+ return;
956
+ }
957
+ if (matchCount === this._messages.length && fresh.length > matchCount) {
958
+ for (let i = matchCount; i < fresh.length; i++) {
959
+ this._messages.push(fresh[i]);
960
+ }
961
+ for (let i = 0; i < matchCount; i++) {
962
+ const f = fresh[i];
963
+ const e = this._messages[i];
964
+ if (f.id) e.id = f.id;
965
+ if (f.path) e.path = f.path;
966
+ if (f.messageType) e.messageType = f.messageType;
967
+ if (f.data) e.data = f.data;
968
+ if (f.children) e.children = f.children;
969
+ }
970
+ await this.rebuildToolCallState();
971
+ this.notify();
972
+ return;
973
+ }
974
+ if (matchCount === fresh.length && fresh.length < this._messages.length) {
975
+ for (let i = 0; i < matchCount; i++) {
976
+ const f = fresh[i];
977
+ const e = this._messages[i];
978
+ if (f.id) e.id = f.id;
979
+ if (f.path) e.path = f.path;
980
+ if (f.messageType) e.messageType = f.messageType;
981
+ if (f.data) e.data = f.data;
982
+ if (f.children) e.children = f.children;
983
+ }
984
+ await this.rebuildToolCallState();
985
+ return;
986
+ }
987
+ this._messages = fresh;
988
+ await this.rebuildToolCallState();
989
+ this.notify();
990
+ } catch (err) {
991
+ logger.debug("[ConversationStore] Silent reload failed:", err);
992
+ }
993
+ }
994
+ // ==========================================================================
995
+ // Streaming timeout (Fix A) — auto-recover on SSE inactivity
996
+ // ==========================================================================
997
+ resetStreamingTimer() {
998
+ this.clearStreamingTimer();
999
+ if (!this._isStreaming) return;
1000
+ this._streamingTimer = setTimeout(() => {
1001
+ if (this._isStreaming) {
1002
+ logger.warn("[ConversationStore] Streaming timeout \u2014 no SSE activity for", this._streamingTimeoutMs, "ms");
1003
+ this.recoverFromHang();
1004
+ }
1005
+ }, this._streamingTimeoutMs);
1006
+ }
1007
+ clearStreamingTimer() {
1008
+ if (this._streamingTimer) {
1009
+ clearTimeout(this._streamingTimer);
1010
+ this._streamingTimer = null;
1011
+ }
1012
+ }
1013
+ // ==========================================================================
1014
+ // Activity watchdog (Fix B) — periodic backend health check
1015
+ // ==========================================================================
1016
+ startWatchdog() {
1017
+ this.stopWatchdog();
1018
+ if (!this._conversationPath) return;
1019
+ this._watchdogTimer = setInterval(async () => {
1020
+ if (!this._isStreaming || !this._conversationPath) {
1021
+ this.stopWatchdog();
1022
+ return;
1023
+ }
1024
+ try {
1025
+ const health = await this.manager.checkTurnHealth(this._conversationPath);
1026
+ if (health === "done" && this._isStreaming) {
1027
+ logger.warn("[ConversationStore] Watchdog detected completed turn while still streaming \u2014 recovering");
1028
+ this.recoverFromHang();
1029
+ }
1030
+ } catch {
1031
+ }
1032
+ }, this._watchdogIntervalMs);
1033
+ }
1034
+ stopWatchdog() {
1035
+ if (this._watchdogTimer) {
1036
+ clearInterval(this._watchdogTimer);
1037
+ this._watchdogTimer = null;
1038
+ }
1039
+ }
1040
+ // ==========================================================================
1041
+ // Hang recovery (shared by timeout + watchdog)
1042
+ // ==========================================================================
1043
+ recoverFromHang() {
1044
+ logger.info("[ConversationStore] Recovering from hang");
1045
+ this.clearStreamingTimer();
1046
+ this.stopWatchdog();
1047
+ this._isStreaming = false;
1048
+ this._isWaiting = true;
1049
+ this._streamingText = "";
1050
+ this.notify();
1051
+ this.silentReload().catch(() => {
1052
+ });
1053
+ }
1054
+ /**
1055
+ * Reconcile a recovered done event against persisted state.
1056
+ * If the backend turn is actually complete, finalize the local state.
1057
+ * Otherwise keep streaming active and let normal events continue.
1058
+ */
1059
+ reconcileRecoveredDone() {
1060
+ if (!this._conversationPath) return;
1061
+ void this.manager.checkTurnHealth(this._conversationPath).then((health) => {
1062
+ if (health !== "done") return;
1063
+ if (!this._isStreaming) return;
1064
+ this._isStreaming = false;
1065
+ this._isWaiting = true;
1066
+ this._activeToolCalls = [];
1067
+ this.clearStreamingTimer();
1068
+ this.stopWatchdog();
1069
+ this.notify();
1070
+ this.deferredReload();
1071
+ }).catch(() => {
1072
+ });
1073
+ }
1074
+ // ==========================================================================
1075
+ // Tool call state rebuild (Fix C) — reconstruct from node tree on reload
1076
+ // ==========================================================================
1077
+ async rebuildToolCallState() {
1078
+ if (!this._conversationPath) {
1079
+ this._activeToolCalls = [];
1080
+ return;
1081
+ }
1082
+ try {
1083
+ const pendingCalls = await this.manager.getActiveToolCalls(this._conversationPath);
1084
+ if (pendingCalls.length > 0) {
1085
+ this._activeToolCalls = pendingCalls.map((tc) => ({
1086
+ id: tc.id,
1087
+ functionName: tc.name,
1088
+ arguments: void 0,
1089
+ status: "running"
1090
+ }));
1091
+ if (!this._isStreaming) {
1092
+ this._isStreaming = true;
1093
+ this.resetStreamingTimer();
1094
+ this.startWatchdog();
1095
+ }
1096
+ } else {
1097
+ this._activeToolCalls = [];
1098
+ if (this._isStreaming) {
1099
+ const lastMsg = this._messages[this._messages.length - 1];
1100
+ const isLastAssistantDone = lastMsg?.role === "assistant" && (lastMsg.dispatchPhase ? lastMsg.dispatchPhase === "terminal" : !!lastMsg.finishReason && lastMsg.finishReason !== "tool_calls");
1101
+ if (isLastAssistantDone) {
1102
+ this._isStreaming = false;
1103
+ this._isWaiting = true;
1104
+ this.clearStreamingTimer();
1105
+ this.stopWatchdog();
1106
+ }
1107
+ }
1108
+ }
1109
+ } catch {
1110
+ this._activeToolCalls = [];
1111
+ }
1112
+ }
1113
+ notify() {
1114
+ const snapshot = this.getSnapshot();
1115
+ for (const sub of this.subscribers) {
1116
+ try {
1117
+ sub(snapshot);
1118
+ } catch (err) {
1119
+ logger.error("Error in conversation store subscriber:", err);
1120
+ }
1121
+ }
1122
+ }
1123
+ };
1124
+
1125
+ // src/stores/conversation-list-store.ts
1126
+ function buildChatsSubscriptionFilters(userHome) {
1127
+ const home = normalizeHomePath(userHome) ?? userHome;
1128
+ return {
1129
+ workspace: "raisin:access_control",
1130
+ path: `${home}/inbox/chats/**`,
1131
+ event_types: ["node:created", "node:updated"]
1132
+ };
1133
+ }
1134
+ var ConversationListStore = class {
1135
+ constructor(options) {
1136
+ this.subscribers = /* @__PURE__ */ new Set();
1137
+ // Internal state
1138
+ this._conversations = [];
1139
+ this._isLoading = false;
1140
+ this._error = null;
1141
+ // Cached ConversationStore instances
1142
+ this._stores = /* @__PURE__ */ new Map();
1143
+ // Real-time subscription
1144
+ this._realtimeSubscription = null;
1145
+ this.database = options.database;
1146
+ this.type = options.type;
1147
+ this.realtime = options.realtime ?? false;
1148
+ }
1149
+ // ==========================================================================
1150
+ // Subscription
1151
+ // ==========================================================================
1152
+ subscribe(callback) {
1153
+ this.subscribers.add(callback);
1154
+ callback(this.getSnapshot());
1155
+ return () => {
1156
+ this.subscribers.delete(callback);
1157
+ };
1158
+ }
1159
+ getSnapshot() {
1160
+ return {
1161
+ conversations: [...this._conversations],
1162
+ totalUnreadCount: this._conversations.reduce((sum, c) => sum + (c.unreadCount ?? 0), 0),
1163
+ isLoading: this._isLoading,
1164
+ error: this._error
1165
+ };
1166
+ }
1167
+ // ==========================================================================
1168
+ // Actions
1169
+ // ==========================================================================
1170
+ /**
1171
+ * Load conversations from the server.
1172
+ */
1173
+ async load() {
1174
+ this._isLoading = true;
1175
+ this._error = null;
1176
+ this.notify();
1177
+ try {
1178
+ const conversations = await this.database.conversations.list({
1179
+ type: this.type
1180
+ });
1181
+ logger.debug(`[ConversationListStore] Loaded ${conversations.length} conversations`);
1182
+ this._conversations = conversations;
1183
+ if (this.realtime) {
1184
+ this.startRealtimeSubscription();
1185
+ }
1186
+ } catch (err) {
1187
+ logger.error("[ConversationListStore] Failed to load conversations", err);
1188
+ this._error = err instanceof Error ? err.message : String(err);
1189
+ } finally {
1190
+ this._isLoading = false;
1191
+ this.notify();
1192
+ }
1193
+ }
1194
+ /**
1195
+ * Create a new conversation.
1196
+ */
1197
+ async createConversation(options) {
1198
+ const convo = await this.database.conversations.create(options);
1199
+ const listItem = {
1200
+ id: convo.id,
1201
+ type: convo.type,
1202
+ conversationPath: convo.conversationPath,
1203
+ conversationWorkspace: convo.conversationWorkspace,
1204
+ agentRef: convo.agentRef,
1205
+ participants: convo.participants,
1206
+ unreadCount: 0,
1207
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1208
+ };
1209
+ this._conversations = [listItem, ...this._conversations];
1210
+ this.notify();
1211
+ return listItem;
1212
+ }
1213
+ /**
1214
+ * Delete a conversation.
1215
+ */
1216
+ async deleteConversation(conversationPath) {
1217
+ const store = this._stores.get(conversationPath);
1218
+ if (store) {
1219
+ store.destroy();
1220
+ this._stores.delete(conversationPath);
1221
+ }
1222
+ await this.database.conversations.delete(conversationPath);
1223
+ this._conversations = this._conversations.filter((c) => c.conversationPath !== conversationPath);
1224
+ this.notify();
1225
+ }
1226
+ /**
1227
+ * Mark a conversation as read.
1228
+ */
1229
+ async markAsRead(conversationPath) {
1230
+ await this.database.conversations.markAsRead(conversationPath);
1231
+ this._conversations = this._conversations.map(
1232
+ (c) => c.conversationPath === conversationPath ? { ...c, unreadCount: 0 } : c
1233
+ );
1234
+ this.notify();
1235
+ }
1236
+ /**
1237
+ * Get or create a ConversationStore for a specific conversation.
1238
+ * Caches instances so repeated calls return the same store.
1239
+ */
1240
+ getConversationStore(conversationPath, overrides) {
1241
+ let store = this._stores.get(conversationPath);
1242
+ if (!store) {
1243
+ store = new ConversationStore({
1244
+ database: this.database,
1245
+ conversationPath,
1246
+ ...overrides
1247
+ });
1248
+ this._stores.set(conversationPath, store);
1249
+ }
1250
+ return store;
1251
+ }
1252
+ /**
1253
+ * Clean up all resources.
1254
+ */
1255
+ destroy() {
1256
+ this._realtimeSubscription?.unsubscribe();
1257
+ this._realtimeSubscription = null;
1258
+ for (const store of this._stores.values()) {
1259
+ store.destroy();
1260
+ }
1261
+ this._stores.clear();
1262
+ this.subscribers.clear();
1263
+ }
1264
+ // ==========================================================================
1265
+ // Internal
1266
+ // ==========================================================================
1267
+ async startRealtimeSubscription() {
1268
+ if (this._realtimeSubscription) return;
1269
+ logger.debug("[ConversationListStore] Starting realtime subscription");
1270
+ try {
1271
+ const workspace = this.database.workspace("raisin:access_control");
1272
+ const events = workspace.events();
1273
+ const result = await this.database.executeSql(
1274
+ `SELECT RAISIN_CURRENT_USER()->>'path'::String as home`
1275
+ );
1276
+ const rows = result.rows;
1277
+ const userHome = rows?.[0]?.home;
1278
+ if (!userHome) return;
1279
+ this._realtimeSubscription = await events.subscribe(
1280
+ buildChatsSubscriptionFilters(userHome),
1281
+ async (event) => {
1282
+ const eventData = event;
1283
+ const nodeId = eventData.payload?.node_id;
1284
+ if (!nodeId) return;
1285
+ try {
1286
+ const nodeResult = await this.database.executeSql(
1287
+ `SELECT id, path, node_type, properties, created_at, updated_at FROM 'raisin:access_control' WHERE id = $1 LIMIT 1`,
1288
+ [nodeId]
1289
+ );
1290
+ const row = nodeResult.rows?.[0];
1291
+ if (!row || row.node_type !== "raisin:Conversation") return;
1292
+ const convPath = row.path;
1293
+ const props = row.properties ?? {};
1294
+ const item = {
1295
+ id: row.id,
1296
+ type: props.conversation_type ?? "ai_chat",
1297
+ conversationPath: convPath,
1298
+ conversationWorkspace: "raisin:access_control",
1299
+ agentRef: props.agent_ref,
1300
+ participants: props.participants,
1301
+ unreadCount: props.unread_count ?? 0,
1302
+ lastMessage: props.last_message,
1303
+ updatedAt: row.updated_at ?? row.created_at
1304
+ };
1305
+ const existingIdx = this._conversations.findIndex((c) => c.conversationPath === convPath);
1306
+ if (existingIdx >= 0) {
1307
+ this._conversations.splice(existingIdx, 1);
1308
+ }
1309
+ this._conversations = [item, ...this._conversations];
1310
+ this.notify();
1311
+ } catch (err) {
1312
+ logger.debug("Failed to process conversation event:", err);
1313
+ }
1314
+ }
1315
+ );
1316
+ } catch (err) {
1317
+ logger.debug("Failed to start realtime subscription:", err);
1318
+ }
1319
+ }
1320
+ notify() {
1321
+ const snapshot = this.getSnapshot();
1322
+ for (const sub of this.subscribers) {
1323
+ try {
1324
+ sub(snapshot);
1325
+ } catch (err) {
1326
+ logger.error("Error in conversation list store subscriber:", err);
1327
+ }
1328
+ }
1329
+ }
1330
+ };
1331
+
1332
+ export {
1333
+ ReconnectManager,
1334
+ LogLevel,
1335
+ configureLogger,
1336
+ getLoggerConfig,
1337
+ setLogLevel,
1338
+ getLogLevel,
1339
+ logger,
1340
+ ConnectionState,
1341
+ Connection,
1342
+ isRecoveredDoneEvent,
1343
+ normalizeHomePath,
1344
+ projectPlansFromMessages,
1345
+ ConversationStore,
1346
+ ConversationListStore
1347
+ };
1348
+ //# sourceMappingURL=chunk-OLJOZIIU.mjs.map