@raisindb/client 0.1.0 → 0.1.1

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