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