@assistant-ui/react 0.5.20 → 0.5.22

Sign up to get free protection for your applications and to get access to all the features.
package/dist/internal.js DELETED
@@ -1,619 +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/internal.ts
31
- var internal_exports = {};
32
- __export(internal_exports, {
33
- BaseAssistantRuntime: () => BaseAssistantRuntime,
34
- MessageRepository: () => MessageRepository,
35
- ProxyConfigProvider: () => ProxyConfigProvider,
36
- TooltipIconButton: () => TooltipIconButton,
37
- generateId: () => generateId,
38
- useSmooth: () => useSmooth,
39
- useSmoothStatus: () => useSmoothStatus,
40
- withSmoothContextProvider: () => withSmoothContextProvider
41
- });
42
- module.exports = __toCommonJS(internal_exports);
43
-
44
- // src/types/ModelConfigTypes.ts
45
- var import_zod = require("zod");
46
- var LanguageModelV1CallSettingsSchema = import_zod.z.object({
47
- maxTokens: import_zod.z.number().int().positive().optional(),
48
- temperature: import_zod.z.number().optional(),
49
- topP: import_zod.z.number().optional(),
50
- presencePenalty: import_zod.z.number().optional(),
51
- frequencyPenalty: import_zod.z.number().optional(),
52
- seed: import_zod.z.number().int().optional(),
53
- headers: import_zod.z.record(import_zod.z.string().optional()).optional()
54
- });
55
- var LanguageModelConfigSchema = import_zod.z.object({
56
- apiKey: import_zod.z.string().optional(),
57
- baseUrl: import_zod.z.string().optional(),
58
- modelName: import_zod.z.string().optional()
59
- });
60
- var mergeModelConfigs = (configSet) => {
61
- const configs = Array.from(configSet).map((c) => c.getModelConfig()).sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
62
- return configs.reduce((acc, config) => {
63
- if (config.system) {
64
- if (acc.system) {
65
- acc.system += `
66
-
67
- ${config.system}`;
68
- } else {
69
- acc.system = config.system;
70
- }
71
- }
72
- if (config.tools) {
73
- for (const [name, tool] of Object.entries(config.tools)) {
74
- if (acc.tools?.[name]) {
75
- throw new Error(
76
- `You tried to define a tool with the name ${name}, but it already exists.`
77
- );
78
- }
79
- if (!acc.tools) acc.tools = {};
80
- acc.tools[name] = tool;
81
- }
82
- }
83
- if (config.config) {
84
- acc.config = {
85
- ...acc.config,
86
- ...config.config
87
- };
88
- }
89
- if (config.callSettings) {
90
- acc.callSettings = {
91
- ...acc.callSettings,
92
- ...config.callSettings
93
- };
94
- }
95
- return acc;
96
- }, {});
97
- };
98
-
99
- // src/utils/ProxyConfigProvider.ts
100
- var ProxyConfigProvider = class {
101
- _providers = /* @__PURE__ */ new Set();
102
- getModelConfig() {
103
- return mergeModelConfigs(this._providers);
104
- }
105
- registerModelConfigProvider(provider) {
106
- this._providers.add(provider);
107
- return () => {
108
- this._providers.delete(provider);
109
- };
110
- }
111
- };
112
-
113
- // src/utils/idUtils.tsx
114
- var import_non_secure = require("nanoid/non-secure");
115
- var generateId = (0, import_non_secure.customAlphabet)(
116
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
117
- 7
118
- );
119
- var optimisticPrefix = "__optimistic__";
120
- var generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;
121
-
122
- // src/runtimes/edge/converters/fromCoreMessage.ts
123
- var fromCoreMessage = (message, {
124
- id = generateId(),
125
- status = { type: "complete", reason: "unknown" }
126
- } = {}) => {
127
- const commonProps = {
128
- id,
129
- createdAt: /* @__PURE__ */ new Date()
130
- };
131
- const role = message.role;
132
- switch (role) {
133
- case "assistant":
134
- return {
135
- ...commonProps,
136
- role,
137
- content: message.content.map((part) => {
138
- if (part.type === "tool-call") {
139
- return {
140
- ...part,
141
- argsText: JSON.stringify(part.args)
142
- };
143
- }
144
- return part;
145
- }),
146
- status
147
- };
148
- case "user":
149
- return {
150
- ...commonProps,
151
- role,
152
- content: message.content
153
- };
154
- case "system":
155
- return {
156
- ...commonProps,
157
- role,
158
- content: message.content
159
- };
160
- default: {
161
- const unsupportedRole = role;
162
- throw new Error(`Unknown message role: ${unsupportedRole}`);
163
- }
164
- }
165
- };
166
-
167
- // src/runtimes/utils/MessageRepository.tsx
168
- var findHead = (message) => {
169
- if (message.next) return findHead(message.next);
170
- return message;
171
- };
172
- var MessageRepository = class {
173
- messages = /* @__PURE__ */ new Map();
174
- // message_id -> item
175
- head = null;
176
- root = {
177
- children: []
178
- };
179
- performOp(newParent, child, operation) {
180
- const parentOrRoot = child.prev ?? this.root;
181
- const newParentOrRoot = newParent ?? this.root;
182
- if (operation === "relink" && parentOrRoot === newParentOrRoot) return;
183
- if (operation !== "link") {
184
- parentOrRoot.children = parentOrRoot.children.filter(
185
- (m) => m !== child.current.id
186
- );
187
- if (child.prev?.next === child) {
188
- const fallbackId = child.prev.children.at(-1);
189
- const fallback = fallbackId ? this.messages.get(fallbackId) : null;
190
- if (fallback === void 0) {
191
- throw new Error(
192
- "MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui."
193
- );
194
- }
195
- child.prev.next = fallback;
196
- }
197
- }
198
- if (operation !== "cut") {
199
- newParentOrRoot.children = [
200
- ...newParentOrRoot.children,
201
- child.current.id
202
- ];
203
- if (newParent && (findHead(child) === this.head || newParent.next === null)) {
204
- newParent.next = child;
205
- }
206
- child.prev = newParent;
207
- }
208
- }
209
- getMessages() {
210
- const messages = new Array(this.head?.level ?? 0);
211
- for (let current = this.head; current; current = current.prev) {
212
- messages[current.level] = current.current;
213
- }
214
- return messages;
215
- }
216
- addOrUpdateMessage(parentId, message) {
217
- const existingItem = this.messages.get(message.id);
218
- const prev = parentId ? this.messages.get(parentId) : null;
219
- if (prev === void 0)
220
- throw new Error(
221
- "MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui."
222
- );
223
- if (existingItem) {
224
- existingItem.current = message;
225
- this.performOp(prev, existingItem, "relink");
226
- return;
227
- }
228
- const newItem = {
229
- prev,
230
- current: message,
231
- next: null,
232
- children: [],
233
- level: prev ? prev.level + 1 : 0
234
- };
235
- this.messages.set(message.id, newItem);
236
- this.performOp(prev, newItem, "link");
237
- if (this.head === prev) {
238
- this.head = newItem;
239
- }
240
- }
241
- getMessage(messageId) {
242
- const message = this.messages.get(messageId);
243
- if (!message)
244
- throw new Error(
245
- "MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui."
246
- );
247
- return {
248
- parentId: message.prev?.current.id ?? null,
249
- message: message.current
250
- };
251
- }
252
- appendOptimisticMessage(parentId, message) {
253
- let optimisticId;
254
- do {
255
- optimisticId = generateOptimisticId();
256
- } while (this.messages.has(optimisticId));
257
- this.addOrUpdateMessage(
258
- parentId,
259
- fromCoreMessage(message, {
260
- id: optimisticId,
261
- status: { type: "running" }
262
- })
263
- );
264
- return optimisticId;
265
- }
266
- deleteMessage(messageId, replacementId) {
267
- const message = this.messages.get(messageId);
268
- if (!message)
269
- throw new Error(
270
- "MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui."
271
- );
272
- const replacement = replacementId === void 0 ? message.prev : replacementId === null ? null : this.messages.get(replacementId);
273
- if (replacement === void 0)
274
- throw new Error(
275
- "MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui."
276
- );
277
- for (const child of message.children) {
278
- const childMessage = this.messages.get(child);
279
- if (!childMessage)
280
- throw new Error(
281
- "MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui."
282
- );
283
- this.performOp(replacement, childMessage, "relink");
284
- }
285
- this.performOp(null, message, "cut");
286
- this.messages.delete(messageId);
287
- if (this.head === message) {
288
- this.head = replacement ? findHead(replacement) : null;
289
- }
290
- }
291
- getBranches(messageId) {
292
- const message = this.messages.get(messageId);
293
- if (!message)
294
- throw new Error(
295
- "MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui."
296
- );
297
- const { children } = message.prev ?? this.root;
298
- return children;
299
- }
300
- switchToBranch(messageId) {
301
- const message = this.messages.get(messageId);
302
- if (!message)
303
- throw new Error(
304
- "MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui."
305
- );
306
- if (message.prev) {
307
- message.prev.next = message;
308
- }
309
- this.head = findHead(message);
310
- }
311
- resetHead(messageId) {
312
- if (messageId === null) {
313
- this.head = null;
314
- return;
315
- }
316
- const message = this.messages.get(messageId);
317
- if (!message)
318
- throw new Error(
319
- "MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui."
320
- );
321
- this.head = message;
322
- for (let current = message; current; current = current.prev) {
323
- if (current.prev) {
324
- current.prev.next = current;
325
- }
326
- }
327
- }
328
- };
329
-
330
- // src/runtimes/core/BaseAssistantRuntime.tsx
331
- var BaseAssistantRuntime = class {
332
- constructor(_thread) {
333
- this._thread = _thread;
334
- this._thread = _thread;
335
- }
336
- get thread() {
337
- return this._thread;
338
- }
339
- set thread(thread) {
340
- this._thread = thread;
341
- this.subscriptionHandler();
342
- }
343
- _subscriptions = /* @__PURE__ */ new Set();
344
- subscribe(callback) {
345
- this._subscriptions.add(callback);
346
- return () => this._subscriptions.delete(callback);
347
- }
348
- subscriptionHandler = () => {
349
- for (const callback of this._subscriptions) callback();
350
- };
351
- };
352
-
353
- // src/utils/smooth/useSmooth.tsx
354
- var import_react4 = require("react");
355
-
356
- // src/context/react/MessageContext.ts
357
- var import_react = require("react");
358
- var MessageContext = (0, import_react.createContext)(null);
359
- function useMessageContext(options) {
360
- const context = (0, import_react.useContext)(MessageContext);
361
- if (!options?.optional && !context)
362
- throw new Error(
363
- "This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />."
364
- );
365
- return context;
366
- }
367
-
368
- // src/context/react/ContentPartContext.ts
369
- var import_react2 = require("react");
370
- var ContentPartContext = (0, import_react2.createContext)(
371
- null
372
- );
373
- function useContentPartContext(options) {
374
- const context = (0, import_react2.useContext)(ContentPartContext);
375
- if (!options?.optional && !context)
376
- throw new Error(
377
- "This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >."
378
- );
379
- return context;
380
- }
381
-
382
- // src/utils/smooth/SmoothContext.tsx
383
- var import_react3 = require("react");
384
- var import_zustand = require("zustand");
385
- var import_jsx_runtime = require("react/jsx-runtime");
386
- var SmoothContext = (0, import_react3.createContext)(null);
387
- var makeSmoothContext = (initialState) => {
388
- const useSmoothStatus2 = (0, import_zustand.create)(() => initialState);
389
- return { useSmoothStatus: useSmoothStatus2 };
390
- };
391
- var SmoothContextProvider = ({ children }) => {
392
- const outer = useSmoothContext({ optional: true });
393
- const { useContentPart } = useContentPartContext();
394
- const [context] = (0, import_react3.useState)(
395
- () => makeSmoothContext(useContentPart.getState().status)
396
- );
397
- if (outer) return children;
398
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SmoothContext.Provider, { value: context, children });
399
- };
400
- var withSmoothContextProvider = (Component) => {
401
- const Wrapped = (0, import_react3.forwardRef)((props, ref) => {
402
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SmoothContextProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, { ...props, ref }) });
403
- });
404
- Wrapped.displayName = Component.displayName;
405
- return Wrapped;
406
- };
407
- function useSmoothContext(options) {
408
- const context = (0, import_react3.useContext)(SmoothContext);
409
- if (!options?.optional && !context)
410
- throw new Error(
411
- "This component must be used within a SmoothContextProvider."
412
- );
413
- return context;
414
- }
415
- var useSmoothStatus = () => {
416
- const { useSmoothStatus: useSmoothStatus2 } = useSmoothContext();
417
- return useSmoothStatus2();
418
- };
419
-
420
- // src/utils/smooth/useSmooth.tsx
421
- var import_react_use_callback_ref = require("@radix-ui/react-use-callback-ref");
422
- var TextStreamAnimator = class {
423
- constructor(currentText, setText) {
424
- this.currentText = currentText;
425
- this.setText = setText;
426
- }
427
- animationFrameId = null;
428
- lastUpdateTime = Date.now();
429
- targetText = "";
430
- start() {
431
- if (this.animationFrameId !== null) return;
432
- this.lastUpdateTime = Date.now();
433
- this.animate();
434
- }
435
- stop() {
436
- if (this.animationFrameId !== null) {
437
- cancelAnimationFrame(this.animationFrameId);
438
- this.animationFrameId = null;
439
- }
440
- }
441
- animate = () => {
442
- const currentTime = Date.now();
443
- const deltaTime = currentTime - this.lastUpdateTime;
444
- let timeToConsume = deltaTime;
445
- const remainingChars = this.targetText.length - this.currentText.length;
446
- const baseTimePerChar = Math.min(5, 250 / remainingChars);
447
- let charsToAdd = 0;
448
- while (timeToConsume >= baseTimePerChar && charsToAdd < remainingChars) {
449
- charsToAdd++;
450
- timeToConsume -= baseTimePerChar;
451
- }
452
- if (charsToAdd !== remainingChars) {
453
- this.animationFrameId = requestAnimationFrame(this.animate);
454
- } else {
455
- this.animationFrameId = null;
456
- }
457
- if (charsToAdd === 0) return;
458
- this.currentText = this.targetText.slice(
459
- 0,
460
- this.currentText.length + charsToAdd
461
- );
462
- this.lastUpdateTime = currentTime - timeToConsume;
463
- this.setText(this.currentText);
464
- };
465
- };
466
- var SMOOTH_STATUS = Object.freeze({
467
- type: "running"
468
- });
469
- var useSmooth = (state, smooth = false) => {
470
- const { useSmoothStatus: useSmoothStatus2 } = useSmoothContext({ optional: true }) ?? {};
471
- const {
472
- part: { text }
473
- } = state;
474
- const { useMessage } = useMessageContext();
475
- const id = useMessage((m) => m.message.id);
476
- const idRef = (0, import_react4.useRef)(id);
477
- const [displayedText, setDisplayedText] = (0, import_react4.useState)(text);
478
- const setText = (0, import_react_use_callback_ref.useCallbackRef)((text2) => {
479
- setDisplayedText(text2);
480
- useSmoothStatus2?.setState(text2 !== state.part.text ? SMOOTH_STATUS : state.status);
481
- });
482
- const [animatorRef] = (0, import_react4.useState)(
483
- new TextStreamAnimator(text, setText)
484
- );
485
- (0, import_react4.useEffect)(() => {
486
- if (!smooth) {
487
- animatorRef.stop();
488
- return;
489
- }
490
- if (idRef.current !== id || !text.startsWith(animatorRef.targetText)) {
491
- idRef.current = id;
492
- setText(text);
493
- animatorRef.currentText = text;
494
- animatorRef.targetText = text;
495
- animatorRef.stop();
496
- return;
497
- }
498
- animatorRef.targetText = text;
499
- animatorRef.start();
500
- }, [setText, animatorRef, id, smooth, text]);
501
- (0, import_react4.useEffect)(() => {
502
- return () => {
503
- animatorRef.stop();
504
- };
505
- }, [animatorRef]);
506
- return (0, import_react4.useMemo)(
507
- () => smooth ? {
508
- part: { type: "text", text: displayedText },
509
- status: text === displayedText ? state.status : SMOOTH_STATUS
510
- } : state,
511
- [smooth, displayedText, state, text]
512
- );
513
- };
514
-
515
- // src/ui/base/tooltip-icon-button.tsx
516
- var import_react7 = require("react");
517
-
518
- // src/ui/base/tooltip.tsx
519
- var TooltipPrimitive = __toESM(require("@radix-ui/react-tooltip"));
520
-
521
- // src/ui/utils/withDefaults.tsx
522
- var import_react5 = require("react");
523
- var import_classnames = __toESM(require("classnames"));
524
- var import_jsx_runtime2 = require("react/jsx-runtime");
525
- var withDefaultProps = ({
526
- className,
527
- ...defaultProps
528
- }) => ({ className: classNameProp, ...props }) => {
529
- return {
530
- className: (0, import_classnames.default)(className, classNameProp),
531
- ...defaultProps,
532
- ...props
533
- };
534
- };
535
- var withDefaults = (Component, defaultProps) => {
536
- const getProps = withDefaultProps(defaultProps);
537
- const WithDefaults = (0, import_react5.forwardRef)(
538
- (props, ref) => {
539
- const ComponentAsAny = Component;
540
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ComponentAsAny, { ...getProps(props), ref });
541
- }
542
- );
543
- WithDefaults.displayName = "withDefaults(" + (typeof Component === "string" ? Component : Component.displayName) + ")";
544
- return WithDefaults;
545
- };
546
-
547
- // src/ui/base/tooltip.tsx
548
- var import_jsx_runtime3 = require("react/jsx-runtime");
549
- var Tooltip = (props) => {
550
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(TooltipPrimitive.Provider, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(TooltipPrimitive.Root, { ...props }) });
551
- };
552
- Tooltip.displayName = "Tooltip";
553
- var TooltipTrigger = TooltipPrimitive.Trigger;
554
- var TooltipContent = withDefaults(TooltipPrimitive.Content, {
555
- sideOffset: 4,
556
- className: "aui-tooltip-content"
557
- });
558
- TooltipContent.displayName = "TooltipContent";
559
-
560
- // src/ui/base/button.tsx
561
- var import_class_variance_authority = require("class-variance-authority");
562
- var import_react_primitive = require("@radix-ui/react-primitive");
563
- var import_react6 = require("react");
564
- var import_jsx_runtime4 = require("react/jsx-runtime");
565
- var buttonVariants = (0, import_class_variance_authority.cva)("aui-button", {
566
- variants: {
567
- variant: {
568
- default: "aui-button-primary",
569
- outline: "aui-button-outline",
570
- ghost: "aui-button-ghost"
571
- },
572
- size: {
573
- default: "aui-button-medium",
574
- icon: "aui-button-icon"
575
- }
576
- },
577
- defaultVariants: {
578
- variant: "default",
579
- size: "default"
580
- }
581
- });
582
- var Button = (0, import_react6.forwardRef)(
583
- ({ className, variant, size, ...props }, ref) => {
584
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
585
- import_react_primitive.Primitive.button,
586
- {
587
- className: buttonVariants({ variant, size, className }),
588
- ...props,
589
- ref
590
- }
591
- );
592
- }
593
- );
594
- Button.displayName = "Button";
595
-
596
- // src/ui/base/tooltip-icon-button.tsx
597
- var import_jsx_runtime5 = require("react/jsx-runtime");
598
- var TooltipIconButton = (0, import_react7.forwardRef)(({ children, tooltip, side = "bottom", ...rest }, ref) => {
599
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Tooltip, { children: [
600
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Button, { variant: "ghost", size: "icon", ...rest, ref, children: [
601
- children,
602
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "aui-sr-only", children: tooltip })
603
- ] }) }),
604
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(TooltipContent, { side, children: tooltip })
605
- ] });
606
- });
607
- TooltipIconButton.displayName = "TooltipIconButton";
608
- // Annotate the CommonJS export names for ESM import in node:
609
- 0 && (module.exports = {
610
- BaseAssistantRuntime,
611
- MessageRepository,
612
- ProxyConfigProvider,
613
- TooltipIconButton,
614
- generateId,
615
- useSmooth,
616
- useSmoothStatus,
617
- withSmoothContextProvider
618
- });
619
- //# sourceMappingURL=internal.js.map