@arbidocs/react 0.4.166 → 0.4.168

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 (97) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3J7MEBOW.cjs +2551 -0
  14. package/dist/chunk-3J7MEBOW.cjs.map +1 -0
  15. package/dist/chunk-3NVSUYUV.js +528 -0
  16. package/dist/chunk-3NVSUYUV.js.map +1 -0
  17. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  18. package/dist/chunk-3WIBD44F.js.map +1 -0
  19. package/dist/chunk-5B4PPJNW.cjs +1035 -0
  20. package/dist/chunk-5B4PPJNW.cjs.map +1 -0
  21. package/dist/chunk-5HDC43MF.js +145 -0
  22. package/dist/chunk-5HDC43MF.js.map +1 -0
  23. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  24. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  25. package/dist/chunk-APZZQZ6P.js +147 -0
  26. package/dist/chunk-APZZQZ6P.js.map +1 -0
  27. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  28. package/dist/chunk-DGMK3EUN.js.map +1 -0
  29. package/dist/chunk-DPYBZDJB.js +18 -0
  30. package/dist/chunk-DPYBZDJB.js.map +1 -0
  31. package/dist/chunk-EEIYXVM4.cjs +181 -0
  32. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  33. package/dist/chunk-H3LMKO3T.js +2362 -0
  34. package/dist/chunk-H3LMKO3T.js.map +1 -0
  35. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  36. package/dist/chunk-KGCGA452.js.map +1 -0
  37. package/dist/chunk-MJNZLWJD.js +986 -0
  38. package/dist/chunk-MJNZLWJD.js.map +1 -0
  39. package/dist/chunk-N73IMVFF.cjs +21 -0
  40. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  41. package/dist/chunk-NVAIVJID.js +298 -0
  42. package/dist/chunk-NVAIVJID.js.map +1 -0
  43. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  44. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  45. package/dist/chunk-S4PCA3ES.cjs +572 -0
  46. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  47. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  48. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  49. package/dist/chunk-VLK52VXC.cjs +307 -0
  50. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +85 -109
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +19 -5
  58. package/dist/document-tools/index.d.ts +19 -5
  59. package/dist/document-tools/index.js +28 -70
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12692 -9494
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +200 -195
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +4 -3
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +2 -2
  84. package/dist/viewers/index.js +1 -1
  85. package/package.json +13 -3
  86. package/dist/chunk-6MTKKT2O.cjs +0 -999
  87. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  88. package/dist/chunk-CEZCFQ47.js +0 -932
  89. package/dist/chunk-CEZCFQ47.js.map +0 -1
  90. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  91. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  92. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  93. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  94. package/dist/chunk-JSSKEXRR.js.map +0 -1
  95. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  96. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  97. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -0,0 +1,986 @@
1
+ import { OWN_SESSION_SLOT } from './chunk-DPYBZDJB.js';
2
+ import { arbiQueryKeys } from './chunk-NVAIVJID.js';
3
+ import { parseVersionRef } from './chunk-NNWMHMEC.js';
4
+ import { useArbiHost, useArbi } from './chunk-KGCGA452.js';
5
+ import { getUserEncryptionKeypair, sealedBoxDecrypt, sealedBoxEncrypt } from '@arbidocs/client';
6
+ import { useSyncExternalStore, useMemo, useRef, useEffect } from 'react';
7
+ import { useQuery, useMutation, useQueryClient, useInfiniteQuery, useQueries } from '@tanstack/react-query';
8
+ import { ArbiApiError } from '@arbidocs/sdk/browser';
9
+
10
+ // src/chat/run-state.ts
11
+ var MIN_QUEUED_MESSAGE_VISIBILITY_MS = 800;
12
+ var mapQueues = (queues, update) => Object.fromEntries(Object.entries(queues).map(([id, messages]) => [id, update(messages)]));
13
+ function findConsumedMessages(messages, combinedContent) {
14
+ const text = combinedContent.trim();
15
+ const taken = /* @__PURE__ */ new Set();
16
+ let cursor = 0;
17
+ for (const message of messages) {
18
+ if (cursor >= text.length) break;
19
+ const content = message.content.trim();
20
+ if (!content) continue;
21
+ const separator = cursor === 0 ? "" : "\n\n";
22
+ if (text.startsWith(separator + content, cursor)) {
23
+ taken.add(message.clientId);
24
+ cursor += separator.length + content.length;
25
+ }
26
+ }
27
+ return cursor === text.length ? taken : /* @__PURE__ */ new Set();
28
+ }
29
+ var queuedMessages = {
30
+ add: (q, responseId, message) => ({
31
+ ...q,
32
+ [responseId]: [...q[responseId] ?? [], message]
33
+ }),
34
+ acknowledge: (q, clientId, serverId) => mapQueues(
35
+ q,
36
+ (messages) => messages.map((m) => m.clientId === clientId ? { ...m, serverId, acknowledged: true } : m)
37
+ ),
38
+ remove: (q, clientId) => mapQueues(q, (messages) => messages.filter((m) => m.clientId !== clientId)),
39
+ removeByServerId: (q, serverId) => mapQueues(q, (messages) => messages.filter((m) => m.serverId !== serverId)),
40
+ removeByContent: (q, responseId, content) => {
41
+ let removed = false;
42
+ return {
43
+ ...q,
44
+ [responseId]: (q[responseId] ?? []).filter((m) => {
45
+ if (!removed && m.content === content) {
46
+ removed = true;
47
+ return false;
48
+ }
49
+ return true;
50
+ })
51
+ };
52
+ },
53
+ /** Take out the prompts a steering interjection delivered into the run. */
54
+ consume: (q, responseId, combinedContent) => {
55
+ const messages = q[responseId] ?? [];
56
+ const consumed = findConsumedMessages(messages, combinedContent);
57
+ return { ...q, [responseId]: messages.filter((m) => !consumed.has(m.clientId)) };
58
+ },
59
+ clear: (q, responseId) => ({ ...q, [responseId]: [] }),
60
+ /** Move the entries still waiting on a finished turn to the turn that is now running. */
61
+ move: (q, fromResponseId, toResponseId) => {
62
+ const waiting = q[fromResponseId] ?? [];
63
+ if (fromResponseId === toResponseId || waiting.length === 0) return q;
64
+ return { ...q, [fromResponseId]: [], [toResponseId]: [...q[toResponseId] ?? [], ...waiting] };
65
+ },
66
+ /** Find a queued follow-up by its client id, under whichever turn holds it. */
67
+ find: (q, clientId) => Object.values(q).flat().find((m) => m.clientId === clientId)
68
+ };
69
+ var without = (record, key) => {
70
+ const next = { ...record };
71
+ delete next[key];
72
+ return next;
73
+ };
74
+ var agentControl = {
75
+ setState: (c, id, state) => ({
76
+ ...c,
77
+ agentControlStates: { ...c.agentControlStates, [id]: state }
78
+ }),
79
+ /** A probe answered: the latest answer, and nothing pending any more. */
80
+ setProbeAnswer: (c, id, probe) => ({
81
+ ...c,
82
+ agentProbeAnswers: { ...c.agentProbeAnswers, [id]: probe },
83
+ agentProbePending: { ...c.agentProbePending, [id]: false }
84
+ }),
85
+ setProbePending: (c, id, pending) => ({
86
+ ...c,
87
+ agentProbePending: { ...c.agentProbePending, [id]: pending }
88
+ }),
89
+ /** The turn is over: drop its control state. */
90
+ clear: (c, id) => ({
91
+ agentControlStates: without(c.agentControlStates, id),
92
+ agentProbeAnswers: without(c.agentProbeAnswers, id),
93
+ agentProbePending: without(c.agentProbePending, id)
94
+ })
95
+ };
96
+
97
+ // src/session/store.ts
98
+ var threadTabId = (tab) => tab.conversationId ?? "new";
99
+ var MAX_THREAD_TABS = 12;
100
+ var DEFAULT_DOCUMENT_VIEWER_STATE = {
101
+ tab: "pdf",
102
+ compareId: null,
103
+ tabRequest: null,
104
+ textScale: 1,
105
+ phonePdfChosen: false
106
+ };
107
+ var EMPTY_SESSION_STATE = {
108
+ workspaceId: null,
109
+ workspaceStatus: "closed",
110
+ conversationId: null,
111
+ viewingDocument: null,
112
+ documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,
113
+ selectedDocumentIds: [],
114
+ generating: {},
115
+ paMode: false,
116
+ conversationDocuments: {},
117
+ conversationDocumentAutoAdd: {},
118
+ conversationFacts: {},
119
+ pinnedDocumentId: null,
120
+ cursor: null,
121
+ suggestedQuery: null,
122
+ queuedMessages: {},
123
+ agentControlStates: {},
124
+ agentProbeAnswers: {},
125
+ agentProbePending: {},
126
+ drafts: {},
127
+ editingMessageId: null,
128
+ deepLinkMessageId: null,
129
+ activeCitationKey: null,
130
+ chatModel: void 0,
131
+ chatModelName: void 0,
132
+ threadTabs: [],
133
+ activeThreadTabId: null,
134
+ newConversationAssistantMode: "always",
135
+ pendingTools: null,
136
+ autoSendDraft: false,
137
+ agentChatOwners: {},
138
+ newAgentChat: null,
139
+ messageTimers: {}
140
+ };
141
+ var selectViewingDocumentId = (state) => state.viewingDocument ? parseVersionRef(state.viewingDocument.id).docId : null;
142
+ var conversationKey = (state) => state.conversationId ?? "new";
143
+ var selectDraft = (state) => state.drafts[conversationKey(state)] ?? "";
144
+ var selectIsGenerating = (conversationId) => (state) => !!conversationId && !!state.generating[conversationId]?.isGenerating;
145
+ function nextViewingDocument(current, input) {
146
+ if (!input) return null;
147
+ const same = current?.id === input.id;
148
+ return {
149
+ id: input.id,
150
+ page: input.page !== void 0 ? input.page : same ? current?.page ?? null : null,
151
+ passageId: input.passageId !== void 0 ? input.passageId : current?.passageId ?? null
152
+ };
153
+ }
154
+ function withoutNew(record) {
155
+ const { new: _new, ...saved } = record;
156
+ return saved;
157
+ }
158
+ function createArbiSessionStore(initial = {}, { draftStorage } = {}) {
159
+ let state = { ...EMPTY_SESSION_STATE, ...initial };
160
+ const listeners = /* @__PURE__ */ new Set();
161
+ const update = (patch) => {
162
+ state = { ...state, ...patch };
163
+ listeners.forEach((listener) => listener());
164
+ };
165
+ let preEdit = { draft: "", cursor: null };
166
+ let draftsRestored = !draftStorage;
167
+ let draftsOwner = draftStorage?.owner() ?? null;
168
+ const restoreDrafts = () => {
169
+ if (!draftStorage) return;
170
+ const owner = draftStorage.owner();
171
+ if (owner !== draftsOwner) {
172
+ if (draftsOwner !== null) update({ drafts: {} });
173
+ draftsOwner = owner;
174
+ draftsRestored = false;
175
+ }
176
+ if (draftsRestored) return;
177
+ draftsRestored = true;
178
+ void draftStorage.load().then(
179
+ (saved) => {
180
+ if (saved && draftStorage.owner() === owner)
181
+ update({ drafts: { ...saved, ...state.drafts } });
182
+ else draftsRestored = false;
183
+ },
184
+ () => {
185
+ draftsRestored = false;
186
+ }
187
+ );
188
+ };
189
+ draftStorage?.onClear(() => {
190
+ draftsRestored = false;
191
+ draftsOwner = null;
192
+ preEdit = { draft: "", cursor: null };
193
+ if (Object.keys(state.drafts).length > 0) update({ drafts: {} });
194
+ });
195
+ restoreDrafts();
196
+ const setDrafts = (drafts) => {
197
+ update({ drafts });
198
+ draftStorage?.save(drafts);
199
+ };
200
+ const setDraftOf = (key, text) => {
201
+ if ((state.drafts[key] ?? "") === text) return;
202
+ const drafts = { ...state.drafts };
203
+ if (text) drafts[key] = text;
204
+ else delete drafts[key];
205
+ setDrafts(drafts);
206
+ };
207
+ return {
208
+ getState: () => state,
209
+ subscribe: (listener) => {
210
+ listeners.add(listener);
211
+ return () => listeners.delete(listener);
212
+ },
213
+ setWorkspaceId: (workspaceId) => {
214
+ if (state.workspaceId !== workspaceId) update({ workspaceId });
215
+ restoreDrafts();
216
+ },
217
+ setWorkspaceStatus: (workspaceStatus) => {
218
+ if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus });
219
+ },
220
+ leaveWorkspace: () => {
221
+ Object.values(state.generating).forEach((generation) => generation.abortController?.abort());
222
+ update({
223
+ workspaceStatus: "closed",
224
+ conversationId: null,
225
+ cursor: null,
226
+ viewingDocument: null,
227
+ selectedDocumentIds: [],
228
+ generating: {},
229
+ // Saved conversations keep their documents; the unsent new chat's belong to this workspace.
230
+ conversationDocuments: withoutNew(state.conversationDocuments),
231
+ conversationDocumentAutoAdd: withoutNew(state.conversationDocumentAutoAdd),
232
+ conversationFacts: {},
233
+ pinnedDocumentId: null,
234
+ newAgentChat: null,
235
+ messageTimers: {},
236
+ threadTabs: [],
237
+ activeThreadTabId: null
238
+ });
239
+ },
240
+ setConversationId: (conversationId) => {
241
+ if (state.conversationId !== conversationId)
242
+ update({ conversationId, cursor: null, editingMessageId: null });
243
+ },
244
+ setViewingDocument: (input) => update({ viewingDocument: nextViewingDocument(state.viewingDocument, input) }),
245
+ setDocumentViewer: (change) => {
246
+ const next = { ...state.documentViewer, ...change };
247
+ const keys = Object.keys(change);
248
+ if (keys.some((key) => next[key] !== state.documentViewer[key]))
249
+ update({ documentViewer: next });
250
+ },
251
+ setSelectedDocumentIds: (ids) => update({ selectedDocumentIds: ids }),
252
+ setConversationGenerating: (conversationId, isGenerating, abortController = null) => {
253
+ const current = state.generating[conversationId];
254
+ update({
255
+ generating: {
256
+ ...state.generating,
257
+ [conversationId]: {
258
+ ...current,
259
+ isGenerating,
260
+ error: isGenerating ? null : current?.error ?? null,
261
+ startTime: isGenerating ? Date.now() : null,
262
+ streamingAssistantId: isGenerating ? current?.streamingAssistantId ?? null : null,
263
+ backendElapsed: isGenerating ? current?.backendElapsed ?? null : null,
264
+ abortController
265
+ }
266
+ }
267
+ });
268
+ },
269
+ setStreamingAssistantId: (conversationId, streamingAssistantId, startTime = Date.now()) => {
270
+ const current = state.generating[conversationId];
271
+ update({
272
+ generating: {
273
+ ...state.generating,
274
+ [conversationId]: {
275
+ ...current ?? { isGenerating: false, error: null },
276
+ streamingAssistantId,
277
+ startTime
278
+ }
279
+ }
280
+ });
281
+ },
282
+ setBackendElapsed: (conversationId, backendElapsed) => {
283
+ const current = state.generating[conversationId] ?? {
284
+ isGenerating: false,
285
+ error: null,
286
+ startTime: null
287
+ };
288
+ update({
289
+ generating: { ...state.generating, [conversationId]: { ...current, backendElapsed } }
290
+ });
291
+ },
292
+ moveConversation: (fromId, toId) => {
293
+ const move = (record) => {
294
+ const next = { ...record };
295
+ if (fromId in next) {
296
+ next[toId] = next[fromId];
297
+ delete next[fromId];
298
+ }
299
+ return next;
300
+ };
301
+ update({
302
+ generating: move(state.generating),
303
+ conversationDocuments: move(state.conversationDocuments),
304
+ conversationDocumentAutoAdd: move(state.conversationDocumentAutoAdd),
305
+ conversationFacts: move(state.conversationFacts),
306
+ conversationId: state.conversationId ?? toId,
307
+ // The new chat's tab is now the conversation's.
308
+ threadTabs: state.threadTabs.map(
309
+ (tab) => threadTabId(tab) === fromId ? { conversationId: toId } : tab
310
+ ),
311
+ activeThreadTabId: state.activeThreadTabId === fromId ? toId : state.activeThreadTabId
312
+ });
313
+ if (fromId in state.drafts) setDrafts(move(state.drafts));
314
+ },
315
+ setConversationFacts: (conversationId, factIds) => update({ conversationFacts: { ...state.conversationFacts, [conversationId]: factIds } }),
316
+ setPinnedDocumentId: (pinnedDocumentId) => update({ pinnedDocumentId }),
317
+ setCursor: (cursor) => {
318
+ if (state.cursor !== cursor) update({ cursor });
319
+ },
320
+ setSuggestedQuery: (suggestedQuery) => update({ suggestedQuery }),
321
+ addQueuedMessage: (id, message) => update({ queuedMessages: queuedMessages.add(state.queuedMessages, id, message) }),
322
+ acknowledgeQueuedMessage: (clientId, serverId) => update({
323
+ queuedMessages: queuedMessages.acknowledge(state.queuedMessages, clientId, serverId)
324
+ }),
325
+ removeQueuedMessage: (clientId) => update({ queuedMessages: queuedMessages.remove(state.queuedMessages, clientId) }),
326
+ removeQueuedMessageByServerId: (serverId) => update({ queuedMessages: queuedMessages.removeByServerId(state.queuedMessages, serverId) }),
327
+ consumeQueuedMessage: (id, content) => update({ queuedMessages: queuedMessages.consume(state.queuedMessages, id, content) }),
328
+ clearQueuedMessages: (id) => update({ queuedMessages: queuedMessages.clear(state.queuedMessages, id) }),
329
+ moveQueuedMessages: (from, to) => update({ queuedMessages: queuedMessages.move(state.queuedMessages, from, to) }),
330
+ setAgentControlState: (id, control) => update(agentControl.setState(state, id, control)),
331
+ setAgentProbeAnswer: (id, probe) => update(agentControl.setProbeAnswer(state, id, probe)),
332
+ setAgentProbePending: (id, pending) => update(agentControl.setProbePending(state, id, pending)),
333
+ clearAgentControl: (id) => update(agentControl.clear(state, id)),
334
+ setDraft: (text) => setDraftOf(conversationKey(state), text),
335
+ setChatModel: (chatModel) => {
336
+ if (state.chatModel !== chatModel) update({ chatModel });
337
+ },
338
+ openThreadTab: (conversationId) => {
339
+ const id = conversationId ?? "new";
340
+ const others = state.threadTabs.filter((tab) => threadTabId(tab) !== id);
341
+ const threadTabs = [...others, { conversationId }].slice(-MAX_THREAD_TABS);
342
+ update({ threadTabs, activeThreadTabId: id });
343
+ if (state.conversationId !== conversationId)
344
+ update({ conversationId, cursor: null, editingMessageId: null });
345
+ return id;
346
+ },
347
+ closeThreadTab: (tabId) => {
348
+ const threadTabs = state.threadTabs.filter((tab) => threadTabId(tab) !== tabId);
349
+ if (threadTabs.length === state.threadTabs.length) return;
350
+ if (state.activeThreadTabId !== tabId) return update({ threadTabs });
351
+ const next = threadTabs.at(-1);
352
+ update({ threadTabs, activeThreadTabId: next ? threadTabId(next) : null });
353
+ if (next && state.conversationId !== next.conversationId)
354
+ update({ conversationId: next.conversationId, cursor: null, editingMessageId: null });
355
+ },
356
+ selectThreadTab: (tabId) => {
357
+ if (tabId === null) {
358
+ if (state.activeThreadTabId !== null) update({ activeThreadTabId: null });
359
+ return;
360
+ }
361
+ const tab = state.threadTabs.find((t) => threadTabId(t) === tabId);
362
+ if (!tab) return;
363
+ update({ activeThreadTabId: tabId });
364
+ if (state.conversationId !== tab.conversationId)
365
+ update({ conversationId: tab.conversationId, cursor: null, editingMessageId: null });
366
+ },
367
+ setChatModelName: (chatModelName) => {
368
+ if (state.chatModelName !== chatModelName) update({ chatModelName });
369
+ },
370
+ setNewConversationAssistantMode: (newConversationAssistantMode) => {
371
+ if (state.newConversationAssistantMode !== newConversationAssistantMode)
372
+ update({ newConversationAssistantMode });
373
+ },
374
+ setNewAgentChat: (newAgentChat) => {
375
+ const current = state.newAgentChat;
376
+ if (current?.agentId !== newAgentChat?.agentId || current?.workspaceId !== newAgentChat?.workspaceId)
377
+ update({ newAgentChat });
378
+ },
379
+ startEditing: (messageId, content) => {
380
+ preEdit = { draft: selectDraft(state), cursor: state.cursor };
381
+ update({ editingMessageId: messageId });
382
+ setDraftOf(conversationKey(state), content);
383
+ },
384
+ cancelEditing: () => {
385
+ if (!state.editingMessageId) return;
386
+ update({ editingMessageId: null, cursor: preEdit.cursor });
387
+ setDraftOf(conversationKey(state), preEdit.draft);
388
+ preEdit = { draft: "", cursor: null };
389
+ },
390
+ completeEditing: () => {
391
+ preEdit = { draft: "", cursor: null };
392
+ if (state.editingMessageId) update({ editingMessageId: null });
393
+ },
394
+ setDeepLinkMessageId: (deepLinkMessageId) => {
395
+ if (state.deepLinkMessageId !== deepLinkMessageId) update({ deepLinkMessageId });
396
+ },
397
+ setActiveCitationKey: (activeCitationKey) => {
398
+ if (state.activeCitationKey !== activeCitationKey) update({ activeCitationKey });
399
+ },
400
+ setPendingTools: (pendingTools) => update({ pendingTools }),
401
+ setAutoSendDraft: (autoSendDraft) => {
402
+ if (state.autoSendDraft !== autoSendDraft) update({ autoSendDraft });
403
+ },
404
+ setAgentChatOwner: (conversationId, agentId) => update({ agentChatOwners: { ...state.agentChatOwners, [conversationId]: agentId } }),
405
+ setMessageTimer: (key, timer) => update({ messageTimers: { ...state.messageTimers, [key]: timer } }),
406
+ clearMessageTimer: (key) => {
407
+ if (!(key in state.messageTimers)) return;
408
+ const messageTimers = { ...state.messageTimers };
409
+ delete messageTimers[key];
410
+ update({ messageTimers });
411
+ },
412
+ setConversationError: (conversationId, error, lastFailedMessage) => {
413
+ const current = state.generating[conversationId];
414
+ update({
415
+ generating: {
416
+ ...state.generating,
417
+ [conversationId]: {
418
+ ...current,
419
+ isGenerating: false,
420
+ error,
421
+ startTime: current?.startTime ?? null,
422
+ lastFailedMessage: lastFailedMessage ?? current?.lastFailedMessage ?? null
423
+ }
424
+ }
425
+ });
426
+ },
427
+ clearConversationError: (conversationId) => {
428
+ const current = state.generating[conversationId];
429
+ update({
430
+ generating: {
431
+ ...state.generating,
432
+ [conversationId]: {
433
+ ...current ?? { isGenerating: false, startTime: null },
434
+ error: null,
435
+ lastFailedMessage: null
436
+ }
437
+ }
438
+ });
439
+ },
440
+ abortConversationGeneration: (conversationId) => {
441
+ const current = state.generating[conversationId];
442
+ current?.abortController?.abort();
443
+ update({
444
+ generating: {
445
+ ...state.generating,
446
+ [conversationId]: {
447
+ ...current ?? { error: null, startTime: null },
448
+ isGenerating: false,
449
+ abortController: null
450
+ }
451
+ }
452
+ });
453
+ },
454
+ startNewConversation: () => update({ conversationId: null, cursor: null, editingMessageId: null }),
455
+ setPaMode: (paMode) => {
456
+ if (state.paMode !== paMode) update({ paMode });
457
+ },
458
+ setConversationDocuments: (conversationId, documents, autoAdd = false) => update({
459
+ conversationDocuments: { ...state.conversationDocuments, [conversationId]: documents },
460
+ conversationDocumentAutoAdd: {
461
+ ...state.conversationDocumentAutoAdd,
462
+ [conversationId]: autoAdd
463
+ }
464
+ })
465
+ };
466
+ }
467
+ var SAVE_DELAY_MS = 500;
468
+ var encoder = new TextEncoder();
469
+ var decoder = new TextDecoder();
470
+ function parseStored(raw) {
471
+ if (!raw) return null;
472
+ try {
473
+ const parsed = JSON.parse(raw);
474
+ return parsed && typeof parsed.owner === "string" && typeof parsed.sealed === "string" ? { owner: parsed.owner, sealed: parsed.sealed } : null;
475
+ } catch {
476
+ return null;
477
+ }
478
+ }
479
+ var storages = /* @__PURE__ */ new Set();
480
+ function clearSealedDrafts() {
481
+ for (const storage of [...storages]) storage.clear();
482
+ }
483
+ function createSealedDraftStorage({
484
+ key = "arbi-drafts",
485
+ storage = typeof localStorage === "undefined" ? void 0 : localStorage,
486
+ owner
487
+ }) {
488
+ let timer;
489
+ let generation = 0;
490
+ const listeners = /* @__PURE__ */ new Set();
491
+ const remove = () => {
492
+ try {
493
+ storage?.removeItem(key);
494
+ } catch {
495
+ }
496
+ };
497
+ const write = async (drafts, written) => {
498
+ if (!storage) return;
499
+ try {
500
+ const user = owner();
501
+ if (!user) return;
502
+ if (Object.keys(drafts).length === 0) {
503
+ if (parseStored(storage.getItem(key))?.owner === user) storage.removeItem(key);
504
+ return;
505
+ }
506
+ const keypair = await getUserEncryptionKeypair();
507
+ if (!keypair || written !== generation || owner() !== user) return;
508
+ const plain = Uint8Array.from(encoder.encode(JSON.stringify(drafts)));
509
+ const record = {
510
+ owner: user,
511
+ sealed: sealedBoxEncrypt(plain, keypair.publicKey)
512
+ };
513
+ storage.setItem(key, JSON.stringify(record));
514
+ } catch {
515
+ }
516
+ };
517
+ const draftStorage = {
518
+ owner,
519
+ load: async () => {
520
+ const user = owner();
521
+ if (!user) return null;
522
+ const keypair = await getUserEncryptionKeypair();
523
+ if (!keypair || owner() !== user) return null;
524
+ try {
525
+ const raw = storage?.getItem(key) ?? null;
526
+ if (!raw) return {};
527
+ const stored = parseStored(raw);
528
+ if (!stored || stored.owner !== user) {
529
+ remove();
530
+ return {};
531
+ }
532
+ const plain = sealedBoxDecrypt(stored.sealed, keypair.secretKey);
533
+ const drafts = JSON.parse(decoder.decode(plain));
534
+ if (!drafts || typeof drafts !== "object") return {};
535
+ return Object.fromEntries(
536
+ Object.entries(drafts).filter((entry) => {
537
+ return typeof entry[1] === "string";
538
+ })
539
+ );
540
+ } catch {
541
+ return {};
542
+ }
543
+ },
544
+ save: (drafts) => {
545
+ clearTimeout(timer);
546
+ const written = generation;
547
+ timer = setTimeout(() => void write(drafts, written), SAVE_DELAY_MS);
548
+ },
549
+ clear: () => {
550
+ clearTimeout(timer);
551
+ timer = void 0;
552
+ generation++;
553
+ remove();
554
+ for (const listener of [...listeners]) listener();
555
+ },
556
+ onClear: (listener) => {
557
+ listeners.add(listener);
558
+ return () => listeners.delete(listener);
559
+ }
560
+ };
561
+ storages.add(draftStorage);
562
+ return draftStorage;
563
+ }
564
+ function signedInUser(host) {
565
+ const state = host.arbi?.session?.getState();
566
+ return state?.signedIn && state.userExtId ? state.userExtId : null;
567
+ }
568
+ var createOwnStore = (host) => createArbiSessionStore(
569
+ {},
570
+ { draftStorage: createSealedDraftStorage({ owner: () => signedInUser(host) }) }
571
+ );
572
+ var moduleDefault = null;
573
+ var defaultStore = () => moduleDefault ??= createArbiSessionStore();
574
+ function useArbiSessionStore() {
575
+ const host = useArbiHost();
576
+ if (host.session) return host.session;
577
+ const own = host[OWN_SESSION_SLOT];
578
+ if (own) return own.current ??= createOwnStore(host);
579
+ return defaultStore();
580
+ }
581
+ function useArbiSessionState(selector) {
582
+ const store = useArbiSessionStore();
583
+ const select = () => selector(store.getState());
584
+ return useSyncExternalStore(store.subscribe, select, select);
585
+ }
586
+ var SIGNED_OUT = {
587
+ status: "signed-out",
588
+ user: null,
589
+ isSso: false,
590
+ hasToken: false,
591
+ serverSessionKey: null
592
+ };
593
+ var noSubscription = () => () => {
594
+ };
595
+ function useArbiSession() {
596
+ return useSignedInSession(useArbiHost().arbi?.session ?? null);
597
+ }
598
+ function useSignedInSession(session) {
599
+ const state = useSyncExternalStore(
600
+ session ? session.subscribe : noSubscription,
601
+ () => session?.getState() ?? null,
602
+ () => session?.getState() ?? null
603
+ );
604
+ return useMemo(
605
+ () => state?.signedIn ? {
606
+ status: "signed-in",
607
+ user: state.user,
608
+ isSso: state.isSsoMode,
609
+ hasToken: !!state.accessToken,
610
+ serverSessionKey: state.serverSessionKey
611
+ } : { ...SIGNED_OUT, isSso: state?.isSsoMode ?? false },
612
+ [state]
613
+ );
614
+ }
615
+
616
+ // src/usage-metered.ts
617
+ function isUsageMetered(usage, subscription) {
618
+ const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0;
619
+ return !(empty && subscription === "dev");
620
+ }
621
+ function useWorkspaces(options) {
622
+ const arbi = useArbi();
623
+ return useQuery({
624
+ queryKey: arbiQueryKeys.workspaces(),
625
+ queryFn: () => arbi.workspaces.list(),
626
+ enabled: options?.enabled ?? arbi.isLoggedIn
627
+ });
628
+ }
629
+ function useDocumentVersionList(docId, options) {
630
+ const arbi = useArbi();
631
+ return useQuery({
632
+ queryKey: arbiQueryKeys.documentVersions(docId ?? ""),
633
+ queryFn: () => arbi.documents.versions(docId),
634
+ enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
635
+ });
636
+ }
637
+ function useConversations(workspaceId, options) {
638
+ const arbi = useArbi();
639
+ const live = options?.live === true;
640
+ return useQuery({
641
+ queryKey: arbiQueryKeys.conversations(workspaceId ?? ""),
642
+ queryFn: () => arbi.conversations.list(),
643
+ enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,
644
+ placeholderData: (previous) => previous,
645
+ ...live ? {
646
+ refetchInterval: (query) => query.state.data?.some((conversation) => conversation.status === "generating") ? 3e3 : 15e3
647
+ } : { staleTime: Infinity, refetchOnMount: false, refetchOnReconnect: false }
648
+ });
649
+ }
650
+ function useBuiltinCommands() {
651
+ const arbi = useArbi();
652
+ const query = useQuery({
653
+ queryKey: arbiQueryKeys.assistantCommands(),
654
+ queryFn: () => arbi.assistant.commands(),
655
+ staleTime: 30 * 1e3,
656
+ enabled: arbi.isLoggedIn
657
+ });
658
+ const commands = useMemo(() => query.data ?? [], [query.data]);
659
+ return { commands, isLoading: query.isLoading };
660
+ }
661
+ function useMessageDetails(messageId, options) {
662
+ const arbi = useArbi();
663
+ return useQuery({
664
+ queryKey: arbiQueryKeys.messageDetails(messageId ?? ""),
665
+ queryFn: () => arbi.conversations.getMessage(messageId),
666
+ enabled: (options?.enabled ?? true) && !!messageId && arbi.isLoggedIn
667
+ });
668
+ }
669
+ function useConversationThreads(conversationId, options) {
670
+ const arbi = useArbi();
671
+ const session = useArbiSessionStore();
672
+ return useQuery({
673
+ queryKey: arbiQueryKeys.conversationThreads(conversationId ?? ""),
674
+ queryFn: async () => {
675
+ try {
676
+ return await arbi.conversations.getThreads(conversationId);
677
+ } catch (error) {
678
+ if (error instanceof ArbiApiError && error.status === 404) {
679
+ return { conversation_ext_id: conversationId, threads: [] };
680
+ }
681
+ throw error;
682
+ }
683
+ },
684
+ enabled: (options?.enabled ?? true) && !!conversationId && arbi.hasWorkspace,
685
+ staleTime: 2 * 60 * 1e3,
686
+ refetchOnWindowFocus: () => session.getState().generating[conversationId ?? ""]?.isGenerating ? false : "always",
687
+ refetchInterval: options?.live ? 3e3 : false
688
+ });
689
+ }
690
+ var tagListKey = (query) => [
691
+ query.kind ? `kind:${query.kind}` : "",
692
+ query.parentId ? `parent:${query.parentId}` : "",
693
+ query.ids?.length ? `ids:${query.ids.join(",")}` : "",
694
+ query.include?.length ? `include:${query.include.join(",")}` : "",
695
+ query.linksLimit !== void 0 ? `links:${query.linksLimit}` : ""
696
+ ].filter(Boolean).join("|");
697
+ function useTags(workspaceId, options) {
698
+ const arbi = useArbi();
699
+ const { enabled, ...query } = options ?? {};
700
+ const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : "");
701
+ const key = tagListKey(query);
702
+ return useQuery({
703
+ queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),
704
+ queryFn: () => arbi.tags.list(key ? query : void 0),
705
+ enabled: (enabled ?? true) && !!workspace && arbi.hasWorkspace && (query.ids === void 0 || query.ids.length > 0),
706
+ ...key ? {} : { staleTime: Infinity }
707
+ });
708
+ }
709
+ function useThumbnails(docIds, options) {
710
+ const arbi = useArbi();
711
+ return useQuery({
712
+ queryKey: arbiQueryKeys.thumbnails(docIds),
713
+ queryFn: () => arbi.documents.getThumbnails(docIds),
714
+ enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,
715
+ staleTime: 5 * 6e4
716
+ });
717
+ }
718
+ function useParsedDocument(docId, stage = "final", options) {
719
+ const arbi = useArbi();
720
+ return useQuery({
721
+ queryKey: arbiQueryKeys.parsedDoc(docId ?? "", stage),
722
+ queryFn: () => {
723
+ const { docId: id, version } = parseVersionRef(docId);
724
+ return arbi.documents.getParsedContent(
725
+ id,
726
+ stage,
727
+ version ?? void 0
728
+ );
729
+ },
730
+ enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace
731
+ });
732
+ }
733
+ function useAssistantQuery() {
734
+ const arbi = useArbi();
735
+ return useMutation({
736
+ mutationFn: ({ request, handlers }) => arbi.assistant.ask(request, handlers)
737
+ });
738
+ }
739
+ function useAgents(options) {
740
+ const arbi = useArbi();
741
+ return useQuery({
742
+ queryKey: arbiQueryKeys.agents(),
743
+ queryFn: () => arbi.agents.list(),
744
+ enabled: (options?.enabled ?? true) && arbi.isLoggedIn
745
+ });
746
+ }
747
+ function useDeleteAgents() {
748
+ const arbi = useArbi();
749
+ const qc = useQueryClient();
750
+ return useMutation({
751
+ mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),
752
+ onSuccess: (_result, { agentExtIds }) => {
753
+ for (const id of agentExtIds) {
754
+ qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) });
755
+ qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) });
756
+ }
757
+ return Promise.all([
758
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),
759
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),
760
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),
761
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() })
762
+ ]);
763
+ }
764
+ });
765
+ }
766
+ function useHealth(options) {
767
+ const arbi = useArbi();
768
+ return useQuery({
769
+ queryKey: arbiQueryKeys.health(),
770
+ queryFn: () => arbi.health.check(),
771
+ enabled: options?.enabled
772
+ });
773
+ }
774
+ function useAvailableModels(options) {
775
+ const arbi = useArbi();
776
+ return useQuery({
777
+ queryKey: arbiQueryKeys.availableModels(),
778
+ queryFn: () => arbi.health.models(),
779
+ staleTime: Infinity,
780
+ enabled: (options?.enabled ?? true) && arbi.isLoggedIn
781
+ });
782
+ }
783
+ function useConfigs(options) {
784
+ const arbi = useArbi();
785
+ return useQuery({
786
+ queryKey: arbiQueryKeys.configVersions(),
787
+ queryFn: () => arbi.agentConfig.list(),
788
+ enabled: options?.enabled ?? arbi.isLoggedIn
789
+ });
790
+ }
791
+ function useConfig(configId, options) {
792
+ const arbi = useArbi();
793
+ return useQuery({
794
+ queryKey: arbiQueryKeys.config(configId ?? ""),
795
+ queryFn: () => arbi.agentConfig.get(configId),
796
+ staleTime: 10 * 60 * 1e3,
797
+ enabled: (options?.enabled ?? true) && !!configId && arbi.isLoggedIn
798
+ });
799
+ }
800
+ function useActivity(options) {
801
+ const arbi = useArbi();
802
+ return useQuery({
803
+ queryKey: arbiQueryKeys.activity(),
804
+ queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),
805
+ enabled: options?.enabled ?? arbi.isLoggedIn
806
+ });
807
+ }
808
+ function useWorkspaceActivity(workspaceId, options) {
809
+ const arbi = useArbi();
810
+ return useInfiniteQuery({
811
+ queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ""),
812
+ queryFn: async ({ pageParam }) => {
813
+ await options?.beforeFetch?.();
814
+ return arbi.workspaces.activity(workspaceId, {
815
+ cursor: pageParam,
816
+ limit: options?.limit
817
+ });
818
+ },
819
+ initialPageParam: null,
820
+ getNextPageParam: (page) => page.next_cursor ?? void 0,
821
+ enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn
822
+ });
823
+ }
824
+ function useProjects(options) {
825
+ const arbi = useArbi();
826
+ return useQuery({
827
+ queryKey: arbiQueryKeys.projects(),
828
+ queryFn: () => arbi.projects.list(),
829
+ enabled: options?.enabled ?? arbi.isLoggedIn
830
+ });
831
+ }
832
+ function useProjectUsage(projectExtId, monthsBack = 0, options) {
833
+ const arbi = useArbi();
834
+ const usage = useQuery({
835
+ queryKey: arbiQueryKeys.projectUsage(projectExtId ?? "", monthsBack),
836
+ queryFn: () => arbi.projects.usage(projectExtId, monthsBack),
837
+ enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
838
+ });
839
+ const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) });
840
+ const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription;
841
+ const metered = usage.data ? isUsageMetered(usage.data, subscription) : void 0;
842
+ return { ...usage, metered };
843
+ }
844
+ function useProjectsUsage(projectExtIds, monthsBack = 0, options) {
845
+ const arbi = useArbi();
846
+ const enabled = (options?.enabled ?? true) && arbi.isLoggedIn;
847
+ const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 });
848
+ const results = useQueries({
849
+ queries: projectExtIds.map((id) => ({
850
+ queryKey: arbiQueryKeys.projectUsage(id, monthsBack),
851
+ queryFn: () => arbi.projects.usage(id, monthsBack),
852
+ enabled: enabled && !!id
853
+ }))
854
+ });
855
+ const signature = results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join("|") + `#${projects.dataUpdatedAt}`;
856
+ return useMemo(() => {
857
+ const dailyMap = /* @__PURE__ */ new Map();
858
+ const modelMap = /* @__PURE__ */ new Map();
859
+ let totalGbp = 0;
860
+ let anyData = false;
861
+ let anyMetered = false;
862
+ let totalTokens = 0;
863
+ let totalRequests = 0;
864
+ results.forEach((r, i) => {
865
+ const d = r.data;
866
+ if (!d) return;
867
+ anyData = true;
868
+ const subscription = projects.data?.find(
869
+ (p) => p.external_id === projectExtIds[i]
870
+ )?.subscription;
871
+ if (isUsageMetered(d, subscription)) anyMetered = true;
872
+ totalGbp += d.total_spend ?? 0;
873
+ totalTokens += d.total_tokens ?? 0;
874
+ totalRequests += d.total_requests ?? 0;
875
+ for (const day of d.daily ?? []) {
876
+ const cur = dailyMap.get(day.date) ?? {
877
+ date: day.date,
878
+ gbp: 0,
879
+ totalTokens: 0,
880
+ apiRequests: 0
881
+ };
882
+ cur.gbp += day.spend ?? 0;
883
+ cur.totalTokens += day.total_tokens ?? 0;
884
+ cur.apiRequests += day.api_requests ?? 0;
885
+ dailyMap.set(day.date, cur);
886
+ }
887
+ for (const [model, mg] of Object.entries(d.model_groups ?? {})) {
888
+ const cur = modelMap.get(model) ?? {
889
+ model,
890
+ gbp: 0,
891
+ totalTokens: 0,
892
+ promptTokens: 0,
893
+ completionTokens: 0,
894
+ successfulRequests: 0
895
+ };
896
+ cur.gbp += mg.spend ?? 0;
897
+ cur.totalTokens += mg.total_tokens ?? 0;
898
+ cur.promptTokens += mg.prompt_tokens ?? 0;
899
+ cur.completionTokens += mg.completion_tokens ?? 0;
900
+ cur.successfulRequests += mg.successful_requests ?? 0;
901
+ modelMap.set(model, cur);
902
+ }
903
+ });
904
+ return {
905
+ totalGbp,
906
+ totalTokens,
907
+ totalRequests,
908
+ daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),
909
+ modelGroups: [...modelMap.values()].sort(
910
+ (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens
911
+ ),
912
+ metered: !anyData || anyMetered,
913
+ isLoading: results.some((r) => r.isLoading),
914
+ isError: results.some((r) => r.isError)
915
+ };
916
+ }, [signature]);
917
+ }
918
+ function useProjectInvoices(projectExtId, options) {
919
+ const arbi = useArbi();
920
+ return useQuery({
921
+ queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ""),
922
+ queryFn: () => arbi.projects.invoices(projectExtId),
923
+ enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
924
+ });
925
+ }
926
+ function useCurrentUser(options) {
927
+ const arbi = useArbi();
928
+ return useQuery({
929
+ queryKey: arbiQueryKeys.currentUser(),
930
+ queryFn: () => arbi.user.me(),
931
+ enabled: options?.enabled ?? arbi.isLoggedIn,
932
+ refetchOnWindowFocus: true,
933
+ staleTime: 3e4
934
+ });
935
+ }
936
+ function useFirmPool(options) {
937
+ const arbi = useArbi();
938
+ return useQuery({
939
+ queryKey: arbiQueryKeys.firmPool(),
940
+ queryFn: () => arbi.firm.pool(),
941
+ enabled: options?.enabled ?? arbi.isLoggedIn,
942
+ retry: false,
943
+ refetchOnWindowFocus: true,
944
+ staleTime: 6e4
945
+ });
946
+ }
947
+ function useTopUpFirmPool() {
948
+ const arbi = useArbi();
949
+ const queryClient = useQueryClient();
950
+ return useMutation({
951
+ mutationFn: (aiAddons) => arbi.firm.topUp(aiAddons),
952
+ onSuccess: (result) => {
953
+ queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool);
954
+ }
955
+ });
956
+ }
957
+ var PROJECT_CREATION_DENIED_REASON = "Only members of your firm can create projects and workspaces.";
958
+ function useCanCreateProjects() {
959
+ const user = useCurrentUser();
960
+ const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess });
961
+ const membership = workspaces?.map((w) => w.external_id).join(",");
962
+ const { refetch } = user;
963
+ const seen = useRef(void 0);
964
+ useEffect(() => {
965
+ if (membership === void 0 || membership === seen.current) return;
966
+ const first = seen.current === void 0;
967
+ seen.current = membership;
968
+ if (!first) void refetch();
969
+ }, [membership, refetch]);
970
+ return user.data?.can_create_projects;
971
+ }
972
+ function useUserUsageToday(options) {
973
+ const arbi = useArbi();
974
+ return useQuery({
975
+ queryKey: arbiQueryKeys.userUsageToday(),
976
+ queryFn: () => arbi.user.usageToday(),
977
+ enabled: (options?.enabled ?? true) && arbi.isLoggedIn,
978
+ refetchOnWindowFocus: true,
979
+ refetchOnMount: "always",
980
+ staleTime: 15e3
981
+ });
982
+ }
983
+
984
+ export { DEFAULT_DOCUMENT_VIEWER_STATE, EMPTY_SESSION_STATE, MAX_THREAD_TABS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, PROJECT_CREATION_DENIED_REASON, agentControl, clearSealedDrafts, conversationKey, createArbiSessionStore, createSealedDraftStorage, isUsageMetered, nextViewingDocument, queuedMessages, selectDraft, selectIsGenerating, selectViewingDocumentId, threadTabId, useActivity, useAgents, useArbiSession, useArbiSessionState, useArbiSessionStore, useAssistantQuery, useAvailableModels, useBuiltinCommands, useCanCreateProjects, useConfig, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocumentVersionList, useFirmPool, useHealth, useMessageDetails, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSignedInSession, useTags, useThumbnails, useTopUpFirmPool, useUserUsageToday, useWorkspaceActivity, useWorkspaces };
985
+ //# sourceMappingURL=chunk-MJNZLWJD.js.map
986
+ //# sourceMappingURL=chunk-MJNZLWJD.js.map