@raisindb/client 0.2.4 → 0.2.6

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-CU5mi_PE.d.mts +6842 -0
  15. package/dist/conversation-list-store-CU5mi_PE.d.ts +6842 -0
  16. package/dist/index-DDus5a7P.d.mts +301 -0
  17. package/dist/index-sFvMihQA.d.ts +301 -0
  18. package/dist/index.d.mts +72 -6109
  19. package/dist/index.d.ts +72 -6109
  20. package/dist/index.js +1640 -211
  21. package/dist/index.js.map +1 -0
  22. package/dist/index.mjs +1280 -3098
  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-B2G94Q9p.d.ts +52 -0
  31. package/dist/svelte-sql-CpXHXg34.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 +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/react.js ADDED
@@ -0,0 +1,2519 @@
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/react/index.ts
21
+ var react_exports = {};
22
+ __export(react_exports, {
23
+ createRaisinReact: () => createRaisinReact
24
+ });
25
+ module.exports = __toCommonJS(react_exports);
26
+
27
+ // src/integrations/react/use-auth.ts
28
+ function createUseAuth(react, context) {
29
+ return function useAuth() {
30
+ const { useState, useEffect, useRef, useCallback, useContext } = react;
31
+ const ctx = useContext(context);
32
+ if (!ctx) {
33
+ throw new Error("useAuth must be used within a <RaisinProvider>");
34
+ }
35
+ const { client } = ctx;
36
+ const [user, setUser] = useState(client.getStoredUser());
37
+ const [isLoading, setIsLoading] = useState(false);
38
+ const mountedRef = useRef(true);
39
+ useEffect(() => {
40
+ mountedRef.current = true;
41
+ const unsubAuth = client.onAuthStateChange(({ event, session }) => {
42
+ if (!mountedRef.current) return;
43
+ if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED" || event === "USER_UPDATED") {
44
+ setUser(session.user);
45
+ } else if (event === "SIGNED_OUT" || event === "SESSION_EXPIRED") {
46
+ setUser(null);
47
+ }
48
+ });
49
+ const unsubUser = client.onUserChange(({ node }) => {
50
+ if (!mountedRef.current) return;
51
+ setUser((prev) => {
52
+ if (!prev) return prev;
53
+ return {
54
+ ...prev,
55
+ home: node.path,
56
+ displayName: node.properties.display_name ?? prev.displayName,
57
+ avatarUrl: node.properties.avatar_url ?? prev.avatarUrl
58
+ };
59
+ });
60
+ });
61
+ return () => {
62
+ mountedRef.current = false;
63
+ unsubAuth();
64
+ unsubUser();
65
+ };
66
+ }, [client]);
67
+ const login = useCallback(async (email, password, repository) => {
68
+ setIsLoading(true);
69
+ try {
70
+ const result = await client.loginWithEmail(email, password, repository);
71
+ return result;
72
+ } finally {
73
+ if (mountedRef.current) setIsLoading(false);
74
+ }
75
+ }, [client]);
76
+ const register = useCallback(async (email, password, repository, displayName) => {
77
+ setIsLoading(true);
78
+ try {
79
+ const result = await client.registerWithEmail(email, password, repository, displayName);
80
+ return result;
81
+ } finally {
82
+ if (mountedRef.current) setIsLoading(false);
83
+ }
84
+ }, [client]);
85
+ const logout = useCallback(async (options) => {
86
+ setIsLoading(true);
87
+ try {
88
+ await client.logout(options);
89
+ } finally {
90
+ if (mountedRef.current) setIsLoading(false);
91
+ }
92
+ }, [client]);
93
+ const initSession = useCallback(async (repository) => {
94
+ setIsLoading(true);
95
+ try {
96
+ const result = await client.initSession(repository);
97
+ return result;
98
+ } finally {
99
+ if (mountedRef.current) setIsLoading(false);
100
+ }
101
+ }, [client]);
102
+ return {
103
+ user,
104
+ isAuthenticated: user !== null,
105
+ isLoading,
106
+ login,
107
+ register,
108
+ logout,
109
+ initSession
110
+ };
111
+ };
112
+ }
113
+
114
+ // src/connection.ts
115
+ var import_events = require("events");
116
+
117
+ // src/utils/reconnect.ts
118
+ var ReconnectManager = class {
119
+ constructor(options = {}) {
120
+ this.attempts = 0;
121
+ this.isReconnecting = false;
122
+ this.initialDelay = options.initialDelay ?? 1e3;
123
+ this.maxDelay = options.maxDelay ?? 3e4;
124
+ this.backoffMultiplier = options.backoffMultiplier ?? 2;
125
+ this.maxAttempts = options.maxAttempts ?? Infinity;
126
+ this.jitter = options.jitter ?? true;
127
+ this.currentDelay = this.initialDelay;
128
+ }
129
+ /**
130
+ * Schedule a reconnection attempt
131
+ *
132
+ * @param callback - Function to call when it's time to reconnect
133
+ * @returns true if reconnection was scheduled, false if max attempts reached
134
+ */
135
+ scheduleReconnect(callback) {
136
+ if (this.attempts >= this.maxAttempts) {
137
+ return false;
138
+ }
139
+ this.cancelReconnect();
140
+ this.isReconnecting = true;
141
+ this.attempts++;
142
+ let delay = this.currentDelay;
143
+ if (this.jitter) {
144
+ const jitterRange = delay * 0.25;
145
+ delay += (Math.random() * 2 - 1) * jitterRange;
146
+ delay = Math.max(0, Math.round(delay));
147
+ }
148
+ this.reconnectTimeout = setTimeout(async () => {
149
+ try {
150
+ await callback();
151
+ this.reset();
152
+ } catch (error) {
153
+ this.currentDelay = Math.min(
154
+ this.currentDelay * this.backoffMultiplier,
155
+ this.maxDelay
156
+ );
157
+ }
158
+ }, delay);
159
+ return true;
160
+ }
161
+ /**
162
+ * Cancel any pending reconnection attempt
163
+ */
164
+ cancelReconnect() {
165
+ if (this.reconnectTimeout) {
166
+ clearTimeout(this.reconnectTimeout);
167
+ this.reconnectTimeout = void 0;
168
+ }
169
+ this.isReconnecting = false;
170
+ }
171
+ /**
172
+ * Reset the reconnection state (call after successful connection)
173
+ */
174
+ reset() {
175
+ this.cancelReconnect();
176
+ this.currentDelay = this.initialDelay;
177
+ this.attempts = 0;
178
+ }
179
+ /**
180
+ * Check if currently in reconnection mode
181
+ */
182
+ isActive() {
183
+ return this.isReconnecting;
184
+ }
185
+ /**
186
+ * Get the current number of reconnection attempts
187
+ */
188
+ getAttempts() {
189
+ return this.attempts;
190
+ }
191
+ /**
192
+ * Get the current delay in milliseconds
193
+ */
194
+ getCurrentDelay() {
195
+ return this.currentDelay;
196
+ }
197
+ /**
198
+ * Check if max attempts have been reached
199
+ */
200
+ hasReachedMaxAttempts() {
201
+ return this.attempts >= this.maxAttempts;
202
+ }
203
+ };
204
+
205
+ // src/logger.ts
206
+ var config = {
207
+ level: 1 /* Error */,
208
+ prefix: "[RaisinDB]"
209
+ };
210
+ function setLogLevel(level) {
211
+ config.level = level;
212
+ }
213
+ function getLogLevel() {
214
+ return config.level;
215
+ }
216
+ var logger = {
217
+ /**
218
+ * Log debug message (only shown when level >= Debug)
219
+ */
220
+ debug(...args) {
221
+ if (config.level >= 4 /* Debug */) {
222
+ console.log(config.prefix, ...args);
223
+ }
224
+ },
225
+ /**
226
+ * Log info message (only shown when level >= Info)
227
+ */
228
+ info(...args) {
229
+ if (config.level >= 3 /* Info */) {
230
+ console.log(config.prefix, ...args);
231
+ }
232
+ },
233
+ /**
234
+ * Log warning message (only shown when level >= Warn)
235
+ */
236
+ warn(...args) {
237
+ if (config.level >= 2 /* Warn */) {
238
+ console.warn(config.prefix, ...args);
239
+ }
240
+ },
241
+ /**
242
+ * Log error message (only shown when level >= Error)
243
+ */
244
+ error(...args) {
245
+ if (config.level >= 1 /* Error */) {
246
+ console.error(config.prefix, ...args);
247
+ }
248
+ }
249
+ };
250
+ if (typeof globalThis !== "undefined") {
251
+ globalThis.__raisinDebug = (enable = true) => {
252
+ setLogLevel(enable ? 4 /* Debug */ : 1 /* Error */);
253
+ console.log(`[RaisinDB] Debug logging ${enable ? "ENABLED" : "DISABLED"} (includes server handler logs)`);
254
+ };
255
+ }
256
+
257
+ // src/integrations/react/use-connection.ts
258
+ function createUseConnection(react, context) {
259
+ return function useConnection() {
260
+ const { useState, useEffect, useCallback, useContext } = react;
261
+ const ctx = useContext(context);
262
+ if (!ctx) {
263
+ throw new Error("useConnection must be used within a <RaisinProvider>");
264
+ }
265
+ const { client } = ctx;
266
+ const [state, setState] = useState(client.getConnectionState());
267
+ const [isReady, setIsReady] = useState(client.isReady());
268
+ useEffect(() => {
269
+ const unsubConn = client.onConnectionStateChange((newState) => {
270
+ setState(newState);
271
+ });
272
+ const unsubReady = client.onReadyStateChange((ready) => {
273
+ setIsReady(ready);
274
+ });
275
+ return () => {
276
+ unsubConn();
277
+ unsubReady();
278
+ };
279
+ }, [client]);
280
+ const connect = useCallback(async () => {
281
+ await client.connect();
282
+ }, [client]);
283
+ const disconnect = useCallback(() => {
284
+ client.disconnect();
285
+ }, [client]);
286
+ return {
287
+ state,
288
+ isConnected: state === "connected" /* Connected */,
289
+ isReady,
290
+ connect,
291
+ disconnect
292
+ };
293
+ };
294
+ }
295
+
296
+ // src/integrations/react/use-sql.ts
297
+ function rowsToObjects(result) {
298
+ return result.rows;
299
+ }
300
+ function createUseSql(react, context) {
301
+ return function useSql(sql, params, options) {
302
+ const { useState, useEffect, useRef, useCallback, useContext } = react;
303
+ const ctx = useContext(context);
304
+ if (!ctx) {
305
+ throw new Error("useSql must be used within a <RaisinProvider>");
306
+ }
307
+ const { client, repository: defaultRepo } = ctx;
308
+ const [data, setData] = useState(null);
309
+ const [isLoading, setIsLoading] = useState(false);
310
+ const [error, setError] = useState(null);
311
+ const mountedRef = useRef(true);
312
+ const enabled = options?.enabled !== false;
313
+ const repo = options?.repository ?? defaultRepo;
314
+ const refetchOnReconnect = options?.refetchOnReconnect !== false;
315
+ const realtime = options?.realtime;
316
+ const paramsKey = params ? JSON.stringify(params) : "";
317
+ const fetchData = useCallback(async () => {
318
+ if (!repo) return;
319
+ setIsLoading(true);
320
+ setError(null);
321
+ try {
322
+ const db = client.database(repo);
323
+ const result = await db.executeSql(sql, params);
324
+ if (mountedRef.current) {
325
+ setData(rowsToObjects(result));
326
+ }
327
+ } catch (err) {
328
+ if (mountedRef.current) {
329
+ setError(err instanceof Error ? err : new Error(String(err)));
330
+ }
331
+ } finally {
332
+ if (mountedRef.current) {
333
+ setIsLoading(false);
334
+ }
335
+ }
336
+ }, [client, repo, sql, paramsKey]);
337
+ useEffect(() => {
338
+ mountedRef.current = true;
339
+ if (enabled) {
340
+ fetchData();
341
+ }
342
+ return () => {
343
+ mountedRef.current = false;
344
+ };
345
+ }, [enabled, fetchData]);
346
+ useEffect(() => {
347
+ if (!enabled || !refetchOnReconnect) return;
348
+ const unsub = client.onReconnected(() => {
349
+ fetchData();
350
+ });
351
+ return unsub;
352
+ }, [client, enabled, refetchOnReconnect, fetchData]);
353
+ useEffect(() => {
354
+ if (!enabled || !realtime || !repo) return;
355
+ const db = client.database(repo);
356
+ let unsubscribe;
357
+ db.events().subscribe(
358
+ {
359
+ workspace: realtime.workspace,
360
+ event_types: realtime.eventTypes,
361
+ path: realtime.path,
362
+ node_type: realtime.nodeType
363
+ },
364
+ () => {
365
+ fetchData();
366
+ }
367
+ ).then((sub) => {
368
+ unsubscribe = () => sub.unsubscribe();
369
+ });
370
+ return () => {
371
+ unsubscribe?.();
372
+ };
373
+ }, [client, enabled, repo, realtime?.workspace, realtime?.path, realtime?.nodeType, fetchData]);
374
+ return {
375
+ data,
376
+ isLoading,
377
+ error,
378
+ refetch: fetchData
379
+ };
380
+ };
381
+ }
382
+
383
+ // src/integrations/react/use-subscription.ts
384
+ function createUseSubscription(react, context) {
385
+ return function useSubscription(options, callback) {
386
+ const { useEffect, useRef, useContext } = react;
387
+ const ctx = useContext(context);
388
+ if (!ctx) {
389
+ throw new Error("useSubscription must be used within a <RaisinProvider>");
390
+ }
391
+ const { client, repository } = ctx;
392
+ const callbackRef = useRef(callback);
393
+ callbackRef.current = callback;
394
+ const enabled = options.enabled !== false;
395
+ useEffect(() => {
396
+ if (!enabled || !repository || !options.workspace) return;
397
+ const db = client.database(repository);
398
+ let unsubscribe;
399
+ let cancelled = false;
400
+ db.events().subscribe(
401
+ {
402
+ workspace: options.workspace,
403
+ event_types: options.event_types,
404
+ path: options.path,
405
+ node_type: options.node_type,
406
+ include_node: options.include_node
407
+ },
408
+ (event) => {
409
+ if (!cancelled) {
410
+ callbackRef.current(event);
411
+ }
412
+ }
413
+ ).then((sub) => {
414
+ if (cancelled) {
415
+ sub.unsubscribe();
416
+ } else {
417
+ unsubscribe = () => sub.unsubscribe();
418
+ }
419
+ });
420
+ return () => {
421
+ cancelled = true;
422
+ unsubscribe?.();
423
+ };
424
+ }, [client, repository, enabled, options.workspace, options.path, options.node_type, options.include_node]);
425
+ };
426
+ }
427
+
428
+ // src/utils/plan-projection.ts
429
+ function asRecord(value) {
430
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
431
+ return value;
432
+ }
433
+ function asString(value) {
434
+ return typeof value === "string" && value.length > 0 ? value : void 0;
435
+ }
436
+ function parsePlanTasks(rawTasks) {
437
+ if (!Array.isArray(rawTasks)) return [];
438
+ return rawTasks.map((rawTask, index) => {
439
+ if (typeof rawTask === "string") {
440
+ return {
441
+ title: rawTask,
442
+ status: "pending"
443
+ };
444
+ }
445
+ const task = asRecord(rawTask);
446
+ if (!task) return null;
447
+ return {
448
+ taskId: asString(task.task_id) ?? asString(task.id),
449
+ title: asString(task.title) ?? `Task ${index + 1}`,
450
+ status: asString(task.status) ?? "pending",
451
+ description: asString(task.description),
452
+ priority: asString(task.priority)
453
+ };
454
+ }).filter((task) => task !== null);
455
+ }
456
+ var TERMINAL_TASK_STATUSES = /* @__PURE__ */ new Set(["completed", "cancelled"]);
457
+ var TERMINAL_PLAN_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
458
+ function setPlanStatus(plan, nextStatus) {
459
+ if (!nextStatus) return;
460
+ if (TERMINAL_PLAN_STATUSES.has(plan.status) && !TERMINAL_PLAN_STATUSES.has(nextStatus)) {
461
+ return;
462
+ }
463
+ plan.status = nextStatus;
464
+ }
465
+ function upsertTask(plan, nextTask) {
466
+ const existingIndex = plan.tasks.findIndex(
467
+ (task) => nextTask.taskId && task.taskId === nextTask.taskId || !nextTask.taskId && task.title === nextTask.title
468
+ );
469
+ if (existingIndex === -1) {
470
+ plan.tasks.push(nextTask);
471
+ return;
472
+ }
473
+ const existing = plan.tasks[existingIndex];
474
+ if (TERMINAL_TASK_STATUSES.has(existing.status) && !TERMINAL_TASK_STATUSES.has(nextTask.status)) {
475
+ return;
476
+ }
477
+ plan.tasks[existingIndex] = {
478
+ ...existing,
479
+ ...nextTask
480
+ };
481
+ }
482
+ function ensurePlan(plans, key, fallbackTitle, timestamp) {
483
+ const existing = plans.get(key);
484
+ if (existing) {
485
+ if (timestamp) existing.updatedAt = timestamp;
486
+ return existing;
487
+ }
488
+ const created = {
489
+ key,
490
+ title: fallbackTitle,
491
+ status: "pending_approval",
492
+ requiresApproval: true,
493
+ tasks: [],
494
+ updatedAt: timestamp
495
+ };
496
+ plans.set(key, created);
497
+ return created;
498
+ }
499
+ function projectPlansFromMessages(messages) {
500
+ const ordered = [...messages].sort((a, b) => {
501
+ const aTime = Date.parse(a.timestamp || "");
502
+ const bTime = Date.parse(b.timestamp || "");
503
+ return (Number.isNaN(aTime) ? 0 : aTime) - (Number.isNaN(bTime) ? 0 : bTime);
504
+ });
505
+ const plans = /* @__PURE__ */ new Map();
506
+ for (const message of ordered) {
507
+ const timestamp = message.timestamp;
508
+ const data = asRecord(message.data);
509
+ if (message.messageType === "ai_plan" && data) {
510
+ const planPath = asString(data.plan_path);
511
+ const planId = asString(data.plan_id);
512
+ const key = planPath || planId || message.path || message.id || `plan:${timestamp}`;
513
+ const plan = ensurePlan(
514
+ plans,
515
+ key,
516
+ asString(data.title) || message.content || "Plan",
517
+ timestamp
518
+ );
519
+ plan.planPath = planPath ?? plan.planPath;
520
+ plan.planId = planId ?? plan.planId;
521
+ plan.title = asString(data.title) || plan.title;
522
+ setPlanStatus(plan, asString(data.status));
523
+ plan.requiresApproval = Boolean(data.requires_approval) || plan.status === "pending_approval";
524
+ plan.sourceMessagePath = message.path ?? plan.sourceMessagePath;
525
+ const parsedTasks = parsePlanTasks(data.tasks);
526
+ if (parsedTasks.length > 0) {
527
+ plan.tasks = parsedTasks;
528
+ }
529
+ }
530
+ if (message.messageType === "ai_task_update" && data) {
531
+ const planPath = asString(data.plan_path);
532
+ const planId = asString(data.plan_id);
533
+ const key = planPath || planId;
534
+ if (!key) continue;
535
+ const plan = ensurePlan(plans, key, "Plan", timestamp);
536
+ plan.planPath = planPath ?? plan.planPath;
537
+ plan.planId = planId ?? plan.planId;
538
+ setPlanStatus(plan, asString(data.plan_status));
539
+ plan.requiresApproval = plan.status === "pending_approval";
540
+ const taskUpdate = {
541
+ taskId: asString(data.task_id),
542
+ title: asString(data.task_title) || asString(data.title) || "Task",
543
+ status: asString(data.status) || "pending"
544
+ };
545
+ upsertTask(plan, taskUpdate);
546
+ }
547
+ if (Array.isArray(message.children)) {
548
+ for (const child of message.children) {
549
+ if (child.type !== "plan") continue;
550
+ const key = child.path || message.path || message.id || `plan-child:${child.id}:${timestamp}`;
551
+ const plan = ensurePlan(plans, key, child.planTitle || message.content || "Plan", timestamp);
552
+ plan.title = child.planTitle || plan.title;
553
+ plan.status = child.status || plan.status;
554
+ plan.requiresApproval = plan.status === "pending_approval";
555
+ if (Array.isArray(child.tasks) && child.tasks.length > 0) {
556
+ plan.tasks = child.tasks.map((task) => ({
557
+ taskId: task.id,
558
+ title: task.title,
559
+ status: task.status
560
+ }));
561
+ }
562
+ }
563
+ }
564
+ }
565
+ for (const plan of plans.values()) {
566
+ if (!TERMINAL_PLAN_STATUSES.has(plan.status) && plan.tasks.length > 0 && plan.tasks.every((task) => TERMINAL_TASK_STATUSES.has(task.status))) {
567
+ plan.status = "completed";
568
+ plan.requiresApproval = false;
569
+ }
570
+ }
571
+ return [...plans.values()].sort((a, b) => {
572
+ const aTime = Date.parse(a.updatedAt || "");
573
+ const bTime = Date.parse(b.updatedAt || "");
574
+ return (Number.isNaN(bTime) ? 0 : bTime) - (Number.isNaN(aTime) ? 0 : aTime);
575
+ });
576
+ }
577
+
578
+ // src/utils/chat-events.ts
579
+ function isRecoveredDoneEvent(event) {
580
+ if (event.type !== "done") return false;
581
+ const done = event;
582
+ if (done.recovered !== true) return false;
583
+ return typeof done.content !== "string" || done.content.trim().length === 0;
584
+ }
585
+
586
+ // src/stores/conversation-store.ts
587
+ var ConversationStore = class {
588
+ constructor(options) {
589
+ this.subscribers = /* @__PURE__ */ new Set();
590
+ // Persistent SSE subscription
591
+ this.subscription = null;
592
+ this._messages = [];
593
+ this._isStreaming = false;
594
+ this._isWaiting = false;
595
+ this._streamingText = "";
596
+ this._error = null;
597
+ this._activeToolCalls = [];
598
+ this._isLoading = false;
599
+ this._conversationType = null;
600
+ this._streamingTimer = null;
601
+ this._watchdogTimer = null;
602
+ this.manager = options.database.conversations;
603
+ this._conversationPath = options.conversationPath ?? null;
604
+ this.createOptions = options.createOptions;
605
+ this.onEvent = options.onEvent;
606
+ this._streamingTimeoutMs = options.streamingTimeoutMs ?? 12e4;
607
+ this._watchdogIntervalMs = options.watchdogIntervalMs ?? 3e4;
608
+ if (this._conversationPath) {
609
+ this.ensureSubscription();
610
+ }
611
+ }
612
+ // ==========================================================================
613
+ // Subscription
614
+ // ==========================================================================
615
+ /**
616
+ * Subscribe to state changes.
617
+ * Returns an unsubscribe function.
618
+ */
619
+ subscribe(callback) {
620
+ this.subscribers.add(callback);
621
+ callback(this.getSnapshot());
622
+ return () => {
623
+ this.subscribers.delete(callback);
624
+ };
625
+ }
626
+ /**
627
+ * Get the current state snapshot.
628
+ */
629
+ getSnapshot() {
630
+ return {
631
+ conversation: this._conversationPath ? { conversationPath: this._conversationPath, type: this._conversationType || "ai_chat" } : null,
632
+ messages: [...this._messages],
633
+ isStreaming: this._isStreaming,
634
+ isWaiting: this._isWaiting,
635
+ streamingText: this._streamingText,
636
+ error: this._error,
637
+ activeToolCalls: [...this._activeToolCalls],
638
+ plans: projectPlansFromMessages(this._messages),
639
+ isLoading: this._isLoading,
640
+ conversationPath: this._conversationPath
641
+ };
642
+ }
643
+ // ==========================================================================
644
+ // Actions
645
+ // ==========================================================================
646
+ /**
647
+ * Send a user message and stream the AI response.
648
+ *
649
+ * If no conversation exists yet and `createOptions` was provided,
650
+ * the conversation is created automatically on the first call.
651
+ */
652
+ async sendMessage(content) {
653
+ if (this._isStreaming) {
654
+ logger.warn("[ConversationStore] Cannot send message while streaming");
655
+ return;
656
+ }
657
+ logger.info("[ConversationStore] Sending message", { path: this._conversationPath });
658
+ this._error = null;
659
+ if (!this._conversationPath) {
660
+ if (!this.createOptions) {
661
+ throw new Error("No conversationPath and no createOptions provided");
662
+ }
663
+ try {
664
+ const convo = await this.manager.create({
665
+ participant: this.createOptions.participant,
666
+ input: this.createOptions.input
667
+ });
668
+ this._conversationPath = convo.conversationPath;
669
+ this._conversationType = convo.type;
670
+ for (const event of convo.initialEvents ?? []) {
671
+ this.onEvent?.(event);
672
+ this.handleEvent(event);
673
+ }
674
+ this.notify();
675
+ } catch (err) {
676
+ this._error = err instanceof Error ? err.message : String(err);
677
+ this.notify();
678
+ return;
679
+ }
680
+ }
681
+ const userMessage = {
682
+ role: "user",
683
+ content,
684
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
685
+ };
686
+ this._messages.push(userMessage);
687
+ this._isStreaming = true;
688
+ this._isWaiting = false;
689
+ this._streamingText = "";
690
+ this._activeToolCalls = [];
691
+ this.resetStreamingTimer();
692
+ this.startWatchdog();
693
+ this.notify();
694
+ try {
695
+ this.ensureSubscription();
696
+ await this.subscription.waitUntilConnected();
697
+ await this.manager.createUserMessage(this._conversationPath, content);
698
+ } catch (err) {
699
+ logger.error("[ConversationStore] Send failed", err);
700
+ this._error = err instanceof Error ? err.message : String(err);
701
+ this._isStreaming = false;
702
+ this.clearStreamingTimer();
703
+ this.stopWatchdog();
704
+ this.notify();
705
+ }
706
+ }
707
+ /**
708
+ * Load messages from the persisted node tree.
709
+ * Useful for loading history on page reload.
710
+ */
711
+ async loadMessages() {
712
+ if (!this._conversationPath) return [];
713
+ this._isLoading = true;
714
+ this.notify();
715
+ try {
716
+ const messages = await this.manager.getMessages(this._conversationPath);
717
+ logger.debug(`[ConversationStore] Loaded ${messages.length} messages`);
718
+ if (messages.length > 0) {
719
+ this._messages = messages;
720
+ this._activeToolCalls = [];
721
+ }
722
+ return messages;
723
+ } finally {
724
+ this._isLoading = false;
725
+ this.notify();
726
+ }
727
+ }
728
+ /**
729
+ * Approve a pending plan.
730
+ */
731
+ async approvePlan(planPath) {
732
+ await this.manager.approvePlan(planPath);
733
+ }
734
+ /**
735
+ * Reject a pending plan.
736
+ */
737
+ async rejectPlan(planPath, feedback) {
738
+ await this.manager.rejectPlan(planPath, feedback);
739
+ }
740
+ /**
741
+ * Mark a single message as read.
742
+ */
743
+ async markMessageAsRead(messagePath) {
744
+ await this.manager.markMessageAsRead(messagePath);
745
+ }
746
+ /**
747
+ * Stop the current streaming response.
748
+ */
749
+ stop() {
750
+ this._isStreaming = false;
751
+ this.clearStreamingTimer();
752
+ this.stopWatchdog();
753
+ this.notify();
754
+ }
755
+ /**
756
+ * Clean up the store and release resources.
757
+ */
758
+ destroy() {
759
+ this.stop();
760
+ this.clearStreamingTimer();
761
+ this.stopWatchdog();
762
+ this.subscription?.unsubscribe();
763
+ this.subscription = null;
764
+ this.subscribers.clear();
765
+ }
766
+ /**
767
+ * Get the conversation path.
768
+ */
769
+ getConversationPath() {
770
+ return this._conversationPath;
771
+ }
772
+ // ==========================================================================
773
+ // Internal
774
+ // ==========================================================================
775
+ ensureSubscription() {
776
+ if (this.subscription) return;
777
+ if (!this._conversationPath) return;
778
+ this.subscription = this.manager.subscribe(
779
+ this._conversationPath,
780
+ (event) => {
781
+ this.onEvent?.(event);
782
+ this.handleEvent(event);
783
+ }
784
+ );
785
+ }
786
+ handleEvent(event) {
787
+ logger.debug("[ConversationStore] SSE:", event.type);
788
+ if (this._isStreaming) {
789
+ this.resetStreamingTimer();
790
+ }
791
+ switch (event.type) {
792
+ case "text_chunk":
793
+ this.markStreamingActivity();
794
+ this._streamingText += event.text;
795
+ this.notify();
796
+ break;
797
+ case "thought_chunk":
798
+ this.markStreamingActivity();
799
+ this.notify();
800
+ break;
801
+ case "assistant_message":
802
+ this._messages.push(event.message);
803
+ this._streamingText = "";
804
+ this.notify();
805
+ break;
806
+ case "tool_call_started": {
807
+ this.markStreamingActivity();
808
+ logger.debug("[ConversationStore] Tool started:", event.functionName);
809
+ const info = {
810
+ id: event.toolCallId,
811
+ functionName: event.functionName,
812
+ arguments: event.arguments,
813
+ status: "running"
814
+ };
815
+ this._activeToolCalls.push(info);
816
+ this.notify();
817
+ break;
818
+ }
819
+ case "tool_call_completed": {
820
+ this.markStreamingActivity();
821
+ logger.debug("[ConversationStore] Tool completed:", event.toolCallId);
822
+ const idx = this._activeToolCalls.findIndex((tc) => tc.id === event.toolCallId);
823
+ if (idx >= 0) {
824
+ this._activeToolCalls[idx] = {
825
+ ...this._activeToolCalls[idx],
826
+ status: event.error ? "failed" : "completed",
827
+ result: event.result,
828
+ durationMs: event.durationMs
829
+ };
830
+ }
831
+ this.notify();
832
+ break;
833
+ }
834
+ case "waiting": {
835
+ logger.info("[ConversationStore] Waiting for input");
836
+ this.flushStreamingText(event.timestamp);
837
+ this._isStreaming = false;
838
+ this._isWaiting = true;
839
+ this._activeToolCalls = [];
840
+ this.clearStreamingTimer();
841
+ this.stopWatchdog();
842
+ this.notify();
843
+ this.deferredReload();
844
+ break;
845
+ }
846
+ case "done": {
847
+ if (isRecoveredDoneEvent(event)) {
848
+ logger.debug("[ConversationStore] Ignoring recovered done event");
849
+ this.reconcileRecoveredDone();
850
+ break;
851
+ }
852
+ const doneEvent = event;
853
+ if (doneEvent.dispatchPhase && doneEvent.dispatchPhase !== "terminal") {
854
+ logger.debug("[ConversationStore] Ignoring non-terminal done event");
855
+ break;
856
+ }
857
+ logger.info("[ConversationStore] Turn done");
858
+ this.flushStreamingText(event.timestamp);
859
+ if (doneEvent.content && !this.lastMessageIsAssistant()) {
860
+ this._messages.push({
861
+ role: doneEvent.role || "assistant",
862
+ content: doneEvent.content,
863
+ timestamp: event.timestamp,
864
+ senderDisplayName: doneEvent.senderDisplayName,
865
+ finishReason: doneEvent.finishReason
866
+ });
867
+ }
868
+ this._isStreaming = false;
869
+ this._isWaiting = true;
870
+ this._activeToolCalls = [];
871
+ this.clearStreamingTimer();
872
+ this.stopWatchdog();
873
+ this.notify();
874
+ this.deferredReload();
875
+ break;
876
+ }
877
+ case "completed": {
878
+ this.flushStreamingText(event.timestamp);
879
+ if (event.messages && event.messages.length > 0) {
880
+ this._messages = event.messages;
881
+ }
882
+ this._isStreaming = false;
883
+ this._isWaiting = false;
884
+ this._activeToolCalls = [];
885
+ this.clearStreamingTimer();
886
+ this.stopWatchdog();
887
+ this.notify();
888
+ this.deferredReload();
889
+ break;
890
+ }
891
+ case "failed":
892
+ logger.error("[ConversationStore] Turn failed", event.error);
893
+ this._error = event.error;
894
+ this._isStreaming = false;
895
+ this._isWaiting = false;
896
+ this._streamingText = "";
897
+ this._activeToolCalls = [];
898
+ this.clearStreamingTimer();
899
+ this.stopWatchdog();
900
+ this.notify();
901
+ break;
902
+ case "conversation_created":
903
+ this._conversationPath = event.conversationPath;
904
+ this.notify();
905
+ break;
906
+ case "message_saved":
907
+ this.silentReload().catch(() => {
908
+ });
909
+ this.notify();
910
+ break;
911
+ case "message_delivered":
912
+ this._messages.push(event.message);
913
+ this.notify();
914
+ break;
915
+ case "log": {
916
+ const logEvent = event;
917
+ const currentLevel = getLogLevel();
918
+ const levelMap = {
919
+ debug: 4 /* Debug */,
920
+ info: 3 /* Info */,
921
+ warn: 2 /* Warn */,
922
+ error: 1 /* Error */
923
+ };
924
+ const eventLevel = levelMap[logEvent.level] ?? 4 /* Debug */;
925
+ if (currentLevel >= eventLevel) {
926
+ const fn = logEvent.level === "error" ? console.error : logEvent.level === "warn" ? console.warn : logEvent.level === "debug" ? console.debug : console.info;
927
+ fn("[server]", logEvent.message);
928
+ }
929
+ break;
930
+ }
931
+ }
932
+ }
933
+ /**
934
+ * Agent activity observed while the store thought the turn was over.
935
+ *
936
+ * This happens when execution continues WITHOUT a user message — plan
937
+ * approval in approve_then_auto / step_by_step (approvePlan() returns an
938
+ * enqueue receipt and the agent starts executing), or agent-initiated
939
+ * follow-ups. The events arrive over the persistent live subscription
940
+ * (no history replay), so activity is always "now": re-enter streaming
941
+ * state so UIs show progress and the end-of-turn handling (done/waiting
942
+ * → deferred reload) runs again for this continuation.
943
+ */
944
+ markStreamingActivity() {
945
+ if (this._isStreaming) return;
946
+ logger.debug("[ConversationStore] Agent activity while idle \u2014 re-entering streaming state");
947
+ this._isStreaming = true;
948
+ this._isWaiting = false;
949
+ this._streamingText = "";
950
+ this.resetStreamingTimer();
951
+ this.startWatchdog();
952
+ }
953
+ /**
954
+ * If accumulated streaming text hasn't been captured in an assistant_message,
955
+ * synthesize one.
956
+ */
957
+ flushStreamingText(timestamp) {
958
+ if (this._streamingText && !this.lastMessageIsAssistant()) {
959
+ this._messages.push({
960
+ role: "assistant",
961
+ content: this._streamingText,
962
+ timestamp
963
+ });
964
+ }
965
+ this._streamingText = "";
966
+ }
967
+ lastMessageIsAssistant() {
968
+ const last = this._messages[this._messages.length - 1];
969
+ return last?.role === "assistant";
970
+ }
971
+ /**
972
+ * After a turn completes, reload canonical messages from the node tree
973
+ * to catch any events missed during SSE gaps.
974
+ */
975
+ deferredReload() {
976
+ if (!this._conversationPath) return;
977
+ logger.debug("[ConversationStore] Scheduling deferred reload");
978
+ const attemptReload = (delay, retriesLeft) => {
979
+ setTimeout(async () => {
980
+ try {
981
+ const prevCount = this._messages.length;
982
+ await this.silentReload();
983
+ if (this._messages.length === prevCount && retriesLeft > 0) {
984
+ attemptReload(delay * 2, retriesLeft - 1);
985
+ }
986
+ } catch {
987
+ }
988
+ }, delay);
989
+ };
990
+ attemptReload(500, 2);
991
+ }
992
+ async silentReload() {
993
+ if (!this._conversationPath) return;
994
+ try {
995
+ const fresh = await this.manager.getMessages(this._conversationPath);
996
+ if (fresh.length === 0) return;
997
+ let matchCount = 0;
998
+ const limit = Math.min(this._messages.length, fresh.length);
999
+ for (let i = 0; i < limit; i++) {
1000
+ if (this._messages[i].role !== fresh[i].role || this._messages[i].content !== fresh[i].content) break;
1001
+ matchCount++;
1002
+ }
1003
+ if (matchCount === this._messages.length && fresh.length === matchCount) {
1004
+ for (let i = 0; i < matchCount; i++) {
1005
+ const f = fresh[i];
1006
+ const e = this._messages[i];
1007
+ if (f.id) e.id = f.id;
1008
+ if (f.path) e.path = f.path;
1009
+ if (f.messageType) e.messageType = f.messageType;
1010
+ if (f.data) e.data = f.data;
1011
+ if (f.children) e.children = f.children;
1012
+ if (f.finishReason) e.finishReason = f.finishReason;
1013
+ }
1014
+ await this.rebuildToolCallState();
1015
+ return;
1016
+ }
1017
+ if (matchCount === this._messages.length && fresh.length > matchCount) {
1018
+ for (let i = matchCount; i < fresh.length; i++) {
1019
+ this._messages.push(fresh[i]);
1020
+ }
1021
+ for (let i = 0; i < matchCount; i++) {
1022
+ const f = fresh[i];
1023
+ const e = this._messages[i];
1024
+ if (f.id) e.id = f.id;
1025
+ if (f.path) e.path = f.path;
1026
+ if (f.messageType) e.messageType = f.messageType;
1027
+ if (f.data) e.data = f.data;
1028
+ if (f.children) e.children = f.children;
1029
+ }
1030
+ await this.rebuildToolCallState();
1031
+ this.notify();
1032
+ return;
1033
+ }
1034
+ if (matchCount === fresh.length && fresh.length < this._messages.length) {
1035
+ for (let i = 0; i < matchCount; i++) {
1036
+ const f = fresh[i];
1037
+ const e = this._messages[i];
1038
+ if (f.id) e.id = f.id;
1039
+ if (f.path) e.path = f.path;
1040
+ if (f.messageType) e.messageType = f.messageType;
1041
+ if (f.data) e.data = f.data;
1042
+ if (f.children) e.children = f.children;
1043
+ }
1044
+ await this.rebuildToolCallState();
1045
+ return;
1046
+ }
1047
+ this._messages = fresh;
1048
+ await this.rebuildToolCallState();
1049
+ this.notify();
1050
+ } catch (err) {
1051
+ logger.debug("[ConversationStore] Silent reload failed:", err);
1052
+ }
1053
+ }
1054
+ // ==========================================================================
1055
+ // Streaming timeout (Fix A) — auto-recover on SSE inactivity
1056
+ // ==========================================================================
1057
+ resetStreamingTimer() {
1058
+ this.clearStreamingTimer();
1059
+ if (!this._isStreaming) return;
1060
+ this._streamingTimer = setTimeout(() => {
1061
+ if (this._isStreaming) {
1062
+ logger.warn("[ConversationStore] Streaming timeout \u2014 no SSE activity for", this._streamingTimeoutMs, "ms");
1063
+ this.recoverFromHang();
1064
+ }
1065
+ }, this._streamingTimeoutMs);
1066
+ }
1067
+ clearStreamingTimer() {
1068
+ if (this._streamingTimer) {
1069
+ clearTimeout(this._streamingTimer);
1070
+ this._streamingTimer = null;
1071
+ }
1072
+ }
1073
+ // ==========================================================================
1074
+ // Activity watchdog (Fix B) — periodic backend health check
1075
+ // ==========================================================================
1076
+ startWatchdog() {
1077
+ this.stopWatchdog();
1078
+ if (!this._conversationPath) return;
1079
+ this._watchdogTimer = setInterval(async () => {
1080
+ if (!this._isStreaming || !this._conversationPath) {
1081
+ this.stopWatchdog();
1082
+ return;
1083
+ }
1084
+ try {
1085
+ const health = await this.manager.checkTurnHealth(this._conversationPath);
1086
+ if (health === "done" && this._isStreaming) {
1087
+ logger.warn("[ConversationStore] Watchdog detected completed turn while still streaming \u2014 recovering");
1088
+ this.recoverFromHang();
1089
+ }
1090
+ } catch {
1091
+ }
1092
+ }, this._watchdogIntervalMs);
1093
+ }
1094
+ stopWatchdog() {
1095
+ if (this._watchdogTimer) {
1096
+ clearInterval(this._watchdogTimer);
1097
+ this._watchdogTimer = null;
1098
+ }
1099
+ }
1100
+ // ==========================================================================
1101
+ // Hang recovery (shared by timeout + watchdog)
1102
+ // ==========================================================================
1103
+ recoverFromHang() {
1104
+ logger.info("[ConversationStore] Recovering from hang");
1105
+ this.clearStreamingTimer();
1106
+ this.stopWatchdog();
1107
+ this._isStreaming = false;
1108
+ this._isWaiting = true;
1109
+ this._streamingText = "";
1110
+ this.notify();
1111
+ this.silentReload().catch(() => {
1112
+ });
1113
+ }
1114
+ /**
1115
+ * Reconcile a recovered done event against persisted state.
1116
+ * If the backend turn is actually complete, finalize the local state.
1117
+ * Otherwise keep streaming active and let normal events continue.
1118
+ */
1119
+ reconcileRecoveredDone() {
1120
+ if (!this._conversationPath) return;
1121
+ void this.manager.checkTurnHealth(this._conversationPath).then((health) => {
1122
+ if (health !== "done") return;
1123
+ if (!this._isStreaming) return;
1124
+ this._isStreaming = false;
1125
+ this._isWaiting = true;
1126
+ this._activeToolCalls = [];
1127
+ this.clearStreamingTimer();
1128
+ this.stopWatchdog();
1129
+ this.notify();
1130
+ this.deferredReload();
1131
+ }).catch(() => {
1132
+ });
1133
+ }
1134
+ // ==========================================================================
1135
+ // Tool call state rebuild (Fix C) — reconstruct from node tree on reload
1136
+ // ==========================================================================
1137
+ async rebuildToolCallState() {
1138
+ if (!this._conversationPath) {
1139
+ this._activeToolCalls = [];
1140
+ return;
1141
+ }
1142
+ try {
1143
+ const pendingCalls = await this.manager.getActiveToolCalls(this._conversationPath);
1144
+ if (pendingCalls.length > 0) {
1145
+ this._activeToolCalls = pendingCalls.map((tc) => ({
1146
+ id: tc.id,
1147
+ functionName: tc.name,
1148
+ arguments: void 0,
1149
+ status: "running"
1150
+ }));
1151
+ if (!this._isStreaming) {
1152
+ this._isStreaming = true;
1153
+ this.resetStreamingTimer();
1154
+ this.startWatchdog();
1155
+ }
1156
+ } else {
1157
+ this._activeToolCalls = [];
1158
+ if (this._isStreaming) {
1159
+ const lastMsg = this._messages[this._messages.length - 1];
1160
+ const isLastAssistantDone = lastMsg?.role === "assistant" && (lastMsg.dispatchPhase ? lastMsg.dispatchPhase === "terminal" : !!lastMsg.finishReason && lastMsg.finishReason !== "tool_calls");
1161
+ if (isLastAssistantDone) {
1162
+ this._isStreaming = false;
1163
+ this._isWaiting = true;
1164
+ this.clearStreamingTimer();
1165
+ this.stopWatchdog();
1166
+ }
1167
+ }
1168
+ }
1169
+ } catch {
1170
+ this._activeToolCalls = [];
1171
+ }
1172
+ }
1173
+ notify() {
1174
+ const snapshot = this.getSnapshot();
1175
+ for (const sub of this.subscribers) {
1176
+ try {
1177
+ sub(snapshot);
1178
+ } catch (err) {
1179
+ logger.error("Error in conversation store subscriber:", err);
1180
+ }
1181
+ }
1182
+ }
1183
+ };
1184
+
1185
+ // src/utils/home-path.ts
1186
+ var ACCESS_CONTROL_PREFIX = "/raisin:access_control";
1187
+ function normalizeHomePath(home) {
1188
+ if (home === null || home === void 0) return null;
1189
+ let path = home.trim();
1190
+ if (path.length === 0) return null;
1191
+ if (path === ACCESS_CONTROL_PREFIX) return "/";
1192
+ if (path.startsWith(`${ACCESS_CONTROL_PREFIX}/`)) {
1193
+ path = path.slice(ACCESS_CONTROL_PREFIX.length);
1194
+ }
1195
+ while (path.length > 1 && path.endsWith("/")) {
1196
+ path = path.slice(0, -1);
1197
+ }
1198
+ return path;
1199
+ }
1200
+
1201
+ // src/stores/conversation-list-store.ts
1202
+ function buildChatsSubscriptionFilters(userHome) {
1203
+ const home = normalizeHomePath(userHome) ?? userHome;
1204
+ return {
1205
+ workspace: "raisin:access_control",
1206
+ path: `${home}/inbox/chats/**`,
1207
+ event_types: ["node:created", "node:updated"]
1208
+ };
1209
+ }
1210
+ var ConversationListStore = class {
1211
+ constructor(options) {
1212
+ this.subscribers = /* @__PURE__ */ new Set();
1213
+ // Internal state
1214
+ this._conversations = [];
1215
+ this._isLoading = false;
1216
+ this._error = null;
1217
+ // Cached ConversationStore instances
1218
+ this._stores = /* @__PURE__ */ new Map();
1219
+ // Real-time subscription
1220
+ this._realtimeSubscription = null;
1221
+ this.database = options.database;
1222
+ this.type = options.type;
1223
+ this.realtime = options.realtime ?? false;
1224
+ }
1225
+ // ==========================================================================
1226
+ // Subscription
1227
+ // ==========================================================================
1228
+ subscribe(callback) {
1229
+ this.subscribers.add(callback);
1230
+ callback(this.getSnapshot());
1231
+ return () => {
1232
+ this.subscribers.delete(callback);
1233
+ };
1234
+ }
1235
+ getSnapshot() {
1236
+ return {
1237
+ conversations: [...this._conversations],
1238
+ totalUnreadCount: this._conversations.reduce((sum, c) => sum + (c.unreadCount ?? 0), 0),
1239
+ isLoading: this._isLoading,
1240
+ error: this._error
1241
+ };
1242
+ }
1243
+ // ==========================================================================
1244
+ // Actions
1245
+ // ==========================================================================
1246
+ /**
1247
+ * Load conversations from the server.
1248
+ */
1249
+ async load() {
1250
+ this._isLoading = true;
1251
+ this._error = null;
1252
+ this.notify();
1253
+ try {
1254
+ const conversations = await this.database.conversations.list({
1255
+ type: this.type
1256
+ });
1257
+ logger.debug(`[ConversationListStore] Loaded ${conversations.length} conversations`);
1258
+ this._conversations = conversations;
1259
+ if (this.realtime) {
1260
+ this.startRealtimeSubscription();
1261
+ }
1262
+ } catch (err) {
1263
+ logger.error("[ConversationListStore] Failed to load conversations", err);
1264
+ this._error = err instanceof Error ? err.message : String(err);
1265
+ } finally {
1266
+ this._isLoading = false;
1267
+ this.notify();
1268
+ }
1269
+ }
1270
+ /**
1271
+ * Create a new conversation.
1272
+ */
1273
+ async createConversation(options) {
1274
+ const convo = await this.database.conversations.create(options);
1275
+ const listItem = {
1276
+ id: convo.id,
1277
+ type: convo.type,
1278
+ conversationPath: convo.conversationPath,
1279
+ conversationWorkspace: convo.conversationWorkspace,
1280
+ agentRef: convo.agentRef,
1281
+ participants: convo.participants,
1282
+ unreadCount: 0,
1283
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1284
+ };
1285
+ this._conversations = [listItem, ...this._conversations];
1286
+ this.notify();
1287
+ return listItem;
1288
+ }
1289
+ /**
1290
+ * Delete a conversation.
1291
+ */
1292
+ async deleteConversation(conversationPath) {
1293
+ const store = this._stores.get(conversationPath);
1294
+ if (store) {
1295
+ store.destroy();
1296
+ this._stores.delete(conversationPath);
1297
+ }
1298
+ await this.database.conversations.delete(conversationPath);
1299
+ this._conversations = this._conversations.filter((c) => c.conversationPath !== conversationPath);
1300
+ this.notify();
1301
+ }
1302
+ /**
1303
+ * Mark a conversation as read.
1304
+ */
1305
+ async markAsRead(conversationPath) {
1306
+ await this.database.conversations.markAsRead(conversationPath);
1307
+ this._conversations = this._conversations.map(
1308
+ (c) => c.conversationPath === conversationPath ? { ...c, unreadCount: 0 } : c
1309
+ );
1310
+ this.notify();
1311
+ }
1312
+ /**
1313
+ * Get or create a ConversationStore for a specific conversation.
1314
+ * Caches instances so repeated calls return the same store.
1315
+ */
1316
+ getConversationStore(conversationPath, overrides) {
1317
+ let store = this._stores.get(conversationPath);
1318
+ if (!store) {
1319
+ store = new ConversationStore({
1320
+ database: this.database,
1321
+ conversationPath,
1322
+ ...overrides
1323
+ });
1324
+ this._stores.set(conversationPath, store);
1325
+ }
1326
+ return store;
1327
+ }
1328
+ /**
1329
+ * Clean up all resources.
1330
+ */
1331
+ destroy() {
1332
+ this._realtimeSubscription?.unsubscribe();
1333
+ this._realtimeSubscription = null;
1334
+ for (const store of this._stores.values()) {
1335
+ store.destroy();
1336
+ }
1337
+ this._stores.clear();
1338
+ this.subscribers.clear();
1339
+ }
1340
+ // ==========================================================================
1341
+ // Internal
1342
+ // ==========================================================================
1343
+ async startRealtimeSubscription() {
1344
+ if (this._realtimeSubscription) return;
1345
+ logger.debug("[ConversationListStore] Starting realtime subscription");
1346
+ try {
1347
+ const workspace = this.database.workspace("raisin:access_control");
1348
+ const events = workspace.events();
1349
+ const result = await this.database.executeSql(
1350
+ `SELECT RAISIN_CURRENT_USER()->>'path'::String as home`
1351
+ );
1352
+ const rows = result.rows;
1353
+ const userHome = rows?.[0]?.home;
1354
+ if (!userHome) return;
1355
+ this._realtimeSubscription = await events.subscribe(
1356
+ buildChatsSubscriptionFilters(userHome),
1357
+ async (event) => {
1358
+ const eventData = event;
1359
+ const nodeId = eventData.payload?.node_id;
1360
+ if (!nodeId) return;
1361
+ try {
1362
+ const nodeResult = await this.database.executeSql(
1363
+ `SELECT id, path, node_type, properties, created_at, updated_at FROM 'raisin:access_control' WHERE id = $1 LIMIT 1`,
1364
+ [nodeId]
1365
+ );
1366
+ const row = nodeResult.rows?.[0];
1367
+ if (!row || row.node_type !== "raisin:Conversation") return;
1368
+ const convPath = row.path;
1369
+ const props = row.properties ?? {};
1370
+ const item = {
1371
+ id: row.id,
1372
+ type: props.conversation_type ?? "ai_chat",
1373
+ conversationPath: convPath,
1374
+ conversationWorkspace: "raisin:access_control",
1375
+ agentRef: props.agent_ref,
1376
+ participants: props.participants,
1377
+ unreadCount: props.unread_count ?? 0,
1378
+ lastMessage: props.last_message,
1379
+ updatedAt: row.updated_at ?? row.created_at
1380
+ };
1381
+ const existingIdx = this._conversations.findIndex((c) => c.conversationPath === convPath);
1382
+ if (existingIdx >= 0) {
1383
+ this._conversations.splice(existingIdx, 1);
1384
+ }
1385
+ this._conversations = [item, ...this._conversations];
1386
+ this.notify();
1387
+ } catch (err) {
1388
+ logger.debug("Failed to process conversation event:", err);
1389
+ }
1390
+ }
1391
+ );
1392
+ } catch (err) {
1393
+ logger.debug("Failed to start realtime subscription:", err);
1394
+ }
1395
+ }
1396
+ notify() {
1397
+ const snapshot = this.getSnapshot();
1398
+ for (const sub of this.subscribers) {
1399
+ try {
1400
+ sub(snapshot);
1401
+ } catch (err) {
1402
+ logger.error("Error in conversation list store subscriber:", err);
1403
+ }
1404
+ }
1405
+ }
1406
+ };
1407
+
1408
+ // src/integrations/react-conversation.ts
1409
+ var INITIAL_SNAPSHOT = {
1410
+ conversation: null,
1411
+ messages: [],
1412
+ isStreaming: false,
1413
+ isWaiting: false,
1414
+ streamingText: "",
1415
+ error: null,
1416
+ activeToolCalls: [],
1417
+ plans: [],
1418
+ isLoading: false,
1419
+ conversationPath: null
1420
+ };
1421
+ function useConversation(react, options) {
1422
+ const { useState, useEffect, useRef, useCallback } = react;
1423
+ const [snapshot, setSnapshot] = useState(INITIAL_SNAPSHOT);
1424
+ const storeRef = useRef(null);
1425
+ useEffect(() => {
1426
+ const store = new ConversationStore(options);
1427
+ storeRef.current = store;
1428
+ const unsubscribe = store.subscribe((next) => setSnapshot(next));
1429
+ return () => {
1430
+ unsubscribe();
1431
+ store.destroy();
1432
+ storeRef.current = null;
1433
+ };
1434
+ }, [options.conversationPath]);
1435
+ const sendMessage = useCallback(async (content) => {
1436
+ await storeRef.current?.sendMessage(content);
1437
+ }, []);
1438
+ const approvePlan = useCallback(async (planPath) => {
1439
+ await storeRef.current?.approvePlan(planPath);
1440
+ }, []);
1441
+ const rejectPlan = useCallback(async (planPath, feedback) => {
1442
+ await storeRef.current?.rejectPlan(planPath, feedback);
1443
+ }, []);
1444
+ const stop = useCallback(() => {
1445
+ storeRef.current?.stop();
1446
+ }, []);
1447
+ const loadMessages = useCallback(async () => {
1448
+ return await storeRef.current?.loadMessages() ?? [];
1449
+ }, []);
1450
+ return {
1451
+ ...snapshot,
1452
+ sendMessage,
1453
+ approvePlan,
1454
+ rejectPlan,
1455
+ stop,
1456
+ loadMessages
1457
+ };
1458
+ }
1459
+ var INITIAL_LIST_SNAPSHOT = {
1460
+ conversations: [],
1461
+ totalUnreadCount: 0,
1462
+ isLoading: true,
1463
+ error: null
1464
+ };
1465
+ function useConversationList(react, options) {
1466
+ const { useState, useEffect, useRef, useCallback } = react;
1467
+ const [snapshot, setSnapshot] = useState(INITIAL_LIST_SNAPSHOT);
1468
+ const storeRef = useRef(null);
1469
+ useEffect(() => {
1470
+ const store = new ConversationListStore(options);
1471
+ storeRef.current = store;
1472
+ const unsubscribe = store.subscribe((next) => setSnapshot(next));
1473
+ store.load();
1474
+ return () => {
1475
+ unsubscribe();
1476
+ store.destroy();
1477
+ storeRef.current = null;
1478
+ };
1479
+ }, [options.type, options.realtime]);
1480
+ const createConversation = useCallback(async (opts) => {
1481
+ return storeRef.current.createConversation(opts);
1482
+ }, []);
1483
+ const deleteConversation = useCallback(async (conversationPath) => {
1484
+ await storeRef.current?.deleteConversation(conversationPath);
1485
+ }, []);
1486
+ const markAsRead = useCallback(async (conversationPath) => {
1487
+ await storeRef.current?.markAsRead(conversationPath);
1488
+ }, []);
1489
+ return {
1490
+ ...snapshot,
1491
+ createConversation,
1492
+ deleteConversation,
1493
+ markAsRead
1494
+ };
1495
+ }
1496
+
1497
+ // src/errors.ts
1498
+ var RaisinError = class extends Error {
1499
+ constructor(message, code, details) {
1500
+ super(message);
1501
+ this.name = "RaisinError";
1502
+ this.code = code;
1503
+ this.details = details;
1504
+ if (Error.captureStackTrace) {
1505
+ Error.captureStackTrace(this, this.constructor);
1506
+ }
1507
+ }
1508
+ };
1509
+ var RaisinConnectionError = class extends RaisinError {
1510
+ constructor(message, code, options) {
1511
+ super(message, code, options?.details);
1512
+ this.name = "RaisinConnectionError";
1513
+ this.status = options?.status;
1514
+ }
1515
+ };
1516
+ var RaisinAuthError = class extends RaisinError {
1517
+ constructor(message, code, status, details) {
1518
+ super(message, code, details);
1519
+ this.name = "RaisinAuthError";
1520
+ this.status = status;
1521
+ }
1522
+ };
1523
+ var RaisinFlowError = class extends RaisinError {
1524
+ constructor(message, code, instanceId, details) {
1525
+ super(message, code, details);
1526
+ this.name = "RaisinFlowError";
1527
+ this.instanceId = instanceId;
1528
+ }
1529
+ };
1530
+ var RaisinTimeoutError = class extends RaisinError {
1531
+ constructor(message, code, timeoutMs, details) {
1532
+ super(message, code, details);
1533
+ this.name = "RaisinTimeoutError";
1534
+ this.timeoutMs = timeoutMs;
1535
+ }
1536
+ };
1537
+ var RaisinAbortError = class extends RaisinError {
1538
+ constructor(message = "Operation was aborted") {
1539
+ super(message, "ABORTED");
1540
+ this.name = "RaisinAbortError";
1541
+ }
1542
+ };
1543
+ function classifyHttpError(status, message, details) {
1544
+ if (status === 401) {
1545
+ return new RaisinAuthError(message, "AUTH_UNAUTHORIZED", status, details);
1546
+ }
1547
+ if (status === 403) {
1548
+ return new RaisinAuthError(message, "AUTH_FORBIDDEN", status, details);
1549
+ }
1550
+ if (status === 404) {
1551
+ return new RaisinFlowError(message, "FLOW_NOT_FOUND", void 0, details);
1552
+ }
1553
+ return new RaisinConnectionError(message, "CONNECTION_FAILED", { status, details });
1554
+ }
1555
+
1556
+ // src/streaming/sse-client.ts
1557
+ function parseSSEBlock(block) {
1558
+ let event = "message";
1559
+ let data = "";
1560
+ let id;
1561
+ const lines = block.split("\n");
1562
+ for (const line of lines) {
1563
+ if (line.startsWith("event:")) {
1564
+ event = line.slice(6).trim();
1565
+ } else if (line.startsWith("data:")) {
1566
+ if (data) data += "\n";
1567
+ data += line.slice(5).trim();
1568
+ } else if (line.startsWith("id:")) {
1569
+ id = line.slice(3).trim();
1570
+ }
1571
+ }
1572
+ if (!data) return null;
1573
+ return { event, data, id };
1574
+ }
1575
+ var SSEClient = class {
1576
+ constructor(url, options = {}) {
1577
+ this.abortController = null;
1578
+ this._state = "disconnected";
1579
+ this.url = url;
1580
+ this.options = options;
1581
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
1582
+ this._lastEventId = options.lastEventId;
1583
+ this.autoReconnect = options.reconnect?.enabled ?? true;
1584
+ this.externalSignal = options.signal;
1585
+ this.inactivityTimeoutMs = options.inactivityTimeoutMs;
1586
+ this.eventTypeSet = options.eventTypes?.length ? new Set(options.eventTypes) : null;
1587
+ this.reconnectManager = new ReconnectManager({
1588
+ initialDelay: options.reconnect?.initialDelay ?? 1e3,
1589
+ maxDelay: options.reconnect?.maxDelay ?? 3e4,
1590
+ backoffMultiplier: options.reconnect?.backoffMultiplier ?? 2,
1591
+ maxAttempts: options.reconnect?.maxAttempts ?? Infinity
1592
+ });
1593
+ }
1594
+ /** Current connection state */
1595
+ get state() {
1596
+ return this._state;
1597
+ }
1598
+ /**
1599
+ * Returns a promise that resolves once the SSE connection is established.
1600
+ *
1601
+ * Useful for ensuring the connection is ready before triggering events
1602
+ * on the server side (e.g., calling resume before consuming the stream).
1603
+ * If the client is already connected, resolves immediately.
1604
+ */
1605
+ waitUntilConnected() {
1606
+ if (this._state === "connected") return Promise.resolve();
1607
+ return new Promise((resolve, reject) => {
1608
+ const originalOnState = this.options.onStateChange;
1609
+ this.options.onStateChange = (state) => {
1610
+ originalOnState?.(state);
1611
+ if (state === "connected") {
1612
+ this.options.onStateChange = originalOnState;
1613
+ resolve();
1614
+ } else if (state === "disconnected") {
1615
+ this.options.onStateChange = originalOnState;
1616
+ reject(new Error("SSE connection failed"));
1617
+ }
1618
+ };
1619
+ });
1620
+ }
1621
+ /** Last received event ID */
1622
+ get lastEventId() {
1623
+ return this._lastEventId;
1624
+ }
1625
+ setState(state) {
1626
+ if (this._state !== state) {
1627
+ this._state = state;
1628
+ this.options.onStateChange?.(state);
1629
+ }
1630
+ }
1631
+ /**
1632
+ * Connect and consume events via callback.
1633
+ *
1634
+ * @param onEvent - Called for each matching SSE event
1635
+ * @param onError - Called when an error occurs (optional)
1636
+ */
1637
+ async connect(onEvent, onError) {
1638
+ this.close();
1639
+ await this.startStream(onEvent, onError);
1640
+ }
1641
+ /**
1642
+ * Close the SSE connection and stop reconnection attempts.
1643
+ */
1644
+ close() {
1645
+ this.reconnectManager.cancelReconnect();
1646
+ if (this.abortController) {
1647
+ this.abortController.abort();
1648
+ this.abortController = null;
1649
+ }
1650
+ this.setState("disconnected");
1651
+ }
1652
+ /**
1653
+ * AsyncIterable interface: allows `for await (const event of sseClient)`.
1654
+ *
1655
+ * The iterator ends when close() is called or the server closes the stream
1656
+ * (and auto-reconnect is disabled or max attempts are exhausted).
1657
+ */
1658
+ async *[Symbol.asyncIterator]() {
1659
+ const queue = [];
1660
+ let resolve = null;
1661
+ let finished = false;
1662
+ const push = (item) => {
1663
+ if (finished) return;
1664
+ if (resolve) {
1665
+ const r = resolve;
1666
+ resolve = null;
1667
+ r(item);
1668
+ } else {
1669
+ queue.push(item);
1670
+ }
1671
+ };
1672
+ const pull = () => {
1673
+ const queued = queue.shift();
1674
+ if (queued) return Promise.resolve(queued);
1675
+ return new Promise((r) => {
1676
+ resolve = r;
1677
+ });
1678
+ };
1679
+ this.startStream(
1680
+ (event) => push({ done: false, value: event }),
1681
+ (error) => push({ done: true, error })
1682
+ ).then(() => {
1683
+ push({ done: true });
1684
+ }).catch((error) => {
1685
+ push({ done: true, error });
1686
+ });
1687
+ try {
1688
+ while (!finished) {
1689
+ const item = await pull();
1690
+ if (item.done) {
1691
+ finished = true;
1692
+ if (item.error) {
1693
+ throw item.error;
1694
+ }
1695
+ return;
1696
+ }
1697
+ yield item.value;
1698
+ }
1699
+ } finally {
1700
+ finished = true;
1701
+ this.close();
1702
+ }
1703
+ }
1704
+ /**
1705
+ * Core streaming loop: connects, reads the SSE stream, and handles reconnection.
1706
+ */
1707
+ async startStream(onEvent, onError) {
1708
+ while (true) {
1709
+ try {
1710
+ await this.readStream(onEvent);
1711
+ if (!this.autoReconnect || this._state === "disconnected") {
1712
+ return;
1713
+ }
1714
+ this.setState("reconnecting");
1715
+ const scheduled = await this.waitForReconnect();
1716
+ if (!scheduled) {
1717
+ logger.warn("SSE max reconnection attempts reached");
1718
+ this.setState("disconnected");
1719
+ return;
1720
+ }
1721
+ } catch (error) {
1722
+ if (this._state === "disconnected") {
1723
+ return;
1724
+ }
1725
+ const err = error instanceof Error ? error : new Error(String(error));
1726
+ if (err.name === "AbortError" || err instanceof RaisinAbortError) {
1727
+ return;
1728
+ }
1729
+ if (err instanceof RaisinTimeoutError && err.code === "SSE_INACTIVITY_TIMEOUT") {
1730
+ logger.warn("SSE inactivity timeout:", err.message);
1731
+ if (!this.autoReconnect) {
1732
+ this.setState("disconnected");
1733
+ onError?.(err);
1734
+ throw err;
1735
+ }
1736
+ this.setState("reconnecting");
1737
+ const scheduled2 = await this.waitForReconnect();
1738
+ if (!scheduled2) {
1739
+ logger.warn("SSE max reconnection attempts reached");
1740
+ this.setState("disconnected");
1741
+ onError?.(err);
1742
+ throw err;
1743
+ }
1744
+ continue;
1745
+ }
1746
+ logger.error("SSE connection error:", err.message);
1747
+ onError?.(err);
1748
+ if (!this.autoReconnect) {
1749
+ this.setState("disconnected");
1750
+ throw err;
1751
+ }
1752
+ this.setState("reconnecting");
1753
+ const scheduled = await this.waitForReconnect();
1754
+ if (!scheduled) {
1755
+ logger.warn("SSE max reconnection attempts reached");
1756
+ this.setState("disconnected");
1757
+ throw err;
1758
+ }
1759
+ }
1760
+ }
1761
+ }
1762
+ /**
1763
+ * Perform a single fetch and read the response body as SSE stream.
1764
+ */
1765
+ async readStream(onEvent) {
1766
+ this.abortController = new AbortController();
1767
+ this.setState("connecting");
1768
+ if (this.externalSignal) {
1769
+ if (this.externalSignal.aborted) {
1770
+ this.abortController.abort();
1771
+ } else {
1772
+ const ctrl = this.abortController;
1773
+ this.externalSignal.addEventListener("abort", () => ctrl.abort(), { once: true });
1774
+ }
1775
+ }
1776
+ const headers = {
1777
+ Accept: "text/event-stream",
1778
+ "Cache-Control": "no-cache",
1779
+ ...this.options.headers
1780
+ };
1781
+ if (this._lastEventId) {
1782
+ headers["Last-Event-ID"] = this._lastEventId;
1783
+ }
1784
+ const method = this.options.method ?? "GET";
1785
+ const fetchOptions = {
1786
+ method,
1787
+ headers,
1788
+ signal: this.abortController.signal
1789
+ };
1790
+ if (method === "POST" && this.options.body !== void 0) {
1791
+ fetchOptions.headers["Content-Type"] = "application/json";
1792
+ fetchOptions.body = JSON.stringify(this.options.body);
1793
+ }
1794
+ const response = await this.withInactivityTimeout(
1795
+ this.fetchImpl(this.url, fetchOptions)
1796
+ );
1797
+ if (!response.ok) {
1798
+ const text = await response.text().catch(() => "");
1799
+ const msg = `SSE connection failed: ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`;
1800
+ if (response.status === 401 || response.status === 403) {
1801
+ throw new RaisinAuthError(
1802
+ msg,
1803
+ response.status === 401 ? "AUTH_UNAUTHORIZED" : "AUTH_FORBIDDEN",
1804
+ response.status
1805
+ );
1806
+ }
1807
+ throw new RaisinConnectionError(msg, "SSE_STREAM_ERROR", { status: response.status });
1808
+ }
1809
+ if (!response.body) {
1810
+ throw new RaisinConnectionError("SSE response has no body", "SSE_STREAM_ERROR");
1811
+ }
1812
+ this.setState("connected");
1813
+ this.reconnectManager.reset();
1814
+ const reader = response.body.getReader();
1815
+ const decoder = new TextDecoder();
1816
+ let buffer = "";
1817
+ try {
1818
+ while (true) {
1819
+ const { done, value } = await this.withInactivityTimeout(reader.read());
1820
+ if (done) break;
1821
+ buffer += decoder.decode(value, { stream: true });
1822
+ const blocks = buffer.split("\n\n");
1823
+ buffer = blocks.pop() ?? "";
1824
+ for (const block of blocks) {
1825
+ const trimmed = block.trim();
1826
+ if (!trimmed) continue;
1827
+ const parsed = parseSSEBlock(trimmed);
1828
+ if (!parsed) continue;
1829
+ if (parsed.id) {
1830
+ this._lastEventId = parsed.id;
1831
+ }
1832
+ if (this.eventTypeSet && !this.eventTypeSet.has(parsed.event)) {
1833
+ continue;
1834
+ }
1835
+ let data;
1836
+ try {
1837
+ data = JSON.parse(parsed.data);
1838
+ } catch {
1839
+ data = parsed.data;
1840
+ }
1841
+ const sseEvent = {
1842
+ type: parsed.event,
1843
+ data,
1844
+ id: parsed.id
1845
+ };
1846
+ onEvent(sseEvent);
1847
+ }
1848
+ }
1849
+ } finally {
1850
+ try {
1851
+ reader.releaseLock();
1852
+ } catch {
1853
+ }
1854
+ }
1855
+ }
1856
+ /**
1857
+ * Race a stream operation against the inactivity timeout.
1858
+ *
1859
+ * If no bytes (or response) arrive within `inactivityTimeoutMs`, the
1860
+ * internal connection is aborted and the operation rejects with a
1861
+ * `RaisinTimeoutError` (code `SSE_INACTIVITY_TIMEOUT`). The timer is
1862
+ * effectively reset on every chunk because each `reader.read()` is
1863
+ * wrapped individually.
1864
+ */
1865
+ withInactivityTimeout(promise) {
1866
+ const timeoutMs = this.inactivityTimeoutMs;
1867
+ if (!timeoutMs || timeoutMs <= 0) return promise;
1868
+ return new Promise((resolve, reject) => {
1869
+ const timer = setTimeout(() => {
1870
+ promise.catch(() => void 0);
1871
+ this.abortController?.abort();
1872
+ reject(
1873
+ new RaisinTimeoutError(
1874
+ `SSE stream inactive for ${timeoutMs}ms`,
1875
+ "SSE_INACTIVITY_TIMEOUT",
1876
+ timeoutMs
1877
+ )
1878
+ );
1879
+ }, timeoutMs);
1880
+ promise.then(
1881
+ (value) => {
1882
+ clearTimeout(timer);
1883
+ resolve(value);
1884
+ },
1885
+ (error) => {
1886
+ clearTimeout(timer);
1887
+ reject(error);
1888
+ }
1889
+ );
1890
+ });
1891
+ }
1892
+ /**
1893
+ * Wait for the reconnect manager to schedule a reconnection attempt.
1894
+ * Returns true if reconnection was scheduled, false if max attempts reached.
1895
+ */
1896
+ waitForReconnect() {
1897
+ return new Promise((resolve) => {
1898
+ const scheduled = this.reconnectManager.scheduleReconnect(() => {
1899
+ resolve(true);
1900
+ });
1901
+ if (!scheduled) {
1902
+ resolve(false);
1903
+ }
1904
+ });
1905
+ }
1906
+ };
1907
+
1908
+ // src/flow-client.ts
1909
+ var FlowClient = class _FlowClient {
1910
+ /**
1911
+ * Create a new FlowClient.
1912
+ *
1913
+ * @param baseUrl - Base HTTP URL of the RaisinDB server (e.g., "http://localhost:8081")
1914
+ * @param repository - Repository name
1915
+ * @param authManager - Auth manager for token access
1916
+ * @param options - Additional options
1917
+ * @param flowsApi - Optional FlowsApi for WebSocket-based flow operations
1918
+ */
1919
+ constructor(baseUrl, repository, authManager, options = {}, flowsApi) {
1920
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1921
+ this.repository = repository;
1922
+ this.authManager = authManager;
1923
+ this.fetchImpl = options.fetch ?? fetch;
1924
+ this.requestTimeout = options.requestTimeout ?? 6e4;
1925
+ this.flowsApi = flowsApi;
1926
+ }
1927
+ /**
1928
+ * Create a FlowClient from an existing RaisinHttpClient.
1929
+ *
1930
+ * @param httpClient - An authenticated RaisinHttpClient instance
1931
+ * @param baseUrl - Base HTTP URL (same as the one used for the HTTP client)
1932
+ * @param repository - Repository name
1933
+ * @param options - Additional options
1934
+ */
1935
+ static fromHttpClient(httpClient, baseUrl, repository, options = {}, flowsApi) {
1936
+ return new _FlowClient(
1937
+ baseUrl,
1938
+ repository,
1939
+ httpClient.getAuthManager(),
1940
+ options,
1941
+ flowsApi
1942
+ );
1943
+ }
1944
+ // ==========================================================================
1945
+ // Flow Execution
1946
+ // ==========================================================================
1947
+ /**
1948
+ * Execute a flow by path.
1949
+ *
1950
+ * Creates a FlowInstance and queues it for execution. Returns immediately
1951
+ * with the instance ID - use `streamEvents()` to monitor progress.
1952
+ *
1953
+ * @param flowPath - Path to the raisin:Flow node (e.g., "/flows/my-flow")
1954
+ * @param input - Input data passed to the flow
1955
+ * @returns Flow run response with instance_id and job_id
1956
+ *
1957
+ * @example
1958
+ * ```typescript
1959
+ * const result = await flows.run('/flows/process-order', {
1960
+ * orderId: 'ord-123',
1961
+ * items: [{ sku: 'ABC', qty: 2 }],
1962
+ * });
1963
+ * console.log('Instance:', result.instance_id);
1964
+ * ```
1965
+ */
1966
+ async run(flowPath, input = {}, options) {
1967
+ if (this.flowsApi) {
1968
+ return this.flowsApi.run(flowPath, input);
1969
+ }
1970
+ const response = await this.request({
1971
+ method: "POST",
1972
+ path: `/api/flows/${this.repository}/run`,
1973
+ body: { flow_path: flowPath, input },
1974
+ signal: options?.signal
1975
+ });
1976
+ return response;
1977
+ }
1978
+ // ==========================================================================
1979
+ // Instance Status
1980
+ // ==========================================================================
1981
+ /**
1982
+ * Get the current status of a flow instance.
1983
+ *
1984
+ * Returns the instance status, variables, and metadata. Useful for
1985
+ * polling-based approaches where SSE is not reliable (e.g., initial
1986
+ * flow execution where events may be missed).
1987
+ *
1988
+ * @param instanceId - Flow instance ID (from `run()`)
1989
+ * @returns Instance status including variables and flow path
1990
+ *
1991
+ * @example
1992
+ * ```typescript
1993
+ * const status = await flows.getInstanceStatus('instance-123');
1994
+ * console.log('Status:', status.status); // 'waiting', 'completed', etc.
1995
+ * ```
1996
+ */
1997
+ async getInstanceStatus(instanceId, options) {
1998
+ if (this.flowsApi) {
1999
+ return this.flowsApi.getInstanceStatus(instanceId);
2000
+ }
2001
+ return this.request({
2002
+ method: "GET",
2003
+ path: `/api/flows/${this.repository}/instances/${instanceId}`,
2004
+ signal: options?.signal
2005
+ });
2006
+ }
2007
+ // ==========================================================================
2008
+ // Event Streaming (SSE)
2009
+ // ==========================================================================
2010
+ /**
2011
+ * Stream real-time execution events for a flow instance via SSE.
2012
+ *
2013
+ * Returns an async iterable that yields FlowExecutionEvent objects.
2014
+ * The stream automatically closes when a terminal event is received
2015
+ * (flow_completed or flow_failed).
2016
+ *
2017
+ * @param instanceId - Flow instance ID (from `run()`)
2018
+ * @returns Async iterable of flow execution events
2019
+ *
2020
+ * @example
2021
+ * ```typescript
2022
+ * const { instance_id } = await flows.run('/flows/my-flow', { key: 'value' });
2023
+ *
2024
+ * for await (const event of flows.streamEvents(instance_id)) {
2025
+ * switch (event.type) {
2026
+ * case 'step_started':
2027
+ * console.log(`Step ${event.node_id} started`);
2028
+ * break;
2029
+ * case 'step_completed':
2030
+ * console.log(`Step ${event.node_id} completed in ${event.duration_ms}ms`);
2031
+ * break;
2032
+ * case 'text_chunk':
2033
+ * process.stdout.write(event.text);
2034
+ * break;
2035
+ * case 'flow_completed':
2036
+ * console.log('Flow done:', event.output);
2037
+ * break;
2038
+ * case 'flow_failed':
2039
+ * console.error('Flow failed:', event.error);
2040
+ * break;
2041
+ * }
2042
+ * }
2043
+ * ```
2044
+ */
2045
+ async *streamEvents(instanceId, options) {
2046
+ if (this.flowsApi) {
2047
+ const sub = await this.flowsApi.subscribeEvents(instanceId);
2048
+ try {
2049
+ for await (const event of sub.events) {
2050
+ if (options?.signal?.aborted) throw new RaisinAbortError();
2051
+ yield event;
2052
+ if (event.type === "flow_completed" || event.type === "flow_failed") {
2053
+ return;
2054
+ }
2055
+ }
2056
+ } finally {
2057
+ await sub.unsubscribe();
2058
+ }
2059
+ return;
2060
+ }
2061
+ const url = `${this.baseUrl}/api/flows/${this.repository}/instances/${instanceId}/events`;
2062
+ const headers = {};
2063
+ const token = this.authManager.getAccessToken();
2064
+ if (token) {
2065
+ headers["Authorization"] = `Bearer ${token}`;
2066
+ }
2067
+ const sse = new SSEClient(url, {
2068
+ headers,
2069
+ eventTypes: ["flow-event", "message"],
2070
+ reconnect: { enabled: false },
2071
+ fetch: this.fetchImpl,
2072
+ signal: options?.signal
2073
+ });
2074
+ try {
2075
+ for await (const sseEvent of sse) {
2076
+ const event = sseEvent.data;
2077
+ yield event;
2078
+ if (event.type === "flow_completed" || event.type === "flow_failed") {
2079
+ return;
2080
+ }
2081
+ }
2082
+ } finally {
2083
+ sse.close();
2084
+ }
2085
+ }
2086
+ /**
2087
+ * Create an eagerly-connected event stream for a flow instance.
2088
+ *
2089
+ * Unlike `streamEvents()` (a lazy async generator), this method opens the
2090
+ * SSE connection immediately and waits until it is established before
2091
+ * returning. This is critical for resume flows: you must subscribe to
2092
+ * events BEFORE calling `resume()`, otherwise events emitted between
2093
+ * the resume and the SSE connection are lost.
2094
+ *
2095
+ * @param instanceId - Flow instance ID
2096
+ * @returns Object with an async iterable `events` and a `close()` method
2097
+ */
2098
+ async createEventStream(instanceId, options) {
2099
+ if (this.flowsApi) {
2100
+ const sub = await this.flowsApi.subscribeEvents(instanceId);
2101
+ return {
2102
+ events: sub.events,
2103
+ close: () => {
2104
+ sub.unsubscribe();
2105
+ }
2106
+ };
2107
+ }
2108
+ const url = `${this.baseUrl}/api/flows/${this.repository}/instances/${instanceId}/events`;
2109
+ const headers = {};
2110
+ const token = this.authManager.getAccessToken();
2111
+ if (token) {
2112
+ headers["Authorization"] = `Bearer ${token}`;
2113
+ }
2114
+ const sse = new SSEClient(url, {
2115
+ headers,
2116
+ eventTypes: ["flow-event", "message"],
2117
+ reconnect: { enabled: false },
2118
+ fetch: this.fetchImpl,
2119
+ signal: options?.signal
2120
+ });
2121
+ const iterator = sse[Symbol.asyncIterator]();
2122
+ let pendingFirst = iterator.next();
2123
+ await sse.waitUntilConnected();
2124
+ const events = {
2125
+ [Symbol.asyncIterator]() {
2126
+ return {
2127
+ async next() {
2128
+ let result;
2129
+ if (pendingFirst) {
2130
+ result = await pendingFirst;
2131
+ pendingFirst = null;
2132
+ } else {
2133
+ result = await iterator.next();
2134
+ }
2135
+ if (result.done) return { done: true, value: void 0 };
2136
+ const event = result.value.data;
2137
+ return { done: false, value: event };
2138
+ },
2139
+ async return() {
2140
+ await iterator.return?.();
2141
+ sse.close();
2142
+ return { done: true, value: void 0 };
2143
+ }
2144
+ };
2145
+ }
2146
+ };
2147
+ return { events, close: () => sse.close() };
2148
+ }
2149
+ // ==========================================================================
2150
+ // Flow Resume & Human Task
2151
+ // ==========================================================================
2152
+ /**
2153
+ * Resume a flow instance that is in a waiting state.
2154
+ *
2155
+ * Use this when a flow is waiting for external input (tool results,
2156
+ * external events, etc.). The resume data is passed to the waiting step.
2157
+ *
2158
+ * @param instanceId - Flow instance ID
2159
+ * @param data - Resume data to pass to the waiting step
2160
+ *
2161
+ * @example
2162
+ * ```typescript
2163
+ * await flows.resume('instance-123', {
2164
+ * tool_name: 'get_weather',
2165
+ * result: { temperature: 72, conditions: 'sunny' },
2166
+ * });
2167
+ * ```
2168
+ */
2169
+ async resume(instanceId, data, options) {
2170
+ if (this.flowsApi) {
2171
+ await this.flowsApi.resume(instanceId, data);
2172
+ return;
2173
+ }
2174
+ await this.request({
2175
+ method: "POST",
2176
+ path: `/api/flows/${this.repository}/instances/${instanceId}/resume`,
2177
+ body: { resume_data: data },
2178
+ signal: options?.signal
2179
+ });
2180
+ }
2181
+ /**
2182
+ * Respond to a human task within a flow.
2183
+ *
2184
+ * When a flow is waiting on a human_task step (approval, input, review),
2185
+ * use this method to submit the response. Completion is validated
2186
+ * (caller must be the task's assignee or an admin) and resumes the flow.
2187
+ *
2188
+ * Note: prefer `InboxApi` for full inbox functionality (listing tasks,
2189
+ * task details); this is a convenience passthrough to the same endpoint.
2190
+ *
2191
+ * @param instanceId - Flow instance ID (unused; kept for API stability)
2192
+ * @param taskId - The inbox task node ID (or path)
2193
+ * @param response - The response data
2194
+ *
2195
+ * @example
2196
+ * ```typescript
2197
+ * // Approve a task
2198
+ * await flows.respondToHumanTask('instance-123', 'task-abc', {
2199
+ * action: 'approve',
2200
+ * comment: 'Looks good!',
2201
+ * });
2202
+ * ```
2203
+ */
2204
+ async respondToHumanTask(_instanceId, taskId, response, options) {
2205
+ await this.request({
2206
+ method: "POST",
2207
+ path: `/api/inbox/${this.repository}/tasks/${encodeURIComponent(taskId)}/complete`,
2208
+ body: { response },
2209
+ signal: options?.signal
2210
+ });
2211
+ }
2212
+ // ==========================================================================
2213
+ // Convenience Methods
2214
+ // ==========================================================================
2215
+ /**
2216
+ * Run a flow and wait for the final result.
2217
+ *
2218
+ * Starts the flow, streams all events, and returns the terminal outcome.
2219
+ * This is a one-shot helper for fire-and-forget flows where you only
2220
+ * care about the final output.
2221
+ *
2222
+ * @param flowPath - Path to the raisin:Flow node
2223
+ * @param input - Input data passed to the flow
2224
+ * @param options - Optional abort signal
2225
+ * @returns The flow outcome including output or error
2226
+ *
2227
+ * @example
2228
+ * ```typescript
2229
+ * const result = await flows.runAndWait('/flows/process-order', { orderId: '123' });
2230
+ * if (result.status === 'completed') {
2231
+ * console.log('Output:', result.output);
2232
+ * }
2233
+ * ```
2234
+ */
2235
+ async runAndWait(flowPath, input = {}, options) {
2236
+ const { instance_id } = await this.run(flowPath, input, options);
2237
+ for await (const event of this.streamEvents(instance_id, options)) {
2238
+ if (event.type === "flow_completed") {
2239
+ return {
2240
+ instanceId: instance_id,
2241
+ status: "completed",
2242
+ output: event.output
2243
+ };
2244
+ }
2245
+ if (event.type === "flow_failed") {
2246
+ return {
2247
+ instanceId: instance_id,
2248
+ status: "failed",
2249
+ error: event.error
2250
+ };
2251
+ }
2252
+ }
2253
+ return { instanceId: instance_id, status: "failed", error: "Stream ended without terminal event" };
2254
+ }
2255
+ /**
2256
+ * Run a flow and collect all events into an array.
2257
+ *
2258
+ * Starts the flow, streams all events, and returns them as a collected array.
2259
+ * Useful for testing, logging, or post-processing all flow events.
2260
+ *
2261
+ * @param flowPath - Path to the raisin:Flow node
2262
+ * @param input - Input data passed to the flow
2263
+ * @param options - Optional abort signal
2264
+ * @returns The instance ID and all collected events
2265
+ *
2266
+ * @example
2267
+ * ```typescript
2268
+ * const { events } = await flows.runAndCollect('/flows/etl-pipeline', { source: 'db' });
2269
+ * const steps = events.filter(e => e.type === 'step_completed');
2270
+ * console.log(`Completed ${steps.length} steps`);
2271
+ * ```
2272
+ */
2273
+ async runAndCollect(flowPath, input = {}, options) {
2274
+ const { instance_id } = await this.run(flowPath, input, options);
2275
+ const events = [];
2276
+ for await (const event of this.streamEvents(instance_id, options)) {
2277
+ events.push(event);
2278
+ }
2279
+ return { instanceId: instance_id, events };
2280
+ }
2281
+ // ==========================================================================
2282
+ // Internal HTTP request helper
2283
+ // ==========================================================================
2284
+ async request(options) {
2285
+ const url = `${this.baseUrl}${options.path}`;
2286
+ const headers = {
2287
+ "Content-Type": "application/json"
2288
+ };
2289
+ const token = this.authManager.getAccessToken();
2290
+ if (token) {
2291
+ headers["Authorization"] = `Bearer ${token}`;
2292
+ }
2293
+ const controller = new AbortController();
2294
+ const timeoutId = setTimeout(() => controller.abort(), this.requestTimeout);
2295
+ if (options.signal) {
2296
+ if (options.signal.aborted) {
2297
+ clearTimeout(timeoutId);
2298
+ throw new RaisinAbortError();
2299
+ }
2300
+ options.signal.addEventListener("abort", () => controller.abort(), { once: true });
2301
+ }
2302
+ try {
2303
+ const response = await this.fetchImpl(url, {
2304
+ method: options.method,
2305
+ headers,
2306
+ body: options.body ? JSON.stringify(options.body) : void 0,
2307
+ signal: controller.signal
2308
+ });
2309
+ clearTimeout(timeoutId);
2310
+ if (!response.ok) {
2311
+ const errorText = await response.text();
2312
+ let errorMessage;
2313
+ try {
2314
+ const errorJson = JSON.parse(errorText);
2315
+ errorMessage = errorJson.message || errorJson.error || errorText;
2316
+ } catch {
2317
+ errorMessage = errorText || `HTTP ${response.status}: ${response.statusText}`;
2318
+ }
2319
+ throw classifyHttpError(response.status, errorMessage);
2320
+ }
2321
+ const contentType = response.headers.get("content-type");
2322
+ if (contentType?.includes("application/json")) {
2323
+ return await response.json();
2324
+ }
2325
+ return void 0;
2326
+ } catch (error) {
2327
+ clearTimeout(timeoutId);
2328
+ if (error instanceof RaisinAbortError || error instanceof RaisinTimeoutError) {
2329
+ throw error;
2330
+ }
2331
+ if (error instanceof Error && error.name === "AbortError") {
2332
+ if (options.signal?.aborted) {
2333
+ throw new RaisinAbortError();
2334
+ }
2335
+ throw new RaisinTimeoutError(
2336
+ `Request timeout after ${this.requestTimeout}ms`,
2337
+ "REQUEST_TIMEOUT",
2338
+ this.requestTimeout
2339
+ );
2340
+ }
2341
+ throw error;
2342
+ }
2343
+ }
2344
+ };
2345
+
2346
+ // src/integrations/react-flow.ts
2347
+ function useFlow(react, options) {
2348
+ const { useState, useEffect, useRef, useCallback } = react;
2349
+ const [events, setEvents] = useState([]);
2350
+ const [status, setStatus] = useState("idle");
2351
+ const [error, setError] = useState(null);
2352
+ const [output, setOutput] = useState(null);
2353
+ const [instanceId, setInstanceId] = useState(null);
2354
+ const clientRef = useRef(null);
2355
+ const abortRef = useRef(false);
2356
+ useEffect(() => {
2357
+ if (options.database) {
2358
+ clientRef.current = options.database.flow;
2359
+ } else if (options.baseUrl && options.repository && options.authManager) {
2360
+ clientRef.current = new FlowClient(
2361
+ options.baseUrl,
2362
+ options.repository,
2363
+ options.authManager,
2364
+ options.clientOptions,
2365
+ options.flowsApi
2366
+ );
2367
+ }
2368
+ return () => {
2369
+ abortRef.current = true;
2370
+ clientRef.current = null;
2371
+ };
2372
+ }, [options.database, options.baseUrl, options.repository]);
2373
+ const run = useCallback(async (flowPath, input = {}) => {
2374
+ const client = clientRef.current;
2375
+ if (!client) return;
2376
+ abortRef.current = false;
2377
+ setEvents([]);
2378
+ setError(null);
2379
+ setOutput(null);
2380
+ setStatus("running");
2381
+ try {
2382
+ const result = await client.run(flowPath, input);
2383
+ setInstanceId(result.instance_id);
2384
+ for await (const event of client.streamEvents(result.instance_id)) {
2385
+ if (abortRef.current) break;
2386
+ setEvents((prev) => [...prev, event]);
2387
+ if (event.type === "flow_waiting") {
2388
+ setStatus("waiting");
2389
+ } else if (event.type === "flow_completed") {
2390
+ setOutput(event.output);
2391
+ setStatus("completed");
2392
+ } else if (event.type === "flow_failed") {
2393
+ setError(event.error);
2394
+ setStatus("failed");
2395
+ }
2396
+ }
2397
+ } catch (err) {
2398
+ setError(err instanceof Error ? err.message : String(err));
2399
+ setStatus("failed");
2400
+ }
2401
+ }, []);
2402
+ const resume = useCallback(async (data) => {
2403
+ const client = clientRef.current;
2404
+ if (!client || !instanceId) return;
2405
+ setStatus("running");
2406
+ setError(null);
2407
+ try {
2408
+ const stream = await client.createEventStream(instanceId);
2409
+ await client.resume(instanceId, data);
2410
+ for await (const event of stream.events) {
2411
+ if (abortRef.current) break;
2412
+ setEvents((prev) => [...prev, event]);
2413
+ if (event.type === "flow_waiting") {
2414
+ setStatus("waiting");
2415
+ stream.close();
2416
+ return;
2417
+ } else if (event.type === "flow_completed") {
2418
+ setOutput(event.output);
2419
+ setStatus("completed");
2420
+ stream.close();
2421
+ return;
2422
+ } else if (event.type === "flow_failed") {
2423
+ setError(event.error);
2424
+ setStatus("failed");
2425
+ stream.close();
2426
+ return;
2427
+ }
2428
+ }
2429
+ stream.close();
2430
+ } catch (err) {
2431
+ setError(err instanceof Error ? err.message : String(err));
2432
+ setStatus("failed");
2433
+ }
2434
+ }, [instanceId]);
2435
+ const reset = useCallback(() => {
2436
+ abortRef.current = true;
2437
+ setEvents([]);
2438
+ setStatus("idle");
2439
+ setError(null);
2440
+ setOutput(null);
2441
+ setInstanceId(null);
2442
+ }, []);
2443
+ return {
2444
+ events,
2445
+ status,
2446
+ isRunning: status === "running",
2447
+ error,
2448
+ output,
2449
+ instanceId,
2450
+ run,
2451
+ resume,
2452
+ reset
2453
+ };
2454
+ }
2455
+
2456
+ // src/integrations/react/index.ts
2457
+ function createRaisinReact(react) {
2458
+ const RaisinContext = react.createContext(null);
2459
+ function RaisinProvider(props) {
2460
+ const { client, repository, children } = props;
2461
+ const value = react.useMemo(
2462
+ () => ({ client, repository }),
2463
+ [client, repository]
2464
+ );
2465
+ return react.createElement(
2466
+ RaisinContext.Provider,
2467
+ { value },
2468
+ children
2469
+ );
2470
+ }
2471
+ function useRaisinClient() {
2472
+ const ctx = react.useContext(RaisinContext);
2473
+ if (!ctx) {
2474
+ throw new Error("useRaisinClient must be used within a <RaisinProvider>");
2475
+ }
2476
+ return ctx.client;
2477
+ }
2478
+ function useDatabase(repository) {
2479
+ const ctx = react.useContext(RaisinContext);
2480
+ if (!ctx) {
2481
+ throw new Error("useDatabase must be used within a <RaisinProvider>");
2482
+ }
2483
+ const repo = repository ?? ctx.repository;
2484
+ if (!repo) {
2485
+ throw new Error("useDatabase requires a repository \u2014 pass it as an argument or set it on <RaisinProvider>");
2486
+ }
2487
+ return react.useMemo(() => ctx.client.database(repo), [ctx.client, repo]);
2488
+ }
2489
+ const useAuth = createUseAuth(react, RaisinContext);
2490
+ const useConnection = createUseConnection(react, RaisinContext);
2491
+ const useSql = createUseSql(react, RaisinContext);
2492
+ const useSubscription = createUseSubscription(react, RaisinContext);
2493
+ function useConversation2(options) {
2494
+ return useConversation(react, options);
2495
+ }
2496
+ function useConversationList2(options) {
2497
+ return useConversationList(react, options);
2498
+ }
2499
+ function useFlow2(options) {
2500
+ return useFlow(react, options);
2501
+ }
2502
+ return {
2503
+ RaisinProvider,
2504
+ useRaisinClient,
2505
+ useDatabase,
2506
+ useAuth,
2507
+ useConnection,
2508
+ useSql,
2509
+ useSubscription,
2510
+ useConversation: useConversation2,
2511
+ useConversationList: useConversationList2,
2512
+ useFlow: useFlow2
2513
+ };
2514
+ }
2515
+ // Annotate the CommonJS export names for ESM import in node:
2516
+ 0 && (module.exports = {
2517
+ createRaisinReact
2518
+ });
2519
+ //# sourceMappingURL=react.js.map