@assistant-ui/react 0.0.29 → 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (53) hide show
  1. package/dist/AssistantRuntime-BM_jVV3g.d.mts +23 -0
  2. package/dist/AssistantRuntime-CBMSAJqH.d.mts +23 -0
  3. package/dist/AssistantRuntime-C_BvM7ZT.d.ts +23 -0
  4. package/dist/AssistantRuntime-DELpXWfG.d.ts +23 -0
  5. package/dist/ModelConfigTypes-B9UY4zxv.d.mts +55 -0
  6. package/dist/ModelConfigTypes-B9UY4zxv.d.ts +55 -0
  7. package/dist/ModelConfigTypes-BF5HxVrH.d.mts +55 -0
  8. package/dist/ModelConfigTypes-BF5HxVrH.d.ts +55 -0
  9. package/dist/ModelConfigTypes-Cf3yjaDu.d.mts +55 -0
  10. package/dist/ModelConfigTypes-Cf3yjaDu.d.ts +55 -0
  11. package/dist/ModelConfigTypes-CzmXY3sn.d.mts +55 -0
  12. package/dist/ModelConfigTypes-CzmXY3sn.d.ts +55 -0
  13. package/dist/Thread-BMASJT4a.d.ts +15 -0
  14. package/dist/Thread-UEVsUmvl.d.mts +15 -0
  15. package/dist/chunk-3XZUKECF.mjs +207 -0
  16. package/dist/chunk-3XZUKECF.mjs.map +1 -0
  17. package/dist/chunk-4DQ2CIAD.mjs +69 -0
  18. package/dist/chunk-4DQ2CIAD.mjs.map +1 -0
  19. package/dist/chunk-5YONSDN4.mjs +200 -0
  20. package/dist/chunk-5YONSDN4.mjs.map +1 -0
  21. package/dist/chunk-CY4TTHR7.mjs +76 -0
  22. package/dist/chunk-CY4TTHR7.mjs.map +1 -0
  23. package/dist/chunk-DKAWDNW5.mjs +22 -0
  24. package/dist/chunk-DKAWDNW5.mjs.map +1 -0
  25. package/dist/chunk-GQKH2ADD.mjs +165 -0
  26. package/dist/chunk-GQKH2ADD.mjs.map +1 -0
  27. package/dist/chunk-J5LGTIGS.mjs +10 -0
  28. package/dist/chunk-J5LGTIGS.mjs.map +1 -0
  29. package/dist/chunk-NSBOH42A.mjs +200 -0
  30. package/dist/chunk-NSBOH42A.mjs.map +1 -0
  31. package/dist/chunk-X4HBDEFP.mjs +30 -0
  32. package/dist/chunk-X4HBDEFP.mjs.map +1 -0
  33. package/dist/experimental.d.mts +86 -0
  34. package/dist/experimental.d.ts +86 -0
  35. package/dist/experimental.js +123 -0
  36. package/dist/experimental.js.map +1 -0
  37. package/dist/experimental.mjs +34 -0
  38. package/dist/experimental.mjs.map +1 -0
  39. package/dist/index.d.mts +11 -230
  40. package/dist/index.d.ts +11 -230
  41. package/dist/index.js +189 -577
  42. package/dist/index.js.map +1 -1
  43. package/dist/index.mjs +140 -757
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/internal-dlLjX30u.d.mts +75 -0
  46. package/dist/internal-dlLjX30u.d.ts +75 -0
  47. package/dist/internal.d.mts +25 -0
  48. package/dist/internal.d.ts +25 -0
  49. package/dist/internal.js +225 -0
  50. package/dist/internal.js.map +1 -0
  51. package/dist/internal.mjs +10 -0
  52. package/dist/internal.mjs.map +1 -0
  53. package/package.json +23 -3
package/dist/index.mjs CHANGED
@@ -1,24 +1,26 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
1
+ import {
2
+ MessageRepository,
3
+ ProxyConfigProvider,
4
+ generateId,
5
+ mergeModelConfigs
6
+ } from "./chunk-NSBOH42A.mjs";
7
+ import {
8
+ AssistantContext,
9
+ ContentPartContext,
10
+ MessageContext,
11
+ ThreadContext,
12
+ useComposerContext,
13
+ useContentPartContext,
14
+ useMessageContext,
15
+ useThreadContext
16
+ } from "./chunk-CY4TTHR7.mjs";
17
+ import {
18
+ __export
19
+ } from "./chunk-J5LGTIGS.mjs";
6
20
 
7
21
  // src/actions/useCopyMessage.tsx
8
22
  import { useCallback } from "react";
9
23
 
10
- // src/context/MessageContext.ts
11
- import { createContext, useContext } from "react";
12
- var MessageContext = createContext(null);
13
- var useMessageContext = () => {
14
- const context = useContext(MessageContext);
15
- if (!context)
16
- throw new Error(
17
- "This component can only be used inside a component passed to <ThreadPrimitive.Messages components={...} />."
18
- );
19
- return context;
20
- };
21
-
22
24
  // src/utils/combined/useCombinedStore.ts
23
25
  import { useMemo } from "react";
24
26
 
@@ -76,18 +78,6 @@ var useCopyMessage = ({ copiedDuration = 3e3 }) => {
76
78
 
77
79
  // src/actions/useReloadMessage.tsx
78
80
  import { useCallback as useCallback2 } from "react";
79
-
80
- // src/context/ThreadContext.ts
81
- import { createContext as createContext2, useContext as useContext2 } from "react";
82
- var ThreadContext = createContext2(null);
83
- var useThreadContext = () => {
84
- const context = useContext2(ThreadContext);
85
- if (!context)
86
- throw new Error("This component must be used within an AssistantProvider.");
87
- return context;
88
- };
89
-
90
- // src/actions/useReloadMessage.tsx
91
81
  var useReloadMessage = () => {
92
82
  const { useThread, useViewport } = useThreadContext();
93
83
  const { useMessage } = useMessageContext();
@@ -436,20 +426,6 @@ var MessageProvider = ({
436
426
  return /* @__PURE__ */ jsx4(MessageContext.Provider, { value: context, children });
437
427
  };
438
428
 
439
- // src/context/ComposerContext.ts
440
- import { useContext as useContext3, useMemo as useMemo2 } from "react";
441
- var useComposerContext = () => {
442
- const { useComposer } = useThreadContext();
443
- const { useComposer: useEditComposer } = useContext3(MessageContext) ?? {};
444
- return useMemo2(
445
- () => ({
446
- useComposer: useEditComposer ?? useComposer,
447
- type: useEditComposer ? "edit" : "new"
448
- }),
449
- [useEditComposer, useComposer]
450
- );
451
- };
452
-
453
429
  // src/primitives/composer/ComposerIf.tsx
454
430
  var useComposerIf = (props) => {
455
431
  const { useComposer } = useComposerContext();
@@ -769,22 +745,6 @@ var MessageRoot = forwardRef9(
769
745
  // src/context/providers/ContentPartProvider.tsx
770
746
  import { useEffect as useEffect5, useState as useState2 } from "react";
771
747
  import { create as create3 } from "zustand";
772
-
773
- // src/context/ContentPartContext.ts
774
- import { createContext as createContext3, useContext as useContext4 } from "react";
775
- var ContentPartContext = createContext3(
776
- null
777
- );
778
- var useContentPartContext = () => {
779
- const context = useContext4(ContentPartContext);
780
- if (!context)
781
- throw new Error(
782
- "This component can only be used inside a component passed to <MessagePrimitive.Content components={...} >."
783
- );
784
- return context;
785
- };
786
-
787
- // src/context/providers/ContentPartProvider.tsx
788
748
  import { jsx as jsx13 } from "react/jsx-runtime";
789
749
  var syncContentPart = ({ message }, useContentPart, partIndex) => {
790
750
  const part = message.content[partIndex];
@@ -883,11 +843,11 @@ var MessageContent = ({
883
843
  import {
884
844
  Primitive as Primitive9
885
845
  } from "@radix-ui/react-primitive";
886
- import { forwardRef as forwardRef10, useMemo as useMemo3 } from "react";
846
+ import { forwardRef as forwardRef10, useMemo as useMemo2 } from "react";
887
847
  import { jsx as jsx15 } from "react/jsx-runtime";
888
848
  var MessageInProgress = forwardRef10((props, ref) => {
889
849
  const { useMessage } = useMessageContext();
890
- useMemo3(() => {
850
+ useMemo2(() => {
891
851
  useMessage.getState().setInProgressIndicator(/* @__PURE__ */ jsx15(Primitive9.span, { ...props, ref }));
892
852
  }, [useMessage, props, ref]);
893
853
  return null;
@@ -1016,585 +976,135 @@ __export(contentPart_exports, {
1016
976
  InProgressIndicator: () => ContentPartInProgressIndicator
1017
977
  });
1018
978
 
1019
- // ../react-ai-sdk/src/rsc/useVercelRSCRuntime.tsx
1020
- import { useEffect as useEffect7, useInsertionEffect, useState as useState3 } from "react";
1021
-
1022
- // ../react-ai-sdk/src/rsc/VercelRSCRuntime.tsx
1023
- import { create as create4 } from "zustand";
1024
-
1025
- // ../react-ai-sdk/src/rsc/useVercelRSCSync.tsx
1026
- import { useEffect as useEffect6, useMemo as useMemo4 } from "react";
1027
-
1028
- // ../react-ai-sdk/src/utils/ThreadMessageConverter.ts
1029
- var ThreadMessageConverter = class {
1030
- cache = /* @__PURE__ */ new WeakMap();
1031
- convertMessages(messages, converter, keyMapper = (key) => key) {
1032
- return messages.map((m) => {
1033
- const key = keyMapper(m);
1034
- const cached = this.cache.get(key);
1035
- const newMessage = converter(m, cached);
1036
- this.cache.set(key, newMessage);
1037
- return newMessage;
1038
- });
1039
- }
1040
- };
1041
-
1042
- // ../react-ai-sdk/src/rsc/getVercelRSCMessage.tsx
1043
- var symbolInnerRSCMessage = Symbol("innerVercelRSCMessage");
1044
- var getVercelRSCMessage = (message) => {
1045
- return message[symbolInnerRSCMessage];
1046
- };
1047
-
1048
- // ../react-ai-sdk/src/rsc/useVercelRSCSync.tsx
1049
- var vercelToThreadMessage = (converter, rawMessage) => {
1050
- const message = converter(rawMessage);
1051
- return {
1052
- id: message.id,
1053
- role: message.role,
1054
- content: [{ type: "ui", display: message.display }],
1055
- createdAt: message.createdAt ?? /* @__PURE__ */ new Date(),
1056
- ...{ status: "done" },
1057
- [symbolInnerRSCMessage]: rawMessage
1058
- };
1059
- };
1060
- var useVercelRSCSync = (adapter, updateData) => {
1061
- const [converter, convertCallback] = useMemo4(() => {
1062
- const rscConverter = adapter.convertMessage ?? ((m) => m);
1063
- const convertCallback2 = (m, cache) => {
1064
- if (cache) return cache;
1065
- return vercelToThreadMessage(rscConverter, m);
1066
- };
1067
- return [new ThreadMessageConverter(), convertCallback2];
1068
- }, [adapter.convertMessage]);
1069
- useEffect6(() => {
1070
- updateData(converter.convertMessages(adapter.messages, convertCallback));
1071
- }, [updateData, converter, convertCallback, adapter.messages]);
1072
- };
979
+ // src/runtime/local/useLocalRuntime.tsx
980
+ import { useInsertionEffect, useState as useState3 } from "react";
1073
981
 
1074
- // ../react-ai-sdk/src/rsc/VercelRSCRuntime.tsx
1075
- var EMPTY_BRANCHES = Object.freeze([]);
1076
- var VercelRSCRuntime = class {
982
+ // src/runtime/local/LocalRuntime.tsx
983
+ var LocalRuntime = class {
1077
984
  constructor(adapter) {
1078
985
  this.adapter = adapter;
1079
- this.useAdapter = create4(() => ({
1080
- adapter
1081
- }));
1082
986
  }
1083
- useAdapter;
1084
987
  _subscriptions = /* @__PURE__ */ new Set();
1085
- isRunning = false;
1086
- messages = [];
1087
- withRunning = (callback) => {
1088
- this.isRunning = true;
1089
- return callback.finally(() => {
1090
- this.isRunning = false;
1091
- });
1092
- };
1093
- getBranches() {
1094
- return EMPTY_BRANCHES;
1095
- }
1096
- switchToBranch() {
1097
- throw new Error(
1098
- "Branch switching is not supported by VercelRSCAssistantProvider."
1099
- );
1100
- }
1101
- async append(message) {
1102
- if (message.parentId !== (this.messages.at(-1)?.id ?? null)) {
1103
- if (!this.adapter.edit)
1104
- throw new Error(
1105
- "Message editing is not enabled, please provide an edit callback to VercelRSCAssistantProvider."
1106
- );
1107
- await this.withRunning(this.adapter.edit(message));
1108
- } else {
1109
- await this.withRunning(this.adapter.append(message));
1110
- }
1111
- }
1112
- async startRun(parentId) {
1113
- if (!this.adapter.reload)
1114
- throw new Error(
1115
- "Message reloading is not enabled, please provide a reload callback to VercelRSCAssistantProvider."
1116
- );
1117
- await this.withRunning(this.adapter.reload(parentId));
1118
- }
1119
- cancelRun() {
1120
- if (process.env["NODE_ENV"] === "development") {
1121
- console.warn(
1122
- "Run cancellation is not supported by VercelRSCAssistantProvider."
1123
- );
1124
- }
1125
- }
1126
- subscribe(callback) {
1127
- this._subscriptions.add(callback);
1128
- return () => this._subscriptions.delete(callback);
1129
- }
1130
- onAdapterUpdated() {
1131
- if (this.useAdapter.getState().adapter !== this.adapter) {
1132
- this.useAdapter.setState({ adapter: this.adapter });
1133
- }
1134
- }
1135
- updateData = (messages) => {
1136
- this.messages = messages;
1137
- for (const callback of this._subscriptions) callback();
1138
- };
1139
- unstable_synchronizer = () => {
1140
- const { adapter } = this.useAdapter();
1141
- useVercelRSCSync(adapter, this.updateData);
1142
- return null;
1143
- };
1144
- };
1145
-
1146
- // ../react-ai-sdk/src/rsc/useVercelRSCRuntime.tsx
1147
- var useVercelRSCRuntime = (adapter) => {
1148
- const [runtime] = useState3(() => new VercelRSCRuntime(adapter));
1149
- useInsertionEffect(() => {
1150
- runtime.adapter = adapter;
1151
- });
1152
- useEffect7(() => {
1153
- runtime.onAdapterUpdated();
1154
- });
1155
- return runtime;
1156
- };
1157
-
1158
- // ../react-ai-sdk/src/ui/use-chat/useVercelUseChatRuntime.tsx
1159
- import { useEffect as useEffect10, useInsertionEffect as useInsertionEffect2, useState as useState4 } from "react";
1160
-
1161
- // ../react-ai-sdk/src/ui/VercelAIRuntime.tsx
1162
- import { create as create5 } from "zustand";
1163
-
1164
- // ../react-ai-sdk/src/ui/getVercelAIMessage.tsx
1165
- var symbolInnerAIMessage = Symbol("innerVercelAIUIMessage");
1166
- var getVercelAIMessage = (message) => {
1167
- return message[symbolInnerAIMessage];
1168
- };
1169
-
1170
- // ../react-ai-sdk/src/ui/utils/sliceMessagesUntil.tsx
1171
- var sliceMessagesUntil = (messages, messageId) => {
1172
- if (messageId == null) return [];
1173
- let messageIdx = messages.findIndex((m) => m.id === messageId);
1174
- if (messageIdx === -1)
1175
- throw new Error(
1176
- "useVercelAIThreadState: Message not found. This is liekly an internal bug in assistant-ui."
1177
- );
1178
- while (messages[messageIdx + 1]?.role === "assistant") {
1179
- messageIdx++;
1180
- }
1181
- return messages.slice(0, messageIdx + 1);
1182
- };
1183
-
1184
- // ../react-ai-sdk/src/ui/utils/useVercelAIComposerSync.tsx
1185
- import { useEffect as useEffect8 } from "react";
1186
- var useVercelAIComposerSync = (vercel) => {
1187
- const { useComposer } = useThreadContext();
1188
- useEffect8(() => {
1189
- useComposer.setState({
1190
- value: vercel.input,
1191
- setValue: vercel.setInput
1192
- });
1193
- }, [useComposer, vercel.input, vercel.setInput]);
1194
- };
1195
-
1196
- // ../react-ai-sdk/src/ui/utils/useVercelAIThreadSync.tsx
1197
- import { useEffect as useEffect9, useMemo as useMemo5 } from "react";
1198
- var getIsRunning = (vercel) => {
1199
- if ("isLoading" in vercel) return vercel.isLoading;
1200
- return vercel.status === "in_progress";
1201
- };
1202
- var vercelToThreadMessage2 = (messages, status) => {
1203
- const firstMessage = messages[0];
1204
- if (!firstMessage) throw new Error("No messages found");
1205
- const common = {
1206
- id: firstMessage.id,
1207
- createdAt: firstMessage.createdAt ?? /* @__PURE__ */ new Date(),
1208
- [symbolInnerAIMessage]: messages
1209
- };
1210
- switch (firstMessage.role) {
1211
- case "user":
1212
- if (messages.length > 1) {
1213
- throw new Error(
1214
- "Multiple user messages found. This is likely an internal bug in assistant-ui."
1215
- );
1216
- }
1217
- return {
1218
- ...common,
1219
- role: "user",
1220
- content: [{ type: "text", text: firstMessage.content }]
1221
- };
1222
- case "assistant":
1223
- return {
1224
- ...common,
1225
- role: "assistant",
1226
- content: messages.flatMap((message) => [
1227
- ...message.content ? [{ type: "text", text: message.content }] : [],
1228
- ...message.toolInvocations?.map(
1229
- (t) => ({
1230
- type: "tool-call",
1231
- name: t.toolName,
1232
- args: t.args,
1233
- result: "result" in t ? t.result : void 0
1234
- })
1235
- ) ?? []
1236
- ]),
1237
- status
1238
- };
1239
- default:
1240
- throw new Error(
1241
- `You have a message with an unsupported role. The role ${firstMessage.role} is not supported.`
1242
- );
1243
- }
1244
- };
1245
- var hasItems = (messages) => messages.length > 0;
1246
- var chunkedMessages = (messages) => {
1247
- const chunks = [];
1248
- let currentChunk = [];
1249
- for (const message of messages) {
1250
- if (message.role === "assistant") {
1251
- currentChunk.push(message);
1252
- } else {
1253
- if (hasItems(currentChunk)) {
1254
- chunks.push(currentChunk);
1255
- currentChunk = [];
1256
- }
1257
- chunks.push([message]);
1258
- }
1259
- }
1260
- if (hasItems(currentChunk)) {
1261
- chunks.push(currentChunk);
1262
- }
1263
- return chunks;
1264
- };
1265
- var shallowArrayEqual = (a, b) => {
1266
- if (a.length !== b.length) return false;
1267
- for (let i = 0; i < a.length; i++) {
1268
- if (a[i] !== b[i]) return false;
988
+ _configProviders = /* @__PURE__ */ new Set();
989
+ abortController = null;
990
+ repository = new MessageRepository();
991
+ get messages() {
992
+ return this.repository.getMessages();
1269
993
  }
1270
- return true;
1271
- };
1272
- var useVercelAIThreadSync = (vercel, updateData) => {
1273
- const isRunning = getIsRunning(vercel);
1274
- const converter = useMemo5(() => new ThreadMessageConverter(), []);
1275
- useEffect9(() => {
1276
- const lastMessageId = vercel.messages.at(-1)?.id;
1277
- const convertCallback = (messages2, cache) => {
1278
- const status = lastMessageId === messages2[0].id && isRunning ? "in_progress" : "done";
1279
- if (cache && shallowArrayEqual(cache.content, messages2) && (cache.role === "user" || cache.status === status))
1280
- return cache;
1281
- return vercelToThreadMessage2(messages2, status);
1282
- };
1283
- const messages = converter.convertMessages(
1284
- chunkedMessages(vercel.messages),
1285
- convertCallback,
1286
- (m) => m[0]
1287
- );
1288
- updateData(isRunning, messages);
1289
- }, [updateData, isRunning, vercel.messages, converter]);
1290
- };
1291
-
1292
- // ../react-ai-sdk/src/ui/VercelAIRuntime.tsx
1293
- var hasUpcomingMessage = (isRunning, messages) => {
1294
- return isRunning && messages[messages.length - 1]?.role !== "assistant";
1295
- };
1296
- var VercelAIRuntime = class {
1297
- constructor(vercel) {
1298
- this.vercel = vercel;
1299
- this.useVercel = create5(() => ({
1300
- vercel
1301
- }));
994
+ get isRunning() {
995
+ return this.abortController != null;
1302
996
  }
1303
- _subscriptions = /* @__PURE__ */ new Set();
1304
- repository = new MessageRepository();
1305
- assistantOptimisticId = null;
1306
- useVercel;
1307
- messages = [];
1308
- isRunning = false;
1309
997
  getBranches(messageId) {
1310
998
  return this.repository.getBranches(messageId);
1311
999
  }
1312
1000
  switchToBranch(branchId) {
1313
1001
  this.repository.switchToBranch(branchId);
1314
- this.updateVercelMessages(this.repository.getMessages());
1002
+ this.notifySubscribers();
1315
1003
  }
1316
1004
  async append(message) {
1317
- if (message.content.length !== 1 || message.content[0]?.type !== "text")
1318
- throw new Error("Only text content is supported by Vercel AI SDK.");
1319
- const newMessages = sliceMessagesUntil(
1320
- this.vercel.messages,
1321
- message.parentId
1322
- );
1323
- this.vercel.setMessages(newMessages);
1324
- await this.vercel.append({
1005
+ const userMessageId = generateId();
1006
+ const userMessage = {
1007
+ id: userMessageId,
1325
1008
  role: "user",
1326
- content: message.content[0].text
1327
- });
1009
+ content: message.content,
1010
+ createdAt: /* @__PURE__ */ new Date()
1011
+ };
1012
+ this.repository.addOrUpdateMessage(message.parentId, userMessage);
1013
+ await this.startRun(userMessageId);
1328
1014
  }
1329
1015
  async startRun(parentId) {
1330
- const reloadMaybe = "reload" in this.vercel ? this.vercel.reload : void 0;
1331
- if (!reloadMaybe)
1332
- throw new Error(
1333
- "Reload is not supported by Vercel AI SDK's useAssistant."
1334
- );
1335
- const newMessages = sliceMessagesUntil(this.vercel.messages, parentId);
1336
- this.vercel.setMessages(newMessages);
1337
- await reloadMaybe();
1016
+ const id = generateId();
1017
+ this.repository.resetHead(parentId);
1018
+ const messages = this.repository.getMessages();
1019
+ const message = {
1020
+ id,
1021
+ role: "assistant",
1022
+ status: "in_progress",
1023
+ content: [{ type: "text", text: "" }],
1024
+ createdAt: /* @__PURE__ */ new Date()
1025
+ };
1026
+ this.repository.addOrUpdateMessage(parentId, { ...message });
1027
+ this.abortController?.abort();
1028
+ this.abortController = new AbortController();
1029
+ this.notifySubscribers();
1030
+ try {
1031
+ const updateHandler = ({ content }) => {
1032
+ message.content = content;
1033
+ this.repository.addOrUpdateMessage(parentId, { ...message });
1034
+ this.notifySubscribers();
1035
+ };
1036
+ const result = await this.adapter.run({
1037
+ messages,
1038
+ abortSignal: this.abortController.signal,
1039
+ config: mergeModelConfigs([...this._configProviders].map((p) => p())),
1040
+ onUpdate: updateHandler
1041
+ });
1042
+ updateHandler(result);
1043
+ message.status = "done";
1044
+ this.repository.addOrUpdateMessage(parentId, { ...message });
1045
+ } catch (e) {
1046
+ message.status = "error";
1047
+ this.repository.addOrUpdateMessage(parentId, { ...message });
1048
+ console.error(e);
1049
+ } finally {
1050
+ this.abortController = null;
1051
+ this.notifySubscribers();
1052
+ }
1338
1053
  }
1339
1054
  cancelRun() {
1340
- const previousMessage = this.vercel.messages.at(-1);
1341
- this.vercel.stop();
1342
- if (this.assistantOptimisticId) {
1343
- this.repository.deleteMessage(this.assistantOptimisticId);
1344
- this.assistantOptimisticId = null;
1345
- }
1346
- let messages = this.repository.getMessages();
1347
- if (previousMessage?.role === "user" && previousMessage.id === messages.at(-1)?.id) {
1348
- this.vercel.setInput(previousMessage.content);
1349
- this.repository.deleteMessage(previousMessage.id);
1350
- messages = this.repository.getMessages();
1351
- }
1352
- setTimeout(() => {
1353
- this.updateVercelMessages(messages);
1354
- }, 0);
1055
+ if (!this.abortController) return;
1056
+ this.abortController.abort();
1057
+ this.abortController = null;
1058
+ this.notifySubscribers();
1059
+ }
1060
+ notifySubscribers() {
1061
+ for (const callback of this._subscriptions) callback();
1355
1062
  }
1356
1063
  subscribe(callback) {
1357
1064
  this._subscriptions.add(callback);
1358
1065
  return () => this._subscriptions.delete(callback);
1359
1066
  }
1360
- updateVercelMessages = (messages) => {
1361
- this.vercel.setMessages(
1362
- messages.flatMap(getVercelAIMessage).filter((m) => m != null)
1363
- );
1364
- };
1365
- onVercelUpdated() {
1366
- if (this.useVercel.getState().vercel !== this.vercel) {
1367
- this.useVercel.setState({ vercel: this.vercel });
1368
- }
1067
+ registerModelConfigProvider(provider) {
1068
+ this._configProviders.add(provider);
1069
+ return () => this._configProviders.delete(provider);
1369
1070
  }
1370
- updateData = (isRunning, vm) => {
1371
- for (let i = 0; i < vm.length; i++) {
1372
- const message = vm[i];
1373
- const parent = vm[i - 1];
1374
- this.repository.addOrUpdateMessage(parent?.id ?? null, message);
1375
- }
1376
- if (this.assistantOptimisticId) {
1377
- this.repository.deleteMessage(this.assistantOptimisticId);
1378
- this.assistantOptimisticId = null;
1379
- }
1380
- if (hasUpcomingMessage(isRunning, vm)) {
1381
- this.assistantOptimisticId = this.repository.appendOptimisticMessage(
1382
- vm.at(-1)?.id ?? null,
1383
- {
1384
- role: "assistant",
1385
- content: [{ type: "text", text: "" }]
1386
- }
1387
- );
1388
- }
1389
- this.repository.resetHead(
1390
- this.assistantOptimisticId ?? vm.at(-1)?.id ?? null
1391
- );
1392
- this.messages = this.repository.getMessages();
1393
- this.isRunning = isRunning;
1394
- for (const callback of this._subscriptions) callback();
1395
- };
1396
- unstable_synchronizer = () => {
1397
- const { vercel } = this.useVercel();
1398
- useVercelAIThreadSync(vercel, this.updateData);
1399
- useVercelAIComposerSync(vercel);
1400
- return null;
1401
- };
1402
1071
  };
1403
1072
 
1404
- // ../react-ai-sdk/src/ui/use-chat/useVercelUseChatRuntime.tsx
1405
- var useVercelUseChatRuntime = (chatHelpers) => {
1406
- const [runtime] = useState4(() => new VercelAIRuntime(chatHelpers));
1407
- useInsertionEffect2(() => {
1408
- runtime.vercel = chatHelpers;
1409
- });
1410
- useEffect10(() => {
1411
- runtime.onVercelUpdated();
1073
+ // src/runtime/local/useLocalRuntime.tsx
1074
+ var useLocalRuntime = (adapter) => {
1075
+ const [runtime] = useState3(() => new LocalRuntime(adapter));
1076
+ useInsertionEffect(() => {
1077
+ runtime.adapter = adapter;
1412
1078
  });
1413
1079
  return runtime;
1414
1080
  };
1415
1081
 
1416
- // ../react-ai-sdk/src/ui/use-assistant/useVercelUseAssistantRuntime.tsx
1417
- import { useEffect as useEffect11, useInsertionEffect as useInsertionEffect3, useState as useState5 } from "react";
1418
- var useVercelUseAssistantRuntime = (assistantHelpers) => {
1419
- const [runtime] = useState5(() => new VercelAIRuntime(assistantHelpers));
1420
- useInsertionEffect3(() => {
1421
- runtime.vercel = assistantHelpers;
1422
- });
1423
- useEffect11(() => {
1424
- runtime.onVercelUpdated();
1425
- });
1426
- return runtime;
1427
- };
1082
+ // src/context/providers/AssistantRuntimeProvider.tsx
1083
+ import { memo } from "react";
1428
1084
 
1429
- // src/runtime/utils/idUtils.tsx
1430
- import { customAlphabet } from "nanoid/non-secure";
1431
- var generateId = customAlphabet(
1432
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
1433
- 7
1434
- );
1435
- var optimisticPrefix = "__optimistic__";
1436
- var generateOptimisticId = () => `${optimisticPrefix}${generateId()}`;
1085
+ // src/context/providers/AssistantProvider.tsx
1086
+ import { useEffect as useEffect7, useInsertionEffect as useInsertionEffect3, useRef as useRef5, useState as useState5 } from "react";
1437
1087
 
1438
- // src/runtime/utils/MessageRepository.tsx
1439
- var findHead = (message) => {
1440
- if (message.next) return findHead(message.next);
1441
- return message;
1442
- };
1443
- var MessageRepository = class {
1444
- messages = /* @__PURE__ */ new Map();
1445
- // message_id -> item
1446
- head = null;
1447
- root = {
1448
- children: []
1449
- };
1450
- performOp(newParent, child, operation) {
1451
- const parentOrRoot = child.prev ?? this.root;
1452
- const newParentOrRoot = newParent ?? this.root;
1453
- if (operation === "relink" && parentOrRoot === newParentOrRoot) return;
1454
- if (operation !== "link") {
1455
- parentOrRoot.children = parentOrRoot.children.filter(
1456
- (m) => m !== child.current.id
1457
- );
1458
- if (child.prev?.next === child) {
1459
- const fallbackId = child.prev.children.at(-1);
1460
- const fallback = fallbackId ? this.messages.get(fallbackId) : null;
1461
- if (fallback === void 0) {
1462
- throw new Error(
1463
- "MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui."
1464
- );
1465
- }
1466
- child.prev.next = fallback;
1467
- }
1468
- }
1469
- if (operation !== "cut") {
1470
- newParentOrRoot.children = [
1471
- ...newParentOrRoot.children,
1472
- child.current.id
1473
- ];
1474
- if (newParent && (findHead(child) === this.head || newParent.next === null)) {
1475
- newParent.next = child;
1476
- }
1477
- child.prev = newParent;
1478
- }
1479
- }
1480
- getMessages() {
1481
- const messages = new Array(this.head?.level ?? 0);
1482
- for (let current = this.head; current; current = current.prev) {
1483
- messages[current.level] = current.current;
1484
- }
1485
- return messages;
1486
- }
1487
- addOrUpdateMessage(parentId, message) {
1488
- const existingItem = this.messages.get(message.id);
1489
- const prev = parentId ? this.messages.get(parentId) : null;
1490
- if (prev === void 0)
1491
- throw new Error(
1492
- "MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui."
1493
- );
1494
- if (existingItem) {
1495
- existingItem.current = message;
1496
- this.performOp(prev, existingItem, "relink");
1497
- return;
1498
- }
1499
- const newItem = {
1500
- prev,
1501
- current: message,
1502
- next: null,
1503
- children: [],
1504
- level: prev ? prev.level + 1 : 0
1505
- };
1506
- this.messages.set(message.id, newItem);
1507
- this.performOp(prev, newItem, "link");
1508
- if (this.head === prev) {
1509
- this.head = newItem;
1510
- }
1511
- }
1512
- appendOptimisticMessage(parentId, message) {
1513
- let optimisticId;
1514
- do {
1515
- optimisticId = generateOptimisticId();
1516
- } while (this.messages.has(optimisticId));
1517
- this.addOrUpdateMessage(parentId, {
1518
- ...message,
1519
- id: optimisticId,
1520
- createdAt: /* @__PURE__ */ new Date(),
1521
- ...message.role === "assistant" ? { status: "in_progress" } : void 0
1522
- });
1523
- return optimisticId;
1524
- }
1525
- deleteMessage(messageId, replacementId) {
1526
- const message = this.messages.get(messageId);
1527
- if (!message)
1528
- throw new Error(
1529
- "MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui."
1530
- );
1531
- const replacement = replacementId === void 0 ? message.prev : replacementId === null ? null : this.messages.get(replacementId);
1532
- if (replacement === void 0)
1533
- throw new Error(
1534
- "MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui."
1535
- );
1536
- for (const child of message.children) {
1537
- const childMessage = this.messages.get(child);
1538
- if (!childMessage)
1539
- throw new Error(
1540
- "MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui."
1541
- );
1542
- this.performOp(replacement, childMessage, "relink");
1543
- }
1544
- this.performOp(null, message, "cut");
1545
- this.messages.delete(messageId);
1546
- if (this.head === message) {
1547
- this.head = replacement ? findHead(replacement) : null;
1548
- }
1549
- }
1550
- getBranches(messageId) {
1551
- const message = this.messages.get(messageId);
1552
- if (!message)
1553
- throw new Error(
1554
- "MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui."
1555
- );
1556
- const { children } = message.prev ?? this.root;
1557
- return children;
1558
- }
1559
- switchToBranch(messageId) {
1560
- const message = this.messages.get(messageId);
1561
- if (!message)
1562
- throw new Error(
1563
- "MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui."
1564
- );
1565
- if (message.prev) {
1566
- message.prev.next = message;
1567
- }
1568
- this.head = findHead(message);
1569
- }
1570
- resetHead(messageId) {
1571
- if (messageId === null) {
1572
- this.head = null;
1573
- return;
1574
- }
1575
- const message = this.messages.get(messageId);
1576
- if (!message)
1577
- throw new Error(
1578
- "MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui."
1579
- );
1580
- this.head = message;
1581
- for (let current = message; current; current = current.prev) {
1582
- if (current.prev) {
1583
- current.prev.next = current;
1584
- }
1088
+ // src/context/stores/AssistantModelConfig.ts
1089
+ import { create as create4 } from "zustand";
1090
+ var makeAssistantModelConfigStore = () => create4(() => {
1091
+ const proxy = new ProxyConfigProvider();
1092
+ return {
1093
+ getModelConfig: () => {
1094
+ return proxy.getModelConfig();
1095
+ },
1096
+ registerModelConfigProvider: (provider) => {
1097
+ return proxy.registerModelConfigProvider(provider);
1585
1098
  }
1586
- }
1587
- };
1588
-
1589
- // src/context/providers/AssistantRuntimeProvider.tsx
1590
- import { memo } from "react";
1099
+ };
1100
+ });
1591
1101
 
1592
1102
  // src/context/providers/ThreadProvider.tsx
1593
- import { useEffect as useEffect12, useInsertionEffect as useInsertionEffect4, useRef as useRef4, useState as useState6 } from "react";
1103
+ import { useEffect as useEffect6, useInsertionEffect as useInsertionEffect2, useRef as useRef4, useState as useState4 } from "react";
1594
1104
 
1595
1105
  // src/context/stores/Composer.ts
1596
- import { create as create6 } from "zustand";
1597
- var makeComposerStore = (useThread) => create6()((set, get, store) => {
1106
+ import { create as create5 } from "zustand";
1107
+ var makeComposerStore = (useThread) => create5()((set, get, store) => {
1598
1108
  return {
1599
1109
  ...makeBaseComposer(set, get, store),
1600
1110
  isEditing: true,
@@ -1616,9 +1126,9 @@ var makeComposerStore = (useThread) => create6()((set, get, store) => {
1616
1126
  });
1617
1127
 
1618
1128
  // src/context/stores/Thread.ts
1619
- import { create as create7 } from "zustand";
1129
+ import { create as create6 } from "zustand";
1620
1130
  var makeThreadStore = (runtimeRef) => {
1621
- const useThread = create7(() => ({
1131
+ const useThread = create6(() => ({
1622
1132
  messages: runtimeRef.current.messages,
1623
1133
  isRunning: runtimeRef.current.isRunning,
1624
1134
  getBranches: (messageId) => runtimeRef.current.getBranches(messageId),
@@ -1640,10 +1150,10 @@ var makeThreadStore = (runtimeRef) => {
1640
1150
  };
1641
1151
 
1642
1152
  // src/context/stores/ThreadViewport.tsx
1643
- import { create as create8 } from "zustand";
1153
+ import { create as create7 } from "zustand";
1644
1154
  var makeThreadViewportStore = () => {
1645
1155
  const scrollToBottomListeners = /* @__PURE__ */ new Set();
1646
- return create8(() => ({
1156
+ return create7(() => ({
1647
1157
  isAtBottom: true,
1648
1158
  scrollToBottom: () => {
1649
1159
  for (const listener of scrollToBottomListeners) {
@@ -1666,10 +1176,10 @@ var ThreadProvider = ({
1666
1176
  runtime
1667
1177
  }) => {
1668
1178
  const runtimeRef = useRef4(runtime);
1669
- useInsertionEffect4(() => {
1179
+ useInsertionEffect2(() => {
1670
1180
  runtimeRef.current = runtime;
1671
1181
  });
1672
- const [{ context, onRuntimeUpdate }] = useState6(() => {
1182
+ const [{ context, onRuntimeUpdate }] = useState4(() => {
1673
1183
  const { useThread, onRuntimeUpdate: onRuntimeUpdate2 } = makeThreadStore(runtimeRef);
1674
1184
  const useViewport = makeThreadViewportStore();
1675
1185
  const useComposer = makeComposerStore(useThread);
@@ -1682,7 +1192,7 @@ var ThreadProvider = ({
1682
1192
  onRuntimeUpdate: onRuntimeUpdate2
1683
1193
  };
1684
1194
  });
1685
- useEffect12(() => {
1195
+ useEffect6(() => {
1686
1196
  onRuntimeUpdate();
1687
1197
  return runtime.subscribe(onRuntimeUpdate);
1688
1198
  }, [onRuntimeUpdate, runtime]);
@@ -1693,145 +1203,30 @@ var ThreadProvider = ({
1693
1203
  ] });
1694
1204
  };
1695
1205
 
1696
- // src/context/providers/AssistantRuntimeProvider.tsx
1206
+ // src/context/providers/AssistantProvider.tsx
1697
1207
  import { jsx as jsx22 } from "react/jsx-runtime";
1698
- var AssistantRuntimeProviderImpl = ({ children, runtime }) => {
1699
- return /* @__PURE__ */ jsx22(ThreadProvider, { runtime, children });
1208
+ var AssistantProvider = ({ children, runtime }) => {
1209
+ const runtimeRef = useRef5(runtime);
1210
+ useInsertionEffect3(() => {
1211
+ runtimeRef.current = runtime;
1212
+ });
1213
+ const [context] = useState5(() => {
1214
+ const useModelConfig = makeAssistantModelConfigStore();
1215
+ return { useModelConfig };
1216
+ });
1217
+ const getModelCOnfig = context.useModelConfig((c) => c.getModelConfig);
1218
+ useEffect7(() => {
1219
+ return runtime.registerModelConfigProvider(getModelCOnfig);
1220
+ }, [runtime, getModelCOnfig]);
1221
+ return /* @__PURE__ */ jsx22(AssistantContext.Provider, { value: context, children: /* @__PURE__ */ jsx22(ThreadProvider, { runtime, children }) });
1700
1222
  };
1701
- var AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);
1702
1223
 
1703
- // src/runtime/vercel-deprecated/VercelAIAssistantProvider.tsx
1224
+ // src/context/providers/AssistantRuntimeProvider.tsx
1704
1225
  import { jsx as jsx23 } from "react/jsx-runtime";
1705
- var VercelUseChatRuntimeProvider = ({
1706
- chat,
1707
- children
1708
- }) => {
1709
- const runtime = useVercelUseChatRuntime(chat);
1710
- return /* @__PURE__ */ jsx23(AssistantRuntimeProvider, { runtime, children });
1711
- };
1712
- var VercelUseAssistantRuntimeProvider = ({
1713
- assistant,
1714
- children
1715
- }) => {
1716
- const runtime = useVercelUseAssistantRuntime(assistant);
1717
- return /* @__PURE__ */ jsx23(AssistantRuntimeProvider, { runtime, children });
1718
- };
1719
- var VercelAIAssistantProvider = ({
1720
- children,
1721
- ...rest
1722
- }) => {
1723
- if ("chat" in rest) {
1724
- return /* @__PURE__ */ jsx23(VercelUseChatRuntimeProvider, { chat: rest.chat, children });
1725
- }
1726
- return /* @__PURE__ */ jsx23(VercelUseAssistantRuntimeProvider, { assistant: rest.assistant, children });
1727
- };
1728
-
1729
- // src/runtime/vercel-deprecated/VercelRSCAssistantProvider.tsx
1730
- import { jsx as jsx24 } from "react/jsx-runtime";
1731
- var VercelRSCAssistantProvider = ({
1732
- children,
1733
- ...adapter
1734
- }) => {
1735
- const runtime = useVercelRSCRuntime(adapter);
1736
- return /* @__PURE__ */ jsx24(AssistantRuntimeProvider, { runtime, children });
1737
- };
1738
-
1739
- // src/runtime/local/useLocalRuntime.tsx
1740
- import { useInsertionEffect as useInsertionEffect5, useState as useState7 } from "react";
1741
-
1742
- // src/runtime/local/LocalRuntime.tsx
1743
- var LocalRuntime = class {
1744
- constructor(adapter) {
1745
- this.adapter = adapter;
1746
- }
1747
- _subscriptions = /* @__PURE__ */ new Set();
1748
- abortController = null;
1749
- repository = new MessageRepository();
1750
- get messages() {
1751
- return this.repository.getMessages();
1752
- }
1753
- get isRunning() {
1754
- return this.abortController != null;
1755
- }
1756
- getBranches(messageId) {
1757
- return this.repository.getBranches(messageId);
1758
- }
1759
- switchToBranch(branchId) {
1760
- this.repository.switchToBranch(branchId);
1761
- this.notifySubscribers();
1762
- }
1763
- async append(message) {
1764
- const userMessageId = generateId();
1765
- const userMessage = {
1766
- id: userMessageId,
1767
- role: "user",
1768
- content: message.content,
1769
- createdAt: /* @__PURE__ */ new Date()
1770
- };
1771
- this.repository.addOrUpdateMessage(message.parentId, userMessage);
1772
- await this.startRun(userMessageId);
1773
- }
1774
- async startRun(parentId) {
1775
- const id = generateId();
1776
- this.repository.resetHead(parentId);
1777
- const messages = this.repository.getMessages();
1778
- const message = {
1779
- id,
1780
- role: "assistant",
1781
- status: "in_progress",
1782
- content: [{ type: "text", text: "" }],
1783
- createdAt: /* @__PURE__ */ new Date()
1784
- };
1785
- this.repository.addOrUpdateMessage(parentId, { ...message });
1786
- this.abortController?.abort();
1787
- this.abortController = new AbortController();
1788
- this.notifySubscribers();
1789
- try {
1790
- const updateHandler = ({ content }) => {
1791
- message.content = content;
1792
- this.repository.addOrUpdateMessage(parentId, { ...message });
1793
- this.notifySubscribers();
1794
- };
1795
- const result = await this.adapter.run({
1796
- messages,
1797
- abortSignal: this.abortController.signal,
1798
- onUpdate: updateHandler
1799
- });
1800
- updateHandler(result);
1801
- message.status = "done";
1802
- this.repository.addOrUpdateMessage(parentId, { ...message });
1803
- } catch (e) {
1804
- message.status = "error";
1805
- this.repository.addOrUpdateMessage(parentId, { ...message });
1806
- console.error(e);
1807
- } finally {
1808
- this.abortController = null;
1809
- this.notifySubscribers();
1810
- }
1811
- }
1812
- cancelRun() {
1813
- if (!this.abortController) return;
1814
- this.abortController.abort();
1815
- this.abortController = null;
1816
- this.notifySubscribers();
1817
- }
1818
- notifySubscribers() {
1819
- for (const callback of this._subscriptions) callback();
1820
- }
1821
- subscribe(callback) {
1822
- this._subscriptions.add(callback);
1823
- return () => this._subscriptions.delete(callback);
1824
- }
1825
- };
1826
-
1827
- // src/runtime/local/useLocalRuntime.tsx
1828
- var useLocalRuntime = (adapter) => {
1829
- const [runtime] = useState7(() => new LocalRuntime(adapter));
1830
- useInsertionEffect5(() => {
1831
- runtime.adapter = adapter;
1832
- });
1833
- return runtime;
1226
+ var AssistantRuntimeProviderImpl = ({ children, runtime }) => {
1227
+ return /* @__PURE__ */ jsx23(AssistantProvider, { runtime, children });
1834
1228
  };
1229
+ var AssistantRuntimeProvider = memo(AssistantRuntimeProviderImpl);
1835
1230
  export {
1836
1231
  actionBar_exports as ActionBarPrimitive,
1837
1232
  AssistantRuntimeProvider,
@@ -1840,23 +1235,11 @@ export {
1840
1235
  contentPart_exports as ContentPartPrimitive,
1841
1236
  message_exports as MessagePrimitive,
1842
1237
  thread_exports as ThreadPrimitive,
1843
- VercelAIAssistantProvider,
1844
- VercelRSCAssistantProvider,
1845
- getVercelAIMessage,
1846
- getVercelRSCMessage,
1847
- MessageRepository as unstable_MessageRepository,
1848
- useComposerContext as unstable_useComposerContext,
1849
- useContentPartContext as unstable_useContentPartContext,
1850
- useLocalRuntime as unstable_useLocalRuntime,
1851
- useMessageContext as unstable_useMessageContext,
1852
- useThreadContext as unstable_useThreadContext,
1853
1238
  useBeginMessageEdit,
1854
1239
  useCopyMessage,
1855
1240
  useGoToNextBranch,
1856
1241
  useGoToPreviousBranch,
1857
- useReloadMessage,
1858
- useVercelRSCRuntime,
1859
- useVercelUseAssistantRuntime,
1860
- useVercelUseChatRuntime
1242
+ useLocalRuntime,
1243
+ useReloadMessage
1861
1244
  };
1862
1245
  //# sourceMappingURL=index.mjs.map