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