@assistant-ui/react 0.1.1 → 0.1.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (53) hide show
  1. package/package.json +6 -15
  2. package/dist/AssistantRuntime-BM_jVV3g.d.mts +0 -23
  3. package/dist/AssistantRuntime-CBMSAJqH.d.mts +0 -23
  4. package/dist/AssistantRuntime-C_BvM7ZT.d.ts +0 -23
  5. package/dist/AssistantRuntime-DELpXWfG.d.ts +0 -23
  6. package/dist/ModelConfigTypes-B9UY4zxv.d.mts +0 -55
  7. package/dist/ModelConfigTypes-B9UY4zxv.d.ts +0 -55
  8. package/dist/ModelConfigTypes-BF5HxVrH.d.mts +0 -55
  9. package/dist/ModelConfigTypes-BF5HxVrH.d.ts +0 -55
  10. package/dist/ModelConfigTypes-Cf3yjaDu.d.mts +0 -55
  11. package/dist/ModelConfigTypes-Cf3yjaDu.d.ts +0 -55
  12. package/dist/ModelConfigTypes-CzmXY3sn.d.mts +0 -55
  13. package/dist/ModelConfigTypes-CzmXY3sn.d.ts +0 -55
  14. package/dist/Thread-BMASJT4a.d.ts +0 -15
  15. package/dist/Thread-UEVsUmvl.d.mts +0 -15
  16. package/dist/chunk-3XZUKECF.mjs +0 -207
  17. package/dist/chunk-3XZUKECF.mjs.map +0 -1
  18. package/dist/chunk-4DQ2CIAD.mjs +0 -69
  19. package/dist/chunk-4DQ2CIAD.mjs.map +0 -1
  20. package/dist/chunk-5YONSDN4.mjs +0 -200
  21. package/dist/chunk-5YONSDN4.mjs.map +0 -1
  22. package/dist/chunk-CY4TTHR7.mjs +0 -76
  23. package/dist/chunk-CY4TTHR7.mjs.map +0 -1
  24. package/dist/chunk-DKAWDNW5.mjs +0 -22
  25. package/dist/chunk-DKAWDNW5.mjs.map +0 -1
  26. package/dist/chunk-GQKH2ADD.mjs +0 -165
  27. package/dist/chunk-GQKH2ADD.mjs.map +0 -1
  28. package/dist/chunk-J5LGTIGS.mjs +0 -10
  29. package/dist/chunk-J5LGTIGS.mjs.map +0 -1
  30. package/dist/chunk-NSBOH42A.mjs +0 -200
  31. package/dist/chunk-NSBOH42A.mjs.map +0 -1
  32. package/dist/chunk-X4HBDEFP.mjs +0 -30
  33. package/dist/chunk-X4HBDEFP.mjs.map +0 -1
  34. package/dist/experimental.d.mts +0 -86
  35. package/dist/experimental.d.ts +0 -86
  36. package/dist/experimental.js +0 -123
  37. package/dist/experimental.js.map +0 -1
  38. package/dist/experimental.mjs +0 -34
  39. package/dist/experimental.mjs.map +0 -1
  40. package/dist/index.d.mts +0 -289
  41. package/dist/index.d.ts +0 -289
  42. package/dist/index.js +0 -1500
  43. package/dist/index.js.map +0 -1
  44. package/dist/index.mjs +0 -1245
  45. package/dist/index.mjs.map +0 -1
  46. package/dist/internal-dlLjX30u.d.mts +0 -75
  47. package/dist/internal-dlLjX30u.d.ts +0 -75
  48. package/dist/internal.d.mts +0 -25
  49. package/dist/internal.d.ts +0 -25
  50. package/dist/internal.js +0 -225
  51. package/dist/internal.js.map +0 -1
  52. package/dist/internal.mjs +0 -10
  53. package/dist/internal.mjs.map +0 -1
package/dist/index.js DELETED
@@ -1,1500 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- ActionBarPrimitive: () => actionBar_exports,
34
- AssistantRuntimeProvider: () => AssistantRuntimeProvider,
35
- BranchPickerPrimitive: () => branchPicker_exports,
36
- ComposerPrimitive: () => composer_exports,
37
- ContentPartPrimitive: () => contentPart_exports,
38
- MessagePrimitive: () => message_exports,
39
- ThreadPrimitive: () => thread_exports,
40
- useBeginMessageEdit: () => useBeginMessageEdit,
41
- useCopyMessage: () => useCopyMessage,
42
- useGoToNextBranch: () => useGoToNextBranch,
43
- useGoToPreviousBranch: () => useGoToPreviousBranch,
44
- useLocalRuntime: () => useLocalRuntime,
45
- useReloadMessage: () => useReloadMessage
46
- });
47
- module.exports = __toCommonJS(src_exports);
48
-
49
- // src/actions/useCopyMessage.tsx
50
- var import_react4 = require("react");
51
-
52
- // src/context/MessageContext.ts
53
- var import_react = require("react");
54
- var MessageContext = (0, import_react.createContext)(null);
55
- var useMessageContext = () => {
56
- const context = (0, import_react.useContext)(MessageContext);
57
- if (!context)
58
- throw new Error(
59
- "This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />."
60
- );
61
- return context;
62
- };
63
-
64
- // src/utils/combined/useCombinedStore.ts
65
- var import_react3 = require("react");
66
-
67
- // src/utils/combined/createCombinedStore.ts
68
- var import_react2 = require("react");
69
- var createCombinedStore = (stores) => {
70
- const subscribe = (callback) => {
71
- const unsubscribes = stores.map((store) => store.subscribe(callback));
72
- return () => {
73
- for (const unsub of unsubscribes) {
74
- unsub();
75
- }
76
- };
77
- };
78
- return (selector) => {
79
- const getSnapshot = () => selector(...stores.map((store) => store.getState()));
80
- return (0, import_react2.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
81
- };
82
- };
83
-
84
- // src/utils/combined/useCombinedStore.ts
85
- var useCombinedStore = (stores, selector) => {
86
- const useCombined = (0, import_react3.useMemo)(() => createCombinedStore(stores), stores);
87
- return useCombined(selector);
88
- };
89
-
90
- // src/utils/getMessageText.tsx
91
- var getMessageText = (message) => {
92
- const textParts = message.content.filter(
93
- (part) => part.type === "text"
94
- );
95
- return textParts.map((part) => part.text).join("\n\n");
96
- };
97
-
98
- // src/actions/useCopyMessage.tsx
99
- var useCopyMessage = ({ copiedDuration = 3e3 }) => {
100
- const { useMessage, useComposer } = useMessageContext();
101
- const hasCopyableContent = useCombinedStore(
102
- [useMessage, useComposer],
103
- (m, c) => {
104
- return c.isEditing || m.message.content.some((c2) => c2.type === "text");
105
- }
106
- );
107
- const callback = (0, import_react4.useCallback)(() => {
108
- const { isEditing, value: composerValue } = useComposer.getState();
109
- const { message, setIsCopied } = useMessage.getState();
110
- const valueToCopy = isEditing ? composerValue : getMessageText(message);
111
- navigator.clipboard.writeText(valueToCopy);
112
- setIsCopied(true);
113
- setTimeout(() => setIsCopied(false), copiedDuration);
114
- }, [useComposer, useMessage, copiedDuration]);
115
- if (!hasCopyableContent) return null;
116
- return callback;
117
- };
118
-
119
- // src/actions/useReloadMessage.tsx
120
- var import_react6 = require("react");
121
-
122
- // src/context/ThreadContext.ts
123
- var import_react5 = require("react");
124
- var ThreadContext = (0, import_react5.createContext)(null);
125
- var useThreadContext = () => {
126
- const context = (0, import_react5.useContext)(ThreadContext);
127
- if (!context)
128
- throw new Error("This component must be used within an AssistantRuntimeProvider.");
129
- return context;
130
- };
131
-
132
- // src/actions/useReloadMessage.tsx
133
- var useReloadMessage = () => {
134
- const { useThread, useViewport } = useThreadContext();
135
- const { useMessage } = useMessageContext();
136
- const disabled = useCombinedStore(
137
- [useThread, useMessage],
138
- (t, m) => t.isRunning || m.message.role !== "assistant"
139
- );
140
- const callback = (0, import_react6.useCallback)(() => {
141
- const { parentId } = useMessage.getState();
142
- useThread.getState().startRun(parentId);
143
- useViewport.getState().scrollToBottom();
144
- }, [useMessage, useThread, useViewport]);
145
- if (disabled) return null;
146
- return callback;
147
- };
148
-
149
- // src/actions/useBeginMessageEdit.tsx
150
- var import_react7 = require("react");
151
- var useBeginMessageEdit = () => {
152
- const { useMessage, useComposer } = useMessageContext();
153
- const disabled = useCombinedStore(
154
- [useMessage, useComposer],
155
- (m, c) => m.message.role !== "user" || c.isEditing
156
- );
157
- const callback = (0, import_react7.useCallback)(() => {
158
- const { edit } = useComposer.getState();
159
- edit();
160
- }, [useComposer]);
161
- if (disabled) return null;
162
- return callback;
163
- };
164
-
165
- // src/actions/useGoToNextBranch.tsx
166
- var import_react8 = require("react");
167
- var useGoToNextBranch = () => {
168
- const { useThread } = useThreadContext();
169
- const { useMessage, useComposer } = useMessageContext();
170
- const disabled = useCombinedStore(
171
- [useMessage, useComposer],
172
- (m, c) => c.isEditing || m.branches.indexOf(m.message.id) + 1 >= m.branches.length
173
- );
174
- const callback = (0, import_react8.useCallback)(() => {
175
- const { message, branches } = useMessage.getState();
176
- useThread.getState().switchToBranch(branches[branches.indexOf(message.id) + 1]);
177
- }, [useMessage, useThread]);
178
- if (disabled) return null;
179
- return callback;
180
- };
181
-
182
- // src/actions/useGoToPreviousBranch.tsx
183
- var import_react9 = require("react");
184
- var useGoToPreviousBranch = () => {
185
- const { useThread } = useThreadContext();
186
- const { useMessage, useComposer } = useMessageContext();
187
- const disabled = useCombinedStore(
188
- [useMessage, useComposer],
189
- (m, c) => c.isEditing || m.branches.indexOf(m.message.id) <= 0
190
- );
191
- const callback = (0, import_react9.useCallback)(() => {
192
- const { message, branches } = useMessage.getState();
193
- useThread.getState().switchToBranch(branches[branches.indexOf(message.id) - 1]);
194
- }, [useMessage, useThread]);
195
- if (disabled) return null;
196
- return callback;
197
- };
198
-
199
- // src/primitives/thread/index.ts
200
- var thread_exports = {};
201
- __export(thread_exports, {
202
- Empty: () => ThreadEmpty,
203
- If: () => ThreadIf,
204
- Messages: () => ThreadMessages,
205
- Root: () => ThreadRoot,
206
- ScrollToBottom: () => ThreadScrollToBottom,
207
- Suggestion: () => ThreadSuggestion,
208
- Viewport: () => ThreadViewport
209
- });
210
-
211
- // src/primitives/thread/ThreadRoot.tsx
212
- var import_react_primitive = require("@radix-ui/react-primitive");
213
- var import_react10 = require("react");
214
- var import_jsx_runtime = require("react/jsx-runtime");
215
- var ThreadRoot = (0, import_react10.forwardRef)(
216
- (props, ref) => {
217
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_primitive.Primitive.div, { ...props, ref });
218
- }
219
- );
220
-
221
- // src/primitives/thread/ThreadIf.tsx
222
- var useThreadIf = (props) => {
223
- const { useThread } = useThreadContext();
224
- return useThread((thread) => {
225
- if (props.empty === true && thread.messages.length !== 0) return false;
226
- if (props.empty === false && thread.messages.length === 0) return false;
227
- if (props.running === true && !thread.isRunning) return false;
228
- if (props.running === false && thread.isRunning) return false;
229
- return true;
230
- });
231
- };
232
- var ThreadIf = ({ children, ...query }) => {
233
- const result = useThreadIf(query);
234
- return result ? children : null;
235
- };
236
-
237
- // src/primitives/thread/ThreadEmpty.tsx
238
- var import_jsx_runtime2 = require("react/jsx-runtime");
239
- var ThreadEmpty = ({ children }) => {
240
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ThreadIf, { empty: true, children });
241
- };
242
-
243
- // src/primitives/thread/ThreadViewport.tsx
244
- var import_primitive = require("@radix-ui/primitive");
245
- var import_react_compose_refs = require("@radix-ui/react-compose-refs");
246
- var import_react_primitive2 = require("@radix-ui/react-primitive");
247
- var import_react13 = require("react");
248
-
249
- // src/utils/hooks/useOnResizeContent.tsx
250
- var import_react_use_callback_ref = require("@radix-ui/react-use-callback-ref");
251
- var import_react11 = require("react");
252
- var useOnResizeContent = (ref, callback) => {
253
- const callbackRef = (0, import_react_use_callback_ref.useCallbackRef)(callback);
254
- (0, import_react11.useEffect)(() => {
255
- const el = ref.current;
256
- if (!el) return;
257
- const resizeObserver = new ResizeObserver(() => {
258
- callbackRef();
259
- });
260
- const mutationObserver = new MutationObserver((mutations) => {
261
- for (const mutation of mutations) {
262
- for (const node of mutation.addedNodes) {
263
- if (node instanceof Element) {
264
- resizeObserver.observe(node);
265
- }
266
- }
267
- for (const node of mutation.removedNodes) {
268
- if (node instanceof Element) {
269
- resizeObserver.unobserve(node);
270
- }
271
- }
272
- }
273
- callbackRef();
274
- });
275
- resizeObserver.observe(el);
276
- mutationObserver.observe(el, { childList: true });
277
- for (const child of el.children) {
278
- resizeObserver.observe(child);
279
- }
280
- return () => {
281
- resizeObserver.disconnect();
282
- mutationObserver.disconnect();
283
- };
284
- }, [ref.current, callbackRef]);
285
- };
286
-
287
- // src/utils/hooks/useOnScrollToBottom.tsx
288
- var import_react_use_callback_ref2 = require("@radix-ui/react-use-callback-ref");
289
- var import_react12 = require("react");
290
- var useOnScrollToBottom = (callback) => {
291
- const callbackRef = (0, import_react_use_callback_ref2.useCallbackRef)(callback);
292
- const { useViewport } = useThreadContext();
293
- (0, import_react12.useEffect)(() => {
294
- return useViewport.getState().onScrollToBottom(() => {
295
- callbackRef();
296
- });
297
- }, [useViewport, callbackRef]);
298
- };
299
-
300
- // src/primitives/thread/ThreadViewport.tsx
301
- var import_jsx_runtime3 = require("react/jsx-runtime");
302
- var ThreadViewport = (0, import_react13.forwardRef)(({ autoScroll = true, onScroll, children, ...rest }, forwardedRef) => {
303
- const messagesEndRef = (0, import_react13.useRef)(null);
304
- const divRef = (0, import_react13.useRef)(null);
305
- const ref = (0, import_react_compose_refs.useComposedRefs)(forwardedRef, divRef);
306
- const { useViewport } = useThreadContext();
307
- const firstRenderRef = (0, import_react13.useRef)(true);
308
- const isScrollingToBottomRef = (0, import_react13.useRef)(false);
309
- const lastScrollTop = (0, import_react13.useRef)(0);
310
- const scrollToBottom = () => {
311
- const div = messagesEndRef.current;
312
- if (!div || !autoScroll) return;
313
- const behavior = firstRenderRef.current ? "instant" : "auto";
314
- firstRenderRef.current = false;
315
- isScrollingToBottomRef.current = true;
316
- div.scrollIntoView({ behavior });
317
- };
318
- useOnResizeContent(divRef, () => {
319
- if (!isScrollingToBottomRef.current && !useViewport.getState().isAtBottom) {
320
- handleScroll();
321
- } else {
322
- scrollToBottom();
323
- }
324
- });
325
- useOnScrollToBottom(() => {
326
- scrollToBottom();
327
- });
328
- const handleScroll = () => {
329
- const div = divRef.current;
330
- if (!div) return;
331
- const isAtBottom = useViewport.getState().isAtBottom;
332
- const newIsAtBottom = div.scrollHeight - div.scrollTop <= div.clientHeight;
333
- if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {
334
- } else if (newIsAtBottom !== isAtBottom) {
335
- isScrollingToBottomRef.current = false;
336
- useViewport.setState({ isAtBottom: newIsAtBottom });
337
- }
338
- lastScrollTop.current = div.scrollTop;
339
- };
340
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
341
- import_react_primitive2.Primitive.div,
342
- {
343
- ...rest,
344
- onScroll: (0, import_primitive.composeEventHandlers)(onScroll, handleScroll),
345
- ref,
346
- children: [
347
- children,
348
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { ref: messagesEndRef })
349
- ]
350
- }
351
- );
352
- });
353
-
354
- // src/context/providers/MessageProvider.tsx
355
- var import_react14 = require("react");
356
- var import_zustand2 = require("zustand");
357
-
358
- // src/context/stores/MessageComposer.ts
359
- var import_zustand = require("zustand");
360
-
361
- // src/context/stores/BaseComposer.ts
362
- var makeBaseComposer = (set) => ({
363
- value: "",
364
- setValue: (value) => {
365
- set({ value });
366
- }
367
- });
368
-
369
- // src/context/stores/MessageComposer.ts
370
- var makeEditComposerStore = ({
371
- onEdit,
372
- onSend
373
- }) => (0, import_zustand.create)()((set, get, store) => ({
374
- ...makeBaseComposer(set, get, store),
375
- isEditing: false,
376
- edit: () => {
377
- const value = onEdit();
378
- set({ isEditing: true, value });
379
- },
380
- send: () => {
381
- const value = get().value;
382
- set({ isEditing: false });
383
- onSend(value);
384
- },
385
- cancel: () => {
386
- if (!get().isEditing) return false;
387
- set({ isEditing: false });
388
- return true;
389
- }
390
- }));
391
-
392
- // src/context/providers/MessageProvider.tsx
393
- var import_jsx_runtime4 = require("react/jsx-runtime");
394
- var getIsLast = (thread, message) => {
395
- return thread.messages[thread.messages.length - 1]?.id === message.id;
396
- };
397
- var syncMessage = (thread, useMessage, messageIndex) => {
398
- const parentId = thread.messages[messageIndex - 1]?.id ?? null;
399
- const message = thread.messages[messageIndex];
400
- if (!message) return;
401
- const isLast = getIsLast(thread, message);
402
- const branches = thread.getBranches(message.id);
403
- const currentState = useMessage.getState();
404
- if (currentState.message === message && currentState.parentId === parentId && currentState.branches === branches && currentState.isLast === isLast)
405
- return;
406
- useMessage.setState({
407
- message,
408
- parentId,
409
- branches,
410
- isLast
411
- });
412
- };
413
- var useMessageContext2 = (messageIndex) => {
414
- const { useThread } = useThreadContext();
415
- const [context] = (0, import_react14.useState)(() => {
416
- const useMessage = (0, import_zustand2.create)((set) => ({
417
- message: null,
418
- parentId: null,
419
- branches: [],
420
- isLast: false,
421
- inProgressIndicator: null,
422
- isCopied: false,
423
- isHovering: false,
424
- setInProgressIndicator: (value) => {
425
- set({ inProgressIndicator: value });
426
- },
427
- setIsCopied: (value) => {
428
- set({ isCopied: value });
429
- },
430
- setIsHovering: (value) => {
431
- set({ isHovering: value });
432
- }
433
- }));
434
- const useComposer = makeEditComposerStore({
435
- onEdit: () => {
436
- const message = useMessage.getState().message;
437
- if (message.role !== "user")
438
- throw new Error(
439
- "Tried to edit a non-user message. Editing is only supported for user messages. This is likely an internal bug in assistant-ui."
440
- );
441
- const text = getMessageText(message);
442
- return text;
443
- },
444
- onSend: (text) => {
445
- const { message, parentId } = useMessage.getState();
446
- if (message.role !== "user")
447
- throw new Error(
448
- "Tried to edit a non-user message. Editing is only supported for user messages. This is likely an internal bug in assistant-ui."
449
- );
450
- const nonTextParts = message.content.filter(
451
- (part) => part.type !== "text" && part.type !== "ui"
452
- );
453
- useThread.getState().append({
454
- parentId,
455
- content: [{ type: "text", text }, ...nonTextParts]
456
- });
457
- }
458
- });
459
- syncMessage(useThread.getState(), useMessage, messageIndex);
460
- return { useMessage, useComposer };
461
- });
462
- (0, import_react14.useEffect)(() => {
463
- return useThread.subscribe((thread) => {
464
- syncMessage(thread, context.useMessage, messageIndex);
465
- });
466
- }, [context, useThread, messageIndex]);
467
- return context;
468
- };
469
- var MessageProvider = ({
470
- messageIndex,
471
- children
472
- }) => {
473
- const context = useMessageContext2(messageIndex);
474
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(MessageContext.Provider, { value: context, children });
475
- };
476
-
477
- // src/context/ComposerContext.ts
478
- var import_react15 = require("react");
479
- var useComposerContext = () => {
480
- const { useComposer } = useThreadContext();
481
- const { useComposer: useEditComposer } = (0, import_react15.useContext)(MessageContext) ?? {};
482
- return (0, import_react15.useMemo)(
483
- () => ({
484
- useComposer: useEditComposer ?? useComposer,
485
- type: useEditComposer ? "edit" : "new"
486
- }),
487
- [useEditComposer, useComposer]
488
- );
489
- };
490
-
491
- // src/primitives/composer/ComposerIf.tsx
492
- var useComposerIf = (props) => {
493
- const { useComposer } = useComposerContext();
494
- return useComposer((composer) => {
495
- if (props.editing === true && !composer.isEditing) return false;
496
- if (props.editing === false && composer.isEditing) return false;
497
- return true;
498
- });
499
- };
500
- var ComposerIf = ({ children, ...query }) => {
501
- const result = useComposerIf(query);
502
- return result ? children : null;
503
- };
504
-
505
- // src/primitives/message/MessageIf.tsx
506
- var useMessageIf = (props) => {
507
- const { useMessage } = useMessageContext();
508
- return useMessage(({ message, branches, isLast, isCopied, isHovering }) => {
509
- if (props.hasBranches === true && branches.length < 2) return false;
510
- if (props.user && message.role !== "user") return false;
511
- if (props.assistant && message.role !== "assistant") return false;
512
- if (props.lastOrHover === true && !isHovering && !isLast) return false;
513
- if (props.copied === true && !isCopied) return false;
514
- if (props.copied === false && isCopied) return false;
515
- return true;
516
- });
517
- };
518
- var MessageIf = ({ children, ...query }) => {
519
- const result = useMessageIf(query);
520
- return result ? children : null;
521
- };
522
-
523
- // src/primitives/thread/ThreadMessages.tsx
524
- var import_jsx_runtime5 = require("react/jsx-runtime");
525
- var getComponents = (components) => {
526
- return {
527
- EditComposer: components.EditComposer ?? components.UserMessage ?? components.Message,
528
- UserMessage: components.UserMessage ?? components.Message,
529
- AssistantMessage: components.AssistantMessage ?? components.Message
530
- };
531
- };
532
- var ThreadMessages = ({ components }) => {
533
- const { useThread } = useThreadContext();
534
- const messagesLength = useThread((t) => t.messages.length);
535
- const { UserMessage, EditComposer, AssistantMessage } = getComponents(components);
536
- if (messagesLength === 0) return null;
537
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_jsx_runtime5.Fragment, { children: new Array(messagesLength).fill(null).map((_, idx) => {
538
- const messageIndex = idx;
539
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
540
- MessageProvider,
541
- {
542
- messageIndex,
543
- children: [
544
- /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(MessageIf, { user: true, children: [
545
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ComposerIf, { editing: false, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(UserMessage, {}) }),
546
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ComposerIf, { editing: true, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(EditComposer, {}) })
547
- ] }),
548
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(MessageIf, { assistant: true, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(AssistantMessage, {}) })
549
- ]
550
- },
551
- messageIndex
552
- );
553
- }) });
554
- };
555
-
556
- // src/primitives/thread/ThreadScrollToBottom.tsx
557
- var import_primitive2 = require("@radix-ui/primitive");
558
- var import_react_primitive3 = require("@radix-ui/react-primitive");
559
- var import_react16 = require("react");
560
- var import_jsx_runtime6 = require("react/jsx-runtime");
561
- var ThreadScrollToBottom = (0, import_react16.forwardRef)(({ onClick, ...rest }, ref) => {
562
- const { useViewport } = useThreadContext();
563
- const isAtBottom = useViewport((s) => s.isAtBottom);
564
- const handleScrollToBottom = () => {
565
- useViewport.getState().scrollToBottom();
566
- };
567
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
568
- import_react_primitive3.Primitive.button,
569
- {
570
- ...rest,
571
- disabled: isAtBottom,
572
- ref,
573
- onClick: (0, import_primitive2.composeEventHandlers)(onClick, handleScrollToBottom)
574
- }
575
- );
576
- });
577
-
578
- // src/primitives/thread/ThreadSuggestion.tsx
579
- var import_primitive3 = require("@radix-ui/primitive");
580
- var import_react_primitive4 = require("@radix-ui/react-primitive");
581
- var import_react17 = require("react");
582
- var import_jsx_runtime7 = require("react/jsx-runtime");
583
- var ThreadSuggestion = (0, import_react17.forwardRef)(({ onClick, prompt, method, autoSend: send, ...rest }, ref) => {
584
- const { useThread, useComposer } = useThreadContext();
585
- const isDisabled = useThread((t) => t.isRunning);
586
- const handleApplySuggestion = () => {
587
- const thread = useThread.getState();
588
- const composer = useComposer.getState();
589
- composer.setValue(prompt);
590
- if (send && !thread.isRunning) {
591
- composer.send();
592
- }
593
- };
594
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
595
- import_react_primitive4.Primitive.button,
596
- {
597
- ...rest,
598
- disabled: isDisabled,
599
- ref,
600
- onClick: (0, import_primitive3.composeEventHandlers)(onClick, handleApplySuggestion)
601
- }
602
- );
603
- });
604
-
605
- // src/primitives/composer/index.ts
606
- var composer_exports = {};
607
- __export(composer_exports, {
608
- Cancel: () => ComposerCancel,
609
- If: () => ComposerIf,
610
- Input: () => ComposerInput,
611
- Root: () => ComposerRoot,
612
- Send: () => ComposerSend
613
- });
614
-
615
- // src/primitives/composer/ComposerRoot.tsx
616
- var import_primitive4 = require("@radix-ui/primitive");
617
- var import_react_compose_refs2 = require("@radix-ui/react-compose-refs");
618
- var import_react_primitive5 = require("@radix-ui/react-primitive");
619
- var import_react18 = require("react");
620
- var import_jsx_runtime8 = require("react/jsx-runtime");
621
- var ComposerRoot = (0, import_react18.forwardRef)(
622
- ({ onSubmit, ...rest }, forwardedRef) => {
623
- const { useViewport } = useThreadContext();
624
- const { useComposer } = useComposerContext();
625
- const formRef = (0, import_react18.useRef)(null);
626
- const ref = (0, import_react_compose_refs2.useComposedRefs)(forwardedRef, formRef);
627
- const handleSubmit = (e) => {
628
- const composerState = useComposer.getState();
629
- if (!composerState.isEditing) return;
630
- e.preventDefault();
631
- composerState.send();
632
- useViewport.getState().scrollToBottom();
633
- };
634
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
635
- import_react_primitive5.Primitive.form,
636
- {
637
- ...rest,
638
- ref,
639
- onSubmit: (0, import_primitive4.composeEventHandlers)(onSubmit, handleSubmit)
640
- }
641
- );
642
- }
643
- );
644
-
645
- // src/primitives/composer/ComposerInput.tsx
646
- var import_primitive5 = require("@radix-ui/primitive");
647
- var import_react_compose_refs3 = require("@radix-ui/react-compose-refs");
648
- var import_react_slot = require("@radix-ui/react-slot");
649
- var import_react19 = require("react");
650
- var import_react_textarea_autosize = __toESM(require("react-textarea-autosize"));
651
- var import_jsx_runtime9 = require("react/jsx-runtime");
652
- var ComposerInput = (0, import_react19.forwardRef)(
653
- ({ autoFocus = false, asChild, disabled, onChange, onKeyDown, ...rest }, forwardedRef) => {
654
- const { useThread, useViewport } = useThreadContext();
655
- const { useComposer, type } = useComposerContext();
656
- const value = useComposer((c) => {
657
- if (!c.isEditing) return "";
658
- return c.value;
659
- });
660
- const Component = asChild ? import_react_slot.Slot : import_react_textarea_autosize.default;
661
- const handleKeyPress = (e) => {
662
- if (disabled) return;
663
- const composer = useComposer.getState();
664
- if (e.key === "Escape") {
665
- if (useComposer.getState().cancel()) {
666
- e.preventDefault();
667
- }
668
- } else if (e.key === "Enter" && e.shiftKey === false) {
669
- const isRunning = useThread.getState().isRunning;
670
- if (!isRunning) {
671
- e.preventDefault();
672
- composer.send();
673
- useViewport.getState().scrollToBottom();
674
- }
675
- }
676
- };
677
- const textareaRef = (0, import_react19.useRef)(null);
678
- const ref = (0, import_react_compose_refs3.useComposedRefs)(forwardedRef, textareaRef);
679
- const autoFocusEnabled = autoFocus && !disabled;
680
- const focus = (0, import_react19.useCallback)(() => {
681
- const textarea = textareaRef.current;
682
- if (!textarea || !autoFocusEnabled) return;
683
- textarea.focus();
684
- textarea.setSelectionRange(
685
- textareaRef.current.value.length,
686
- textareaRef.current.value.length
687
- );
688
- }, [autoFocusEnabled]);
689
- (0, import_react19.useEffect)(() => focus(), [focus]);
690
- useOnScrollToBottom(() => {
691
- if (type === "new") {
692
- focus();
693
- }
694
- });
695
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
696
- Component,
697
- {
698
- value,
699
- ...rest,
700
- ref,
701
- disabled,
702
- onChange: (0, import_primitive5.composeEventHandlers)(onChange, (e) => {
703
- const composerState = useComposer.getState();
704
- if (!composerState.isEditing) return;
705
- return composerState.setValue(e.target.value);
706
- }),
707
- onKeyDown: (0, import_primitive5.composeEventHandlers)(onKeyDown, handleKeyPress)
708
- }
709
- );
710
- }
711
- );
712
-
713
- // src/primitives/composer/ComposerSend.tsx
714
- var import_react_primitive6 = require("@radix-ui/react-primitive");
715
- var import_react20 = require("react");
716
- var import_jsx_runtime10 = require("react/jsx-runtime");
717
- var ComposerSend = (0, import_react20.forwardRef)(
718
- ({ disabled, ...rest }, ref) => {
719
- const { useComposer } = useComposerContext();
720
- const hasValue = useComposer((c) => c.isEditing && c.value.length > 0);
721
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
722
- import_react_primitive6.Primitive.button,
723
- {
724
- type: "submit",
725
- ...rest,
726
- ref,
727
- disabled: disabled || !hasValue
728
- }
729
- );
730
- }
731
- );
732
-
733
- // src/primitives/composer/ComposerCancel.tsx
734
- var import_primitive6 = require("@radix-ui/primitive");
735
- var import_react_primitive7 = require("@radix-ui/react-primitive");
736
- var import_react21 = require("react");
737
- var import_jsx_runtime11 = require("react/jsx-runtime");
738
- var ComposerCancel = (0, import_react21.forwardRef)(({ onClick, ...rest }, ref) => {
739
- const { useComposer } = useComposerContext();
740
- const handleCancel = () => {
741
- useComposer.getState().cancel();
742
- };
743
- return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
744
- import_react_primitive7.Primitive.button,
745
- {
746
- type: "button",
747
- ...rest,
748
- ref,
749
- onClick: (0, import_primitive6.composeEventHandlers)(onClick, handleCancel)
750
- }
751
- );
752
- });
753
-
754
- // src/primitives/message/index.ts
755
- var message_exports = {};
756
- __export(message_exports, {
757
- Content: () => MessageContent,
758
- If: () => MessageIf,
759
- InProgress: () => MessageInProgress,
760
- Root: () => MessageRoot
761
- });
762
-
763
- // src/primitives/message/MessageRoot.tsx
764
- var import_primitive7 = require("@radix-ui/primitive");
765
- var import_react_primitive8 = require("@radix-ui/react-primitive");
766
- var import_react22 = require("react");
767
- var import_jsx_runtime12 = require("react/jsx-runtime");
768
- var MessageRoot = (0, import_react22.forwardRef)(
769
- ({ onMouseEnter, onMouseLeave, ...rest }, ref) => {
770
- const { useMessage } = useMessageContext();
771
- const setIsHovering = useMessage((s) => s.setIsHovering);
772
- const handleMouseEnter = () => {
773
- setIsHovering(true);
774
- };
775
- const handleMouseLeave = () => {
776
- setIsHovering(false);
777
- };
778
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
779
- import_react_primitive8.Primitive.div,
780
- {
781
- ...rest,
782
- ref,
783
- onMouseEnter: (0, import_primitive7.composeEventHandlers)(onMouseEnter, handleMouseEnter),
784
- onMouseLeave: (0, import_primitive7.composeEventHandlers)(onMouseLeave, handleMouseLeave)
785
- }
786
- );
787
- }
788
- );
789
-
790
- // src/context/providers/ContentPartProvider.tsx
791
- var import_react24 = require("react");
792
- var import_zustand3 = require("zustand");
793
-
794
- // src/context/ContentPartContext.ts
795
- var import_react23 = require("react");
796
- var ContentPartContext = (0, import_react23.createContext)(
797
- null
798
- );
799
- var useContentPartContext = () => {
800
- const context = (0, import_react23.useContext)(ContentPartContext);
801
- if (!context)
802
- throw new Error(
803
- "This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >."
804
- );
805
- return context;
806
- };
807
-
808
- // src/context/providers/ContentPartProvider.tsx
809
- var import_jsx_runtime13 = require("react/jsx-runtime");
810
- var syncContentPart = ({ message }, useContentPart, partIndex) => {
811
- const part = message.content[partIndex];
812
- if (!part) return;
813
- const messageStatus = message.role === "assistant" ? message.status : "done";
814
- const status = partIndex === message.content.length - 1 ? messageStatus : "done";
815
- useContentPart.setState({ part, status });
816
- };
817
- var useContentPartContext2 = (partIndex) => {
818
- const { useMessage } = useMessageContext();
819
- const [context] = (0, import_react24.useState)(() => {
820
- const useContentPart = (0, import_zustand3.create)(() => ({
821
- part: { type: "text", text: "" },
822
- status: "done"
823
- }));
824
- syncContentPart(useMessage.getState(), useContentPart, partIndex);
825
- return { useContentPart };
826
- });
827
- (0, import_react24.useEffect)(() => {
828
- return useMessage.subscribe((message) => {
829
- syncContentPart(message, context.useContentPart, partIndex);
830
- });
831
- }, [context, useMessage, partIndex]);
832
- return context;
833
- };
834
- var ContentPartProvider = ({
835
- partIndex,
836
- children
837
- }) => {
838
- const context = useContentPartContext2(partIndex);
839
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(ContentPartContext.Provider, { value: context, children });
840
- };
841
-
842
- // src/primitives/contentPart/ContentPartInProgressIndicator.tsx
843
- var ContentPartInProgressIndicator = () => {
844
- const { useMessage } = useMessageContext();
845
- const { useContentPart } = useContentPartContext();
846
- const indicator = useCombinedStore(
847
- [useMessage, useContentPart],
848
- (m, c) => c.status === "in_progress" ? m.inProgressIndicator : null
849
- );
850
- return indicator;
851
- };
852
-
853
- // src/primitives/message/MessageContent.tsx
854
- var import_jsx_runtime14 = require("react/jsx-runtime");
855
- var defaultComponents = {
856
- Text: ({ part }) => /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
857
- part.text,
858
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ContentPartInProgressIndicator, {})
859
- ] }),
860
- Image: () => null,
861
- UI: ({ part }) => part.display,
862
- tools: {
863
- Fallback: () => null
864
- }
865
- };
866
- var MessageContent = ({
867
- components: {
868
- Text = defaultComponents.Text,
869
- Image = defaultComponents.Image,
870
- UI = defaultComponents.UI,
871
- tools: { by_name = {}, Fallback = defaultComponents.tools.Fallback } = {}
872
- } = {}
873
- }) => {
874
- const { useMessage } = useMessageContext();
875
- const message = useMessage((s) => s.message);
876
- const content = message.content;
877
- return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_jsx_runtime14.Fragment, { children: content.map((part, i) => {
878
- const partIndex = i;
879
- const type = part.type;
880
- let component = null;
881
- switch (type) {
882
- case "text":
883
- component = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { part });
884
- break;
885
- case "image":
886
- component = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Image, { part });
887
- break;
888
- case "ui":
889
- component = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(UI, { part });
890
- break;
891
- case "tool-call": {
892
- const Tool = by_name[part.name] || Fallback;
893
- component = /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Tool, { part });
894
- break;
895
- }
896
- default:
897
- throw new Error(`Unknown content part type: ${type}`);
898
- }
899
- return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ContentPartProvider, { partIndex, children: component }, partIndex);
900
- }) });
901
- };
902
-
903
- // src/primitives/message/MessageInProgress.tsx
904
- var import_react_primitive9 = require("@radix-ui/react-primitive");
905
- var import_react25 = require("react");
906
- var import_jsx_runtime15 = require("react/jsx-runtime");
907
- var MessageInProgress = (0, import_react25.forwardRef)((props, ref) => {
908
- const { useMessage } = useMessageContext();
909
- (0, import_react25.useMemo)(() => {
910
- useMessage.getState().setInProgressIndicator(/* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_primitive9.Primitive.span, { ...props, ref }));
911
- }, [useMessage, props, ref]);
912
- return null;
913
- });
914
-
915
- // src/primitives/branchPicker/index.ts
916
- var branchPicker_exports = {};
917
- __export(branchPicker_exports, {
918
- Count: () => BranchPickerCount,
919
- Next: () => BranchPickerNext,
920
- Number: () => BranchPickerNumber,
921
- Previous: () => BranchPickerPrevious,
922
- Root: () => BranchPickerRoot
923
- });
924
-
925
- // src/utils/createActionButton.tsx
926
- var import_primitive8 = require("@radix-ui/primitive");
927
- var import_react_primitive10 = require("@radix-ui/react-primitive");
928
- var import_react26 = require("react");
929
- var import_jsx_runtime16 = require("react/jsx-runtime");
930
- var createActionButton = (useActionButton) => {
931
- return (0, import_react26.forwardRef)(
932
- (props, forwardedRef) => {
933
- const onClick = useActionButton(props);
934
- return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
935
- import_react_primitive10.Primitive.button,
936
- {
937
- type: "button",
938
- disabled: !onClick,
939
- ...props,
940
- ref: forwardedRef,
941
- onClick: (0, import_primitive8.composeEventHandlers)(props.onClick, onClick ?? void 0)
942
- }
943
- );
944
- }
945
- );
946
- };
947
-
948
- // src/primitives/branchPicker/BranchPickerNext.tsx
949
- var BranchPickerNext = createActionButton(useGoToNextBranch);
950
-
951
- // src/primitives/branchPicker/BranchPickerPrevious.tsx
952
- var BranchPickerPrevious = createActionButton(useGoToPreviousBranch);
953
-
954
- // src/primitives/branchPicker/BranchPickerCount.tsx
955
- var import_jsx_runtime17 = require("react/jsx-runtime");
956
- var BranchPickerCount = () => {
957
- const { useMessage } = useMessageContext();
958
- const branchCount = useMessage((s) => s.branches.length);
959
- return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_jsx_runtime17.Fragment, { children: branchCount });
960
- };
961
-
962
- // src/primitives/branchPicker/BranchPickerNumber.tsx
963
- var import_jsx_runtime18 = require("react/jsx-runtime");
964
- var BranchPickerNumber = () => {
965
- const { useMessage } = useMessageContext();
966
- const branchIdx = useMessage((s) => s.branches.indexOf(s.message.id));
967
- return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_jsx_runtime18.Fragment, { children: branchIdx + 1 });
968
- };
969
-
970
- // src/primitives/branchPicker/BranchPickerRoot.tsx
971
- var import_react_primitive11 = require("@radix-ui/react-primitive");
972
- var import_react27 = require("react");
973
- var import_jsx_runtime19 = require("react/jsx-runtime");
974
- var BranchPickerRoot = (0, import_react27.forwardRef)(({ hideWhenSingleBranch, ...rest }, ref) => {
975
- return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(MessageIf, { hasBranches: hideWhenSingleBranch ? true : void 0, children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_react_primitive11.Primitive.div, { ...rest, ref }) });
976
- });
977
-
978
- // src/primitives/actionBar/index.ts
979
- var actionBar_exports = {};
980
- __export(actionBar_exports, {
981
- Copy: () => ActionBarCopy,
982
- Edit: () => ActionBarEdit,
983
- Reload: () => ActionBarReload,
984
- Root: () => ActionBarRoot
985
- });
986
-
987
- // src/primitives/actionBar/ActionBarRoot.tsx
988
- var import_react_primitive12 = require("@radix-ui/react-primitive");
989
- var import_react28 = require("react");
990
- var import_jsx_runtime20 = require("react/jsx-runtime");
991
- var ActionBarRoot = (0, import_react28.forwardRef)(({ hideWhenRunning, autohide, autohideFloat, ...rest }, ref) => {
992
- const { useThread } = useThreadContext();
993
- const { useMessage } = useMessageContext();
994
- const hideAndfloatStatus = useCombinedStore(
995
- [useThread, useMessage],
996
- (t, m) => {
997
- if (hideWhenRunning && t.isRunning) return "hidden" /* Hidden */;
998
- const autohideEnabled = autohide === "always" || autohide === "not-last" && !m.isLast;
999
- if (!autohideEnabled) return "normal" /* Normal */;
1000
- if (!m.isHovering) return "hidden" /* Hidden */;
1001
- if (autohideFloat === "always" || autohideFloat === "single-branch" && m.branches.length <= 1)
1002
- return "floating" /* Floating */;
1003
- return "normal" /* Normal */;
1004
- }
1005
- );
1006
- if (hideAndfloatStatus === "hidden" /* Hidden */) return null;
1007
- return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
1008
- import_react_primitive12.Primitive.div,
1009
- {
1010
- "data-floating": hideAndfloatStatus === "floating" /* Floating */,
1011
- ...rest,
1012
- ref
1013
- }
1014
- );
1015
- });
1016
-
1017
- // src/primitives/actionBar/ActionBarCopy.tsx
1018
- var ActionBarCopy = createActionButton(useCopyMessage);
1019
-
1020
- // src/primitives/actionBar/ActionBarReload.tsx
1021
- var ActionBarReload = createActionButton(useReloadMessage);
1022
-
1023
- // src/primitives/actionBar/ActionBarEdit.tsx
1024
- var ActionBarEdit = createActionButton(useBeginMessageEdit);
1025
-
1026
- // src/primitives/contentPart/index.ts
1027
- var contentPart_exports = {};
1028
- __export(contentPart_exports, {
1029
- InProgressIndicator: () => ContentPartInProgressIndicator
1030
- });
1031
-
1032
- // src/runtime/local/useLocalRuntime.tsx
1033
- var import_react29 = require("react");
1034
-
1035
- // src/utils/ModelConfigTypes.ts
1036
- var mergeModelConfigs = (configs) => {
1037
- return configs.reduce((acc, config) => {
1038
- if (config.system) {
1039
- if (acc.system) {
1040
- acc.system += `
1041
-
1042
- ${config.system}`;
1043
- } else {
1044
- acc.system = config.system;
1045
- }
1046
- }
1047
- if (config.tools) {
1048
- acc.tools = { ...acc.tools, ...config.tools };
1049
- }
1050
- return acc;
1051
- }, {});
1052
- };
1053
-
1054
- // src/runtime/utils/idUtils.tsx
1055
- var import_non_secure = require("nanoid/non-secure");
1056
- var generateId = (0, import_non_secure.customAlphabet)(
1057
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
1058
- 7
1059
- );
1060
- var optimisticPrefix = "__optimistic__";
1061
- var generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;
1062
-
1063
- // src/runtime/utils/MessageRepository.tsx
1064
- var findHead = (message) => {
1065
- if (message.next) return findHead(message.next);
1066
- return message;
1067
- };
1068
- var MessageRepository = class {
1069
- messages = /* @__PURE__ */ new Map();
1070
- // message_id -> item
1071
- head = null;
1072
- root = {
1073
- children: []
1074
- };
1075
- performOp(newParent, child, operation) {
1076
- const parentOrRoot = child.prev ?? this.root;
1077
- const newParentOrRoot = newParent ?? this.root;
1078
- if (operation === "relink" && parentOrRoot === newParentOrRoot) return;
1079
- if (operation !== "link") {
1080
- parentOrRoot.children = parentOrRoot.children.filter(
1081
- (m) => m !== child.current.id
1082
- );
1083
- if (child.prev?.next === child) {
1084
- const fallbackId = child.prev.children.at(-1);
1085
- const fallback = fallbackId ? this.messages.get(fallbackId) : null;
1086
- if (fallback === void 0) {
1087
- throw new Error(
1088
- "MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui."
1089
- );
1090
- }
1091
- child.prev.next = fallback;
1092
- }
1093
- }
1094
- if (operation !== "cut") {
1095
- newParentOrRoot.children = [
1096
- ...newParentOrRoot.children,
1097
- child.current.id
1098
- ];
1099
- if (newParent && (findHead(child) === this.head || newParent.next === null)) {
1100
- newParent.next = child;
1101
- }
1102
- child.prev = newParent;
1103
- }
1104
- }
1105
- getMessages() {
1106
- const messages = new Array(this.head?.level ?? 0);
1107
- for (let current = this.head; current; current = current.prev) {
1108
- messages[current.level] = current.current;
1109
- }
1110
- return messages;
1111
- }
1112
- addOrUpdateMessage(parentId, message) {
1113
- const existingItem = this.messages.get(message.id);
1114
- const prev = parentId ? this.messages.get(parentId) : null;
1115
- if (prev === void 0)
1116
- throw new Error(
1117
- "MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui."
1118
- );
1119
- if (existingItem) {
1120
- existingItem.current = message;
1121
- this.performOp(prev, existingItem, "relink");
1122
- return;
1123
- }
1124
- const newItem = {
1125
- prev,
1126
- current: message,
1127
- next: null,
1128
- children: [],
1129
- level: prev ? prev.level + 1 : 0
1130
- };
1131
- this.messages.set(message.id, newItem);
1132
- this.performOp(prev, newItem, "link");
1133
- if (this.head === prev) {
1134
- this.head = newItem;
1135
- }
1136
- }
1137
- appendOptimisticMessage(parentId, message) {
1138
- let optimisticId;
1139
- do {
1140
- optimisticId = generateOptimisticId();
1141
- } while (this.messages.has(optimisticId));
1142
- this.addOrUpdateMessage(parentId, {
1143
- ...message,
1144
- id: optimisticId,
1145
- createdAt: /* @__PURE__ */ new Date(),
1146
- ...message.role === "assistant" ? { status: "in_progress" } : void 0
1147
- });
1148
- return optimisticId;
1149
- }
1150
- deleteMessage(messageId, replacementId) {
1151
- const message = this.messages.get(messageId);
1152
- if (!message)
1153
- throw new Error(
1154
- "MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui."
1155
- );
1156
- const replacement = replacementId === void 0 ? message.prev : replacementId === null ? null : this.messages.get(replacementId);
1157
- if (replacement === void 0)
1158
- throw new Error(
1159
- "MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui."
1160
- );
1161
- for (const child of message.children) {
1162
- const childMessage = this.messages.get(child);
1163
- if (!childMessage)
1164
- throw new Error(
1165
- "MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui."
1166
- );
1167
- this.performOp(replacement, childMessage, "relink");
1168
- }
1169
- this.performOp(null, message, "cut");
1170
- this.messages.delete(messageId);
1171
- if (this.head === message) {
1172
- this.head = replacement ? findHead(replacement) : null;
1173
- }
1174
- }
1175
- getBranches(messageId) {
1176
- const message = this.messages.get(messageId);
1177
- if (!message)
1178
- throw new Error(
1179
- "MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui."
1180
- );
1181
- const { children } = message.prev ?? this.root;
1182
- return children;
1183
- }
1184
- switchToBranch(messageId) {
1185
- const message = this.messages.get(messageId);
1186
- if (!message)
1187
- throw new Error(
1188
- "MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui."
1189
- );
1190
- if (message.prev) {
1191
- message.prev.next = message;
1192
- }
1193
- this.head = findHead(message);
1194
- }
1195
- resetHead(messageId) {
1196
- if (messageId === null) {
1197
- this.head = null;
1198
- return;
1199
- }
1200
- const message = this.messages.get(messageId);
1201
- if (!message)
1202
- throw new Error(
1203
- "MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui."
1204
- );
1205
- this.head = message;
1206
- for (let current = message; current; current = current.prev) {
1207
- if (current.prev) {
1208
- current.prev.next = current;
1209
- }
1210
- }
1211
- }
1212
- };
1213
-
1214
- // src/runtime/local/LocalRuntime.tsx
1215
- var LocalRuntime = class {
1216
- constructor(adapter) {
1217
- this.adapter = adapter;
1218
- }
1219
- _subscriptions = /* @__PURE__ */ new Set();
1220
- _configProviders = /* @__PURE__ */ new Set();
1221
- abortController = null;
1222
- repository = new MessageRepository();
1223
- get messages() {
1224
- return this.repository.getMessages();
1225
- }
1226
- get isRunning() {
1227
- return this.abortController != null;
1228
- }
1229
- getBranches(messageId) {
1230
- return this.repository.getBranches(messageId);
1231
- }
1232
- switchToBranch(branchId) {
1233
- this.repository.switchToBranch(branchId);
1234
- this.notifySubscribers();
1235
- }
1236
- async append(message) {
1237
- const userMessageId = generateId();
1238
- const userMessage = {
1239
- id: userMessageId,
1240
- role: "user",
1241
- content: message.content,
1242
- createdAt: /* @__PURE__ */ new Date()
1243
- };
1244
- this.repository.addOrUpdateMessage(message.parentId, userMessage);
1245
- await this.startRun(userMessageId);
1246
- }
1247
- async startRun(parentId) {
1248
- const id = generateId();
1249
- this.repository.resetHead(parentId);
1250
- const messages = this.repository.getMessages();
1251
- const message = {
1252
- id,
1253
- role: "assistant",
1254
- status: "in_progress",
1255
- content: [{ type: "text", text: "" }],
1256
- createdAt: /* @__PURE__ */ new Date()
1257
- };
1258
- this.repository.addOrUpdateMessage(parentId, { ...message });
1259
- this.abortController?.abort();
1260
- this.abortController = new AbortController();
1261
- this.notifySubscribers();
1262
- try {
1263
- const updateHandler = ({ content }) => {
1264
- message.content = content;
1265
- this.repository.addOrUpdateMessage(parentId, { ...message });
1266
- this.notifySubscribers();
1267
- };
1268
- const result = await this.adapter.run({
1269
- messages,
1270
- abortSignal: this.abortController.signal,
1271
- config: mergeModelConfigs([...this._configProviders].map((p) => p())),
1272
- onUpdate: updateHandler
1273
- });
1274
- updateHandler(result);
1275
- message.status = "done";
1276
- this.repository.addOrUpdateMessage(parentId, { ...message });
1277
- } catch (e) {
1278
- message.status = "error";
1279
- this.repository.addOrUpdateMessage(parentId, { ...message });
1280
- console.error(e);
1281
- } finally {
1282
- this.abortController = null;
1283
- this.notifySubscribers();
1284
- }
1285
- }
1286
- cancelRun() {
1287
- if (!this.abortController) return;
1288
- this.abortController.abort();
1289
- this.abortController = null;
1290
- this.notifySubscribers();
1291
- }
1292
- notifySubscribers() {
1293
- for (const callback of this._subscriptions) callback();
1294
- }
1295
- subscribe(callback) {
1296
- this._subscriptions.add(callback);
1297
- return () => this._subscriptions.delete(callback);
1298
- }
1299
- registerModelConfigProvider(provider) {
1300
- this._configProviders.add(provider);
1301
- return () => this._configProviders.delete(provider);
1302
- }
1303
- };
1304
-
1305
- // src/runtime/local/useLocalRuntime.tsx
1306
- var useLocalRuntime = (adapter) => {
1307
- const [runtime] = (0, import_react29.useState)(() => new LocalRuntime(adapter));
1308
- (0, import_react29.useInsertionEffect)(() => {
1309
- runtime.adapter = adapter;
1310
- });
1311
- return runtime;
1312
- };
1313
-
1314
- // src/context/providers/AssistantRuntimeProvider.tsx
1315
- var import_react33 = require("react");
1316
-
1317
- // src/context/providers/AssistantProvider.tsx
1318
- var import_react32 = require("react");
1319
-
1320
- // src/context/AssistantContext.ts
1321
- var import_react30 = require("react");
1322
- var AssistantContext = (0, import_react30.createContext)(
1323
- null
1324
- );
1325
-
1326
- // src/context/stores/AssistantModelConfig.ts
1327
- var import_zustand4 = require("zustand");
1328
-
1329
- // src/utils/ProxyConfigProvider.ts
1330
- var ProxyConfigProvider = class {
1331
- _providers = /* @__PURE__ */ new Set();
1332
- getModelConfig() {
1333
- return mergeModelConfigs([...this._providers].map((p) => p()));
1334
- }
1335
- registerModelConfigProvider(provider) {
1336
- this._providers.add(provider);
1337
- return () => {
1338
- this._providers.delete(provider);
1339
- };
1340
- }
1341
- };
1342
-
1343
- // src/context/stores/AssistantModelConfig.ts
1344
- var makeAssistantModelConfigStore = () => (0, import_zustand4.create)(() => {
1345
- const proxy = new ProxyConfigProvider();
1346
- return {
1347
- getModelConfig: () => {
1348
- return proxy.getModelConfig();
1349
- },
1350
- registerModelConfigProvider: (provider) => {
1351
- return proxy.registerModelConfigProvider(provider);
1352
- }
1353
- };
1354
- });
1355
-
1356
- // src/context/providers/ThreadProvider.tsx
1357
- var import_react31 = require("react");
1358
-
1359
- // src/context/stores/Composer.ts
1360
- var import_zustand5 = require("zustand");
1361
- var makeComposerStore = (useThread) => (0, import_zustand5.create)()((set, get, store) => {
1362
- return {
1363
- ...makeBaseComposer(set, get, store),
1364
- isEditing: true,
1365
- send: () => {
1366
- const { setValue, value } = get();
1367
- setValue("");
1368
- useThread.getState().append({
1369
- parentId: useThread.getState().messages.at(-1)?.id ?? null,
1370
- content: [{ type: "text", text: value }]
1371
- });
1372
- },
1373
- cancel: () => {
1374
- const thread = useThread.getState();
1375
- if (!thread.isRunning) return false;
1376
- useThread.getState().cancelRun();
1377
- return true;
1378
- }
1379
- };
1380
- });
1381
-
1382
- // src/context/stores/Thread.ts
1383
- var import_zustand6 = require("zustand");
1384
- var makeThreadStore = (runtimeRef) => {
1385
- const useThread = (0, import_zustand6.create)(() => ({
1386
- messages: runtimeRef.current.messages,
1387
- isRunning: runtimeRef.current.isRunning,
1388
- getBranches: (messageId) => runtimeRef.current.getBranches(messageId),
1389
- switchToBranch: (branchId) => runtimeRef.current.switchToBranch(branchId),
1390
- startRun: (parentId) => runtimeRef.current.startRun(parentId),
1391
- append: (message) => runtimeRef.current.append(message),
1392
- cancelRun: () => runtimeRef.current.cancelRun()
1393
- }));
1394
- const onRuntimeUpdate = () => {
1395
- useThread.setState({
1396
- messages: runtimeRef.current.messages,
1397
- isRunning: runtimeRef.current.isRunning
1398
- });
1399
- };
1400
- return {
1401
- useThread,
1402
- onRuntimeUpdate
1403
- };
1404
- };
1405
-
1406
- // src/context/stores/ThreadViewport.tsx
1407
- var import_zustand7 = require("zustand");
1408
- var makeThreadViewportStore = () => {
1409
- const scrollToBottomListeners = /* @__PURE__ */ new Set();
1410
- return (0, import_zustand7.create)(() => ({
1411
- isAtBottom: true,
1412
- scrollToBottom: () => {
1413
- for (const listener of scrollToBottomListeners) {
1414
- listener();
1415
- }
1416
- },
1417
- onScrollToBottom: (callback) => {
1418
- scrollToBottomListeners.add(callback);
1419
- return () => {
1420
- scrollToBottomListeners.delete(callback);
1421
- };
1422
- }
1423
- }));
1424
- };
1425
-
1426
- // src/context/providers/ThreadProvider.tsx
1427
- var import_jsx_runtime21 = require("react/jsx-runtime");
1428
- var ThreadProvider = ({
1429
- children,
1430
- runtime
1431
- }) => {
1432
- const runtimeRef = (0, import_react31.useRef)(runtime);
1433
- (0, import_react31.useInsertionEffect)(() => {
1434
- runtimeRef.current = runtime;
1435
- });
1436
- const [{ context, onRuntimeUpdate }] = (0, import_react31.useState)(() => {
1437
- const { useThread, onRuntimeUpdate: onRuntimeUpdate2 } = makeThreadStore(runtimeRef);
1438
- const useViewport = makeThreadViewportStore();
1439
- const useComposer = makeComposerStore(useThread);
1440
- return {
1441
- context: {
1442
- useViewport,
1443
- useThread,
1444
- useComposer
1445
- },
1446
- onRuntimeUpdate: onRuntimeUpdate2
1447
- };
1448
- });
1449
- (0, import_react31.useEffect)(() => {
1450
- onRuntimeUpdate();
1451
- return runtime.subscribe(onRuntimeUpdate);
1452
- }, [onRuntimeUpdate, runtime]);
1453
- const RuntimeSynchronizer = runtime.unstable_synchronizer;
1454
- return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(ThreadContext.Provider, { value: context, children: [
1455
- RuntimeSynchronizer && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(RuntimeSynchronizer, {}),
1456
- children
1457
- ] });
1458
- };
1459
-
1460
- // src/context/providers/AssistantProvider.tsx
1461
- var import_jsx_runtime22 = require("react/jsx-runtime");
1462
- var AssistantProvider = ({ children, runtime }) => {
1463
- const runtimeRef = (0, import_react32.useRef)(runtime);
1464
- (0, import_react32.useInsertionEffect)(() => {
1465
- runtimeRef.current = runtime;
1466
- });
1467
- const [context] = (0, import_react32.useState)(() => {
1468
- const useModelConfig = makeAssistantModelConfigStore();
1469
- return { useModelConfig };
1470
- });
1471
- const getModelCOnfig = context.useModelConfig((c) => c.getModelConfig);
1472
- (0, import_react32.useEffect)(() => {
1473
- return runtime.registerModelConfigProvider(getModelCOnfig);
1474
- }, [runtime, getModelCOnfig]);
1475
- return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(AssistantContext.Provider, { value: context, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(ThreadProvider, { runtime, children }) });
1476
- };
1477
-
1478
- // src/context/providers/AssistantRuntimeProvider.tsx
1479
- var import_jsx_runtime23 = require("react/jsx-runtime");
1480
- var AssistantRuntimeProviderImpl = ({ children, runtime }) => {
1481
- return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(AssistantProvider, { runtime, children });
1482
- };
1483
- var AssistantRuntimeProvider = (0, import_react33.memo)(AssistantRuntimeProviderImpl);
1484
- // Annotate the CommonJS export names for ESM import in node:
1485
- 0 && (module.exports = {
1486
- ActionBarPrimitive,
1487
- AssistantRuntimeProvider,
1488
- BranchPickerPrimitive,
1489
- ComposerPrimitive,
1490
- ContentPartPrimitive,
1491
- MessagePrimitive,
1492
- ThreadPrimitive,
1493
- useBeginMessageEdit,
1494
- useCopyMessage,
1495
- useGoToNextBranch,
1496
- useGoToPreviousBranch,
1497
- useLocalRuntime,
1498
- useReloadMessage
1499
- });
1500
- //# sourceMappingURL=index.js.map