@raisindb/client 0.1.16 → 0.1.18

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