@mujian/js-sdk 0.1.0-beta.1 → 0.1.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -77,8 +77,18 @@ declare class MujianSdk {
77
77
  editOne: (messageId: string, content: string) => Promise<unknown>;
78
78
  swipe: (messageId: string, swipeId: number) => Promise<unknown>;
79
79
  getPage: (fromCursor: import("./types").Cursor | undefined, pageSize: number) => Promise<{
80
+ messages: {
81
+ swipes: (string & import("./react/chat/useChat/message").MessageV2Swipe)[];
82
+ content: string;
83
+ role: string;
84
+ id: string;
85
+ isUser: boolean;
86
+ activeSwipeId: number;
87
+ isGenerating?: boolean;
88
+ finishReason?: string;
89
+ error?: import("./react/chat/useChat/message").ChatError;
90
+ }[];
80
91
  nextCursor?: import("./types").Cursor;
81
- messages: Array<import("./react").Message>;
82
92
  total?: number;
83
93
  conversationVersion: number;
84
94
  }>;
package/dist/index.js CHANGED
@@ -89,10 +89,22 @@ const messageSwipe = async function(messageId, swipeId) {
89
89
  });
90
90
  };
91
91
  async function getPage(fromCursor, pageSize) {
92
- return await this.call(events_EVENT.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE, {
92
+ const resp = await this.call(events_EVENT.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE, {
93
93
  fromCursor,
94
94
  pageSize
95
95
  });
96
+ return {
97
+ ...resp,
98
+ messages: resp.messages.map((m)=>({
99
+ ...m,
100
+ swipes: m.swipes.map((s)=>{
101
+ const ret = Object.assign(s.content, s);
102
+ return ret;
103
+ }),
104
+ content: m.swipes[m.activeSwipeId].content,
105
+ role: m.isUser ? 'user' : 'assistant'
106
+ }))
107
+ };
96
108
  }
97
109
  const getInfo = async function() {
98
110
  return await this.call(events_EVENT.MUJIAN_AI_CHAT_PROJECT_GET_INFO);
@@ -1,5 +1,4 @@
1
1
  import type { MujianSdk } from '../../../../index.ts';
2
- import type { Message } from '../../../../react/chat/useChat/message';
3
2
  import { Cursor } from '../../../../types';
4
3
  /**
5
4
  * 删除消息
@@ -30,9 +29,19 @@ this: MujianSdk, messageId: string, swipeId: number) => Promise<unknown>;
30
29
  export declare function getPage(
31
30
  /** @hidden */
32
31
  this: MujianSdk, fromCursor: Cursor | undefined, pageSize: number): Promise<{
32
+ messages: {
33
+ swipes: (string & import("../../../../react/chat/useChat/message").MessageV2Swipe)[];
34
+ content: string;
35
+ role: string;
36
+ id: string;
37
+ isUser: boolean;
38
+ activeSwipeId: number;
39
+ isGenerating?: boolean;
40
+ finishReason?: string;
41
+ error?: import("../../../../react/chat/useChat/message").ChatError;
42
+ }[];
33
43
  /** 分页游标,若为空则表示无下一页 */
34
44
  nextCursor?: Cursor;
35
- messages: Array<Message>;
36
45
  total?: number;
37
46
  conversationVersion: number;
38
47
  }>;
@@ -4,13 +4,11 @@ export type { Message };
4
4
  /**
5
5
  * Use chat
6
6
  * @param {object} body - The body of the chat.
7
- * @param {function} onError - The function to call when an error occurs.
8
7
  * @param {function} onFinish - The function to call when the chat is finished.
9
8
  * @returns {UseChatReturn} The chat.
10
9
  */
11
10
  export type UseChatProps = {
12
11
  body?: object;
13
- onError?: (e: unknown) => void;
14
12
  onFinish?: (message: Message) => void;
15
13
  /** 消息分页大小,不传时不分页 */
16
14
  pageSize?: number;
@@ -37,7 +35,6 @@ export type UseChatProps = {
37
35
  export type UseChatReturn = {
38
36
  messages: Message[];
39
37
  status: 'uninitialized' | 'ready' | 'streaming' | 'error';
40
- error?: unknown;
41
38
  /** 提交用户输入,让AI回答 */
42
39
  append: (query: string) => Promise<void>;
43
40
  /** 重新生成最后一条回答 */
@@ -54,6 +51,7 @@ export type UseChatReturn = {
54
51
  deleteMessage: (messageId: string) => Promise<void>;
55
52
  loadMoreMessage: () => Promise<void>;
56
53
  messagesStatus: 'all-loaded' | 'loading' | 'has-more' | 'error';
54
+ refresh: () => Promise<void>;
57
55
  };
58
56
  /**
59
57
  * Use chat common
@@ -67,7 +65,6 @@ export type UseChatCommon = {
67
65
  * Use chat
68
66
  * @param {UseChatProps} props - The props of the chat.
69
67
  * @param {object} props.body - The body of the chat.
70
- * @param {function} props.onError - The function to call when an error occurs.
71
68
  * @param {function} props.onFinish - The function to call when the chat is finished.
72
69
  * @param {number} props.pageSize - The page size of the chat.
73
70
  * @returns {UseChatReturn} The chat.
@@ -78,4 +75,4 @@ export type UseChatCommon = {
78
75
  * },
79
76
  * });
80
77
  */
81
- export declare const useChat: ({ body, onError, onFinish, pageSize, }: UseChatProps) => UseChatReturn;
78
+ export declare const useChat: ({ body, onFinish, pageSize, }: UseChatProps) => UseChatReturn;
@@ -4,7 +4,6 @@ import type { UseChatCommon } from '..';
4
4
  import type { Message } from '../message';
5
5
  interface ChatStreamingProps {
6
6
  common: UseChatCommon;
7
- setError: (error: unknown) => void;
8
7
  setMessages: Dispatch<SetStateAction<Message[]>>;
9
8
  getMessages: () => Message[];
10
9
  setInput: (input: string) => void;
@@ -12,7 +11,7 @@ interface ChatStreamingProps {
12
11
  conversationVersion: RefObject<number>;
13
12
  }
14
13
  export declare const NOT_SAVED_MSG_ID_PREFIX = "not_saved";
15
- export declare const useChatStreaming: ({ common, setError, setMessages, getMessages, setInput, mujian, conversationVersion: conversationVersionRef, }: ChatStreamingProps) => {
14
+ export declare const useChatStreaming: ({ common, setMessages, getMessages, setInput, mujian, conversationVersion: conversationVersionRef, }: ChatStreamingProps) => {
16
15
  chatStreaming: ({ query, regenerate, is_continue, conversationVersion, }: {
17
16
  /** 用户输入 */
18
17
  query?: string;
package/dist/react.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { useInfiniteScroll, useLatest, useRequest, useUnmount, useUpdateEffect } from "ahooks";
2
2
  import react, { createContext, forwardRef, useCallback, useContext, useEffect, useRef, useState } from "react";
3
+ import { z } from "zod";
3
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
5
  import css_tools from "@adobe/css-tools";
5
6
  import dompurify from "dompurify";
@@ -9,7 +10,6 @@ import postmate from "postmate";
9
10
  import { Virtualizer } from "virtua";
10
11
  import { get } from "lodash-es";
11
12
  import { produce } from "immer";
12
- import { z } from "zod";
13
13
  const adjustIframeHeight = (iframeId)=>`
14
14
  (function () {
15
15
  let scheduled = false;
@@ -592,10 +592,22 @@ const messageSwipe = async function(messageId, swipeId) {
592
592
  });
593
593
  };
594
594
  async function getPage(fromCursor, pageSize) {
595
- return await this.call(events_EVENT.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE, {
595
+ const resp = await this.call(events_EVENT.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE, {
596
596
  fromCursor,
597
597
  pageSize
598
598
  });
599
+ return {
600
+ ...resp,
601
+ messages: resp.messages.map((m)=>({
602
+ ...m,
603
+ swipes: m.swipes.map((s)=>{
604
+ const ret = Object.assign(s.content, s);
605
+ return ret;
606
+ }),
607
+ content: m.swipes[m.activeSwipeId].content,
608
+ role: m.isUser ? 'user' : 'assistant'
609
+ }))
610
+ };
599
611
  }
600
612
  const getInfo = async function() {
601
613
  return await this.call(events_EVENT.MUJIAN_AI_CHAT_PROJECT_GET_INFO);
@@ -923,7 +935,7 @@ const MessageItem = (props)=>{
923
935
  } } = props;
924
936
  const mujian = useMujian();
925
937
  const { updateMessageTypeWritingCount } = useChatContext();
926
- const lastMessage = useLatest(message);
938
+ const latestMessage = useLatest(message);
927
939
  const [typeWritingPos, setTypeWritingPos] = useState(null);
928
940
  const typeWritingIntervalId = useRef(null);
929
941
  function stopTypeWriting() {
@@ -949,7 +961,7 @@ const MessageItem = (props)=>{
949
961
  setTypeWritingPos((p)=>{
950
962
  const frames = calcTimeFrames();
951
963
  const posIncrement = frames * typingOpts.chunkSize;
952
- const message = lastMessage.current;
964
+ const message = latestMessage.current;
953
965
  const content = message.swipes[message.activeSwipeId].content;
954
966
  const maxPos = content.length;
955
967
  const nextPos = Math.min((p || 0) + posIncrement, maxPos);
@@ -973,6 +985,27 @@ const MessageItem = (props)=>{
973
985
  }, [
974
986
  message.isGenerating
975
987
  ]);
988
+ const prevMessageBrief = useRef(null);
989
+ useEffect(()=>{
990
+ const length = message.swipes[message.activeSwipeId].content.length;
991
+ if (prevMessageBrief.current) {
992
+ const { length: prevLength } = prevMessageBrief.current;
993
+ if (0 === prevLength) setTypeWritingPos(length);
994
+ }
995
+ prevMessageBrief.current = {
996
+ length
997
+ };
998
+ }, [
999
+ message
1000
+ ]);
1001
+ useEffect(()=>{
1002
+ if ('user_stopped' === message.finishReason) {
1003
+ const length = message.swipes[message.activeSwipeId].content.length;
1004
+ setTypeWritingPos(length);
1005
+ }
1006
+ }, [
1007
+ message.finishReason
1008
+ ]);
976
1009
  const { data: renderedMessage } = useRequest(async ()=>{
977
1010
  if (null !== typeWritingPos) {
978
1011
  const pos = typeWritingPos;
@@ -1119,13 +1152,6 @@ const errorMessages = [
1119
1152
  function isNetworkError(message) {
1120
1153
  return errorMessages.some((m)=>message.includes(m));
1121
1154
  }
1122
- class SendMessageError extends Error {
1123
- constructor(message, cause){
1124
- super(message);
1125
- this.name = this.constructor.name;
1126
- this.cause = cause;
1127
- }
1128
- }
1129
1155
  async function* callSdk(mujian, content, type = 'generate', conversationVersion, assisMsgId) {
1130
1156
  const queue = [];
1131
1157
  let resolveWait = null;
@@ -1172,15 +1198,21 @@ async function* callSdk(mujian, content, type = 'generate', conversationVersion,
1172
1198
  resolveWait = resolve;
1173
1199
  });
1174
1200
  }
1201
+ const errorSchema = z.object({
1202
+ message: z.string()
1203
+ });
1204
+ function isError(e) {
1205
+ const { success } = errorSchema.safeParse(e);
1206
+ return success;
1207
+ }
1175
1208
  const NOT_SAVED_MSG_ID_PREFIX = 'not_saved';
1176
- const useChatStreaming = ({ common, setError, setMessages, getMessages, setInput, mujian, conversationVersion: conversationVersionRef })=>{
1209
+ const useChatStreaming = ({ common, setMessages, getMessages, setInput, mujian, conversationVersion: conversationVersionRef })=>{
1177
1210
  const { body } = common;
1178
1211
  const [isStreaming, setIsStreaming] = useState(false);
1179
1212
  const chatStreaming = useCallback(async ({ query, regenerate, is_continue, conversationVersion })=>{
1213
+ const backupMessages = getMessages();
1180
1214
  try {
1181
- setError(void 0);
1182
1215
  setIsStreaming(true);
1183
- const backupMessages = getMessages();
1184
1216
  const userMessage = {
1185
1217
  id: `${NOT_SAVED_MSG_ID_PREFIX}_user_${Date.now()}`,
1186
1218
  isUser: true,
@@ -1204,12 +1236,14 @@ const useChatStreaming = ({ common, setError, setMessages, getMessages, setInput
1204
1236
  isGenerating: true
1205
1237
  };
1206
1238
  if (regenerate) setMessages(produce((draft)=>{
1207
- const lastMessage = draft[draft.length - 1];
1239
+ const lastMessage = draft.at(-1);
1208
1240
  lastMessage.activeSwipeId = lastMessage.swipes.length;
1209
1241
  lastMessage.swipes.push({
1210
1242
  content: ''
1211
1243
  });
1212
1244
  lastMessage.isGenerating = true;
1245
+ lastMessage.finishReason = void 0;
1246
+ lastMessage.error = void 0;
1213
1247
  }));
1214
1248
  else is_continue ? setMessages((prev)=>[
1215
1249
  ...prev,
@@ -1220,50 +1254,62 @@ const useChatStreaming = ({ common, setError, setMessages, getMessages, setInput
1220
1254
  aiMessage
1221
1255
  ]);
1222
1256
  const stream = callSdk(mujian, query || '', is_continue ? 'continue' : regenerate ? 'regenerate' : 'generate', conversationVersion);
1223
- try {
1224
- for await (const chunk of stream){
1225
- if (!chunk) return;
1226
- if ('meta' === chunk.type) {
1227
- if (!regenerate) setMessages(produce((draft)=>{
1228
- if (!is_continue) {
1229
- const userMsg = draft[draft.length - 2];
1230
- userMsg.id = chunk.userMsgId;
1231
- }
1232
- const lastMessage = draft[draft.length - 1];
1233
- lastMessage.id = chunk.assisMsgId;
1234
- }));
1235
- conversationVersionRef.current = chunk.newConversationVersion;
1236
- } else if ('data' === chunk.type) {
1237
- setMessages(produce((draft)=>{
1238
- const lastMessage = draft[draft.length - 1];
1239
- lastMessage.swipes[lastMessage.activeSwipeId] = {
1240
- content: chunk.content,
1241
- mjv: chunk.mjv
1242
- };
1243
- if (chunk.finishReason) lastMessage.finishReason = chunk.finishReason;
1244
- if (chunk.error) lastMessage.error = chunk.error;
1245
- }));
1246
- await new Promise((resolve)=>setTimeout(resolve, 10));
1247
- }
1257
+ for await (const chunk of stream){
1258
+ if (!chunk) return;
1259
+ if ('meta' === chunk.type) {
1260
+ if (!regenerate) setMessages(produce((draft)=>{
1261
+ if (!is_continue) {
1262
+ const userMsg = draft[draft.length - 2];
1263
+ userMsg.id = chunk.userMsgId;
1264
+ }
1265
+ const lastMessage = draft[draft.length - 1];
1266
+ lastMessage.id = chunk.assisMsgId;
1267
+ }));
1268
+ conversationVersionRef.current = chunk.newConversationVersion;
1269
+ } else if ('data' === chunk.type) {
1270
+ setMessages(produce((draft)=>{
1271
+ const lastMessage = draft.at(-1);
1272
+ lastMessage.swipes[lastMessage.activeSwipeId] = {
1273
+ content: chunk.content,
1274
+ mjv: chunk.mjv
1275
+ };
1276
+ if (chunk.finishReason) lastMessage.finishReason = chunk.finishReason;
1277
+ if (chunk.error) lastMessage.error = chunk.error;
1278
+ }));
1279
+ await new Promise((resolve)=>setTimeout(resolve, 10));
1248
1280
  }
1249
- } catch (error) {
1250
- Log.e('Stream error', error);
1251
- if ('object' == typeof error && error && 'message' in error && 'string' == typeof error.message) if ('code' in error && 2011030001 === error.code) {
1252
- setMessages(backupMessages);
1253
- if (!regenerate && !is_continue && query) setInput(query);
1254
- } else isNetworkError(error.message) ? setError(new SendMessageError('E_NETWORK_ERROR')) : setError(new SendMessageError(error.message));
1255
- else setError(error);
1256
- } finally{
1257
- setMessages(produce((draft)=>{
1258
- const lastMessage = draft[draft.length - 1];
1259
- lastMessage.isGenerating = false;
1260
- }));
1261
1281
  }
1262
1282
  } catch (error) {
1263
- console.error('Error:', error);
1264
- setError(new SendMessageError('Send message failed', error));
1265
- setMessages((prev)=>prev.slice(0, -1));
1283
+ Log.e('Stream error', error);
1284
+ setMessages(produce((draft)=>{
1285
+ const lastMessage = draft.at(-1);
1286
+ if (isError(error) && isNetworkError(error.message)) lastMessage.error = {
1287
+ code: -10000,
1288
+ message: 'E_NETWORK_ERROR'
1289
+ };
1290
+ else lastMessage.error = {
1291
+ code: 1000000005,
1292
+ message: String(error)
1293
+ };
1294
+ }));
1266
1295
  } finally{
1296
+ setMessages(produce((draft)=>{
1297
+ const lastMessage = draft[draft.length - 1];
1298
+ lastMessage.isGenerating = false;
1299
+ if (lastMessage.error?.code === 2011030009) {
1300
+ const backup = backupMessages.find((m)=>m.id === lastMessage.id);
1301
+ if (backup) {
1302
+ lastMessage.swipes = backup.swipes;
1303
+ lastMessage.activeSwipeId = backup.activeSwipeId;
1304
+ } else {
1305
+ lastMessage.activeSwipeId -= 1;
1306
+ lastMessage.swipes.length = lastMessage.swipes.length - 1;
1307
+ }
1308
+ } else if (lastMessage.error?.code === 2011030001) {
1309
+ setMessages(backupMessages);
1310
+ query && setInput(query);
1311
+ }
1312
+ }));
1267
1313
  setIsStreaming(false);
1268
1314
  }
1269
1315
  }, [
@@ -1288,8 +1334,17 @@ const useChatStreaming = ({ common, setError, setMessages, getMessages, setInput
1288
1334
  }
1289
1335
  } catch (error) {
1290
1336
  Log.e('Stream error', error);
1291
- if ('object' == typeof error && error && 'message' in error && 'string' == typeof error.message) isNetworkError(error.message) ? setError(new SendMessageError('E_NETWORK_ERROR')) : setError(new SendMessageError(error.message));
1292
- else setError(error);
1337
+ setMessages(produce((draft)=>{
1338
+ const lastMessage = draft.at(-1);
1339
+ if (isError(error) && isNetworkError(error.message)) lastMessage.error = {
1340
+ code: -10000,
1341
+ message: 'E_NETWORK_ERROR'
1342
+ };
1343
+ else lastMessage.error = {
1344
+ code: 1000000005,
1345
+ message: String(error)
1346
+ };
1347
+ }));
1293
1348
  } finally{
1294
1349
  setMessages(produce((draft)=>{
1295
1350
  const msg = draft.find((m)=>m.id === messageId);
@@ -1306,17 +1361,12 @@ const useChatStreaming = ({ common, setError, setMessages, getMessages, setInput
1306
1361
  recoverStreaming
1307
1362
  };
1308
1363
  };
1309
- const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1310
- const [error, _setError] = useState();
1364
+ const useChat = ({ body, onFinish, pageSize = 10 })=>{
1311
1365
  const [input, setInput] = useState('');
1312
1366
  const conversationVersion = useRef(0);
1313
1367
  const mujian = useMujian();
1314
- const setError = (error)=>{
1315
- _setError(error);
1316
- if (error) onError?.(error);
1317
- };
1318
1368
  const isLoadingMore = useRef(false);
1319
- const { data, loadMoreAsync, loadingMore, loading, mutate, error: messageLoadError } = useInfiniteScroll(async (current)=>{
1369
+ const { data, loadMoreAsync, loadingMore, loading, mutate, error: messageLoadError, reloadAsync } = useInfiniteScroll(async (current)=>{
1320
1370
  isLoadingMore.current = true;
1321
1371
  if (current?.noMore) return {
1322
1372
  noMore: true,
@@ -1338,6 +1388,9 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1338
1388
  }, {
1339
1389
  direction: 'top'
1340
1390
  });
1391
+ const refresh = async ()=>{
1392
+ await reloadAsync();
1393
+ };
1341
1394
  const loadMoreMessage = async ()=>{
1342
1395
  if (isLoadingMore.current) return;
1343
1396
  try {
@@ -1367,7 +1420,6 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1367
1420
  common: {
1368
1421
  body
1369
1422
  },
1370
- setError,
1371
1423
  setMessages,
1372
1424
  getMessages,
1373
1425
  setInput,
@@ -1384,15 +1436,10 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1384
1436
  ]);
1385
1437
  const append = useCallback(async (query)=>{
1386
1438
  if (isStreaming) throw new Error('useChat is streaming already.');
1387
- try {
1388
- await chatStreaming({
1389
- query,
1390
- conversationVersion: conversationVersion.current
1391
- });
1392
- } catch (e) {
1393
- setError(e);
1394
- throw e;
1395
- }
1439
+ await chatStreaming({
1440
+ query,
1441
+ conversationVersion: conversationVersion.current
1442
+ });
1396
1443
  }, [
1397
1444
  isStreaming,
1398
1445
  chatStreaming
@@ -1400,17 +1447,12 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1400
1447
  const regenerate = useCallback(async ()=>{
1401
1448
  if (isStreaming) throw new Error('useChat is streaming already.');
1402
1449
  const lastMessage = messages.findLast((message)=>message.isUser);
1403
- try {
1404
- const query = lastMessage ? lastMessage.swipes[lastMessage.activeSwipeId].content : '';
1405
- await chatStreaming({
1406
- query,
1407
- regenerate: true,
1408
- conversationVersion: conversationVersion.current
1409
- });
1410
- } catch (e) {
1411
- setError(e);
1412
- throw e;
1413
- }
1450
+ const query = lastMessage ? lastMessage.swipes[lastMessage.activeSwipeId].content : '';
1451
+ await chatStreaming({
1452
+ query,
1453
+ regenerate: true,
1454
+ conversationVersion: conversationVersion.current
1455
+ });
1414
1456
  }, [
1415
1457
  isStreaming,
1416
1458
  messages,
@@ -1418,16 +1460,11 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1418
1460
  ]);
1419
1461
  const continueGenerate = useCallback(async ()=>{
1420
1462
  if (isStreaming) throw new Error('useChat is streaming already.');
1421
- try {
1422
- await chatStreaming({
1423
- query: '',
1424
- is_continue: true,
1425
- conversationVersion: conversationVersion.current
1426
- });
1427
- } catch (e) {
1428
- setError(e);
1429
- throw e;
1430
- }
1463
+ await chatStreaming({
1464
+ query: '',
1465
+ is_continue: true,
1466
+ conversationVersion: conversationVersion.current
1467
+ });
1431
1468
  }, [
1432
1469
  isStreaming,
1433
1470
  chatStreaming
@@ -1435,14 +1472,19 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1435
1472
  const stop = ()=>{
1436
1473
  const assisMsgId = messages.at(-1)?.id;
1437
1474
  if (!assisMsgId) return;
1438
- mujian.ai.chat.stop(conversationVersion.current, assisMsgId);
1475
+ mujian.ai.chat.stop(conversationVersion.current, assisMsgId).then(()=>{
1476
+ setMessages(produce((draft)=>{
1477
+ const lastMessage = draft.at(-1);
1478
+ if (lastMessage?.finishReason) lastMessage.finishReason = 'user_stopped';
1479
+ }));
1480
+ });
1439
1481
  };
1440
1482
  const setSwipe = async (messageId, swipeId)=>{
1441
1483
  if (swipeId < 0) return;
1442
- setMessages((prev)=>prev.map((msg)=>msg.id === messageId && swipeId < msg.swipes.length ? {
1443
- ...msg,
1444
- activeSwipeId: swipeId
1445
- } : msg));
1484
+ setMessages(produce((draft)=>{
1485
+ const msg = draft.find((m)=>m.id === messageId);
1486
+ if (msg) msg.activeSwipeId = swipeId;
1487
+ }));
1446
1488
  const resp = await mujian.ai.chat.message.swipe(messageId, swipeId);
1447
1489
  const schema = z.object({
1448
1490
  newConversationVersion: z.number()
@@ -1457,20 +1499,10 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1457
1499
  });
1458
1500
  const { data, success } = schema.safeParse(resp);
1459
1501
  if (success && data.newConversationVersion) conversationVersion.current = data.newConversationVersion;
1460
- const patchMessage = (msg)=>{
1461
- const newMsg = {
1462
- ...msg,
1463
- content
1464
- };
1465
- if (!newMsg.isUser) {
1466
- newMsg.swipes = [
1467
- ...newMsg.swipes
1468
- ];
1469
- newMsg.swipes[newMsg.activeSwipeId].content = content;
1470
- }
1471
- return newMsg;
1472
- };
1473
- setMessages((prev)=>prev.map((msg)=>msg.id === messageId ? patchMessage(msg) : msg));
1502
+ setMessages(produce((draft)=>{
1503
+ const msg = draft.find((msg)=>msg.id === messageId);
1504
+ if (msg) msg.swipes[msg.activeSwipeId].content = content;
1505
+ }));
1474
1506
  };
1475
1507
  const deleteMessage = async (messageId)=>{
1476
1508
  if (!messageId.startsWith(NOT_SAVED_MSG_ID_PREFIX)) try {
@@ -1492,11 +1524,9 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1492
1524
  stop,
1493
1525
  messages: messages,
1494
1526
  status: (()=>{
1495
- if (error) return 'error';
1496
1527
  if (isStreaming) return 'streaming';
1497
1528
  return 'ready';
1498
1529
  })(),
1499
- error,
1500
1530
  setMessages: setMessages,
1501
1531
  input,
1502
1532
  setInput,
@@ -1507,7 +1537,8 @@ const useChat = ({ body, onError, onFinish, pageSize = 10 })=>{
1507
1537
  editMessage,
1508
1538
  deleteMessage,
1509
1539
  loadMoreMessage,
1510
- messagesStatus: messageLoadError ? 'error' : loadingMore || loading ? 'loading' : data?.noMore ? 'all-loaded' : 'has-more'
1540
+ messagesStatus: messageLoadError ? 'error' : loadingMore || loading ? 'loading' : data?.noMore ? 'all-loaded' : 'has-more',
1541
+ refresh
1511
1542
  };
1512
1543
  };
1513
1544
  export { MdRenderer, MujianProvider, MujianSpinner, Thread, useChat, useChatContext, useMjEngine, useMujian };
package/dist/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.MujianUMD=e():t.MujianUMD=e()}(globalThis,()=>(()=>{"use strict";var t,e={};e.d=(t,i)=>{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},e.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),e.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};e.r(i),e.d(i,{MujianSdk:()=>G,EVENT:()=>u});var n="application/x-postmate-v1+json",a=0,s=function(t){var e=document.createElement("a");e.href=t;var i=e.protocol.length>4?e.protocol:window.location.protocol,n=e.host.length?"80"===e.port||"443"===e.port?e.hostname:e.host:window.location.host;return e.origin||i+"//"+n},r={handshake:1,"handshake-reply":1,call:1,emit:1,reply:1,request:1},o=function(t,e){return("string"!=typeof e||t.origin===e)&&!!t.data&&("object"!=typeof t.data||"postmate"in t.data)&&t.data.type===n&&!!r[t.data.postmate]},c=function(t,e){var i="function"==typeof t[e]?t[e]():t[e];return h.Promise.resolve(i)},l=function(){function t(t){var e=this;this.parent=t.parent,this.frame=t.frame,this.child=t.child,this.childOrigin=t.childOrigin,this.events={},this.listener=function(t){if(!o(t,e.childOrigin))return!1;var i=((t||{}).data||{}).value||{},n=i.data,a=i.name;"emit"===t.data.postmate&&a in e.events&&e.events[a].call(e,n)},this.parent.addEventListener("message",this.listener,!1)}var e=t.prototype;return e.get=function(t){var e=this;return new h.Promise(function(i){var s=++a;e.parent.addEventListener("message",function t(n){n.data.uid===s&&"reply"===n.data.postmate&&(e.parent.removeEventListener("message",t,!1),i(n.data.value))},!1),e.child.postMessage({postmate:"request",type:n,property:t,uid:s},e.childOrigin)})},e.call=function(t,e){this.child.postMessage({postmate:"call",type:n,property:t,data:e},this.childOrigin)},e.on=function(t,e){this.events[t]=e},e.destroy=function(){window.removeEventListener("message",this.listener,!1),this.frame.parentNode.removeChild(this.frame)},t}(),d=function(){function t(t){var e=this;this.model=t.model,this.parent=t.parent,this.parentOrigin=t.parentOrigin,this.child=t.child,this.child.addEventListener("message",function(t){if(o(t,e.parentOrigin)){var i=t.data,a=i.property,s=i.uid,r=i.data;if("call"===t.data.postmate){a in e.model&&"function"==typeof e.model[a]&&e.model[a](r);return}c(e.model,a).then(function(e){return t.source.postMessage({property:a,postmate:"reply",type:n,uid:s,value:e},t.origin)})}})}return t.prototype.emit=function(t,e){this.parent.postMessage({postmate:"emit",type:n,value:{name:t,data:e}},this.parentOrigin)},t}(),h=function(){function t(t){var e=t.container,i=void 0===e?void 0!==i?i:document.body:e,n=t.model,a=t.url,s=t.name,r=t.classListArray;return this.parent=window,this.frame=document.createElement("iframe"),this.frame.name=s||"",this.frame.classList.add.apply(this.frame.classList,void 0===r?[]:r),i.appendChild(this.frame),this.child=this.frame.contentWindow||this.frame.contentDocument.parentWindow,this.model=n||{},this.sendHandshake(a)}return t.prototype.sendHandshake=function(e){var i,a=this,r=s(e),c=0;return new t.Promise(function(t,s){a.parent.addEventListener("message",function e(n){return!!o(n,r)&&("handshake-reply"===n.data.postmate?(clearInterval(i),a.parent.removeEventListener("message",e,!1),a.childOrigin=n.origin,t(new l(a))):s("Failed handshake"))},!1);var d=function(){c++,a.child.postMessage({postmate:"handshake",type:n,model:a.model},r),5===c&&clearInterval(i)},h=function(){d(),i=setInterval(d,500)};a.frame.attachEvent?a.frame.attachEvent("onload",h):a.frame.onload=h,a.frame.src=e})},t}();h.debug=!1,h.Promise=function(){try{return window?window.Promise:Promise}catch(t){return null}}(),h.Model=function(){function t(t){return this.child=window,this.model=t,this.parent=this.child.parent,this.sendHandshakeReply()}return t.prototype.sendHandshakeReply=function(){var t=this;return new h.Promise(function(e,i){t.child.addEventListener("message",function a(s){if(s.data.postmate){if("handshake"===s.data.postmate){t.child.removeEventListener("message",a,!1),s.source.postMessage({postmate:"handshake-reply",type:n},s.origin),t.parentOrigin=s.origin;var r=s.data.model;return r&&Object.keys(r).forEach(function(e){t.model[e]=r[e]}),e(new d(t))}return i("Handshake Reply Failed")}},!1)})},t}();var u=((t={}).MUJIAN_INIT="mujian:init",t.MUJIAN_AI_CHAT_STOP="mujian:ai:chat:stop",t.MUJIAN_AI_CHAT_COMPLETE="mujian:ai:chat:complete",t.MUJIAN_AI_CHAT_APPLY_REGEX="mujian:ai:chat:applyRegex",t.MUJIAN_AI_CHAT_RENDER_MESSAGE="mujian:ai:chat:renderMessage",t.MUJIAN_AI_TEXT_GENERATE="mujian:ai:text:generate",t.MUJIAN_AI_OPENAI_COMPLETIONS_CREATE="mujian:ai:openai:completions:create",t.MUJIAN_AI_OPENAI_CHAT_COMPLETIONS_CREATE="mujian:ai:openai:chat:completions:create",t.MUJIAN_AI_OPENAI_RESPONSES_CREATE="mujian:ai:openai:responses:create",t.MUJIAN_AI_CHAT_MESSAGE_GET_ALL="mujian:ai:chat:message:getAll",t.MUJIAN_AI_CHAT_MESSAGE_GET_PAGE="mujian:ai:chat:message:getPage",t.MUJIAN_AI_CHAT_PROJECT_GET_INFO="mujian:ai:chat:project:getInfo",t.MUJIAN_AI_CHAT_V2_COMPLETE="mujian:ai:chat_v2:complete",t.MUJIAN_AI_CHAT_V2_RECOVER="mujian:ai:chat_v2:recover",t.MUJIAN_AI_CHAT_V2_STOP="mujian:ai:chat_v2:stop",t.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE="mujian:ai:chat_v2:message:getPage",t.MUJIAN_AI_CHAT_V2_RENDER_MESSAGE="mujian:ai:chat_v2:renderMessage",t.MUJIAN_AI_SETTINGS_PERSONA_GET_ACTIVE="mujian:ai:settings:persona:getActive",t.MUJIAN_AI_SETTINGS_PERSONA_SET_ACTIVE="mujian:ai:settings:persona:setActive",t.MUJIAN_AI_SETTINGS_MODEL_GET_ALL="mujian:ai:settings:model:getAll",t.MUJIAN_AI_SETTINGS_MODEL_SET_ACTIVE="mujian:ai:settings:model:setActive",t.MUJIAN_AI_SETTINGS_MODEL_GET_ACTIVE="mujian:ai:settings:model:getActive",t.MUJIAN_AI_CHAT_MESSAGE_DELETE_ONE="mujian:ai:chat:message:deleteOne",t.MUJIAN_AI_CHAT_MESSAGE_EDIT_ONE="mujian:ai:chat:message:editOne",t.MUJIAN_AI_CHAT_MESSAGE_SWIPE="mujian:ai:chat:message:swipe",t.MUJIAN_AI_OPENAI_IMAGES_GENERATE="mujian:ai:openai:images:generate",t.MUJIAN_UTILS_CLIPBOARD_WRITE_TEXT="mujian:utils:clipboard:writeText",t.MUJIAN_GET_CONFIG="mujian:getConfig",t);let _=async function(t,e,i){await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{content:t,conversationVersion:e},{onData:i})},m=async function(t){return await this.call(u.MUJIAN_AI_CHAT_V2_RENDER_MESSAGE,t)},p=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{isContinue:!0,conversationVersion:t},{onData:e})},A=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{isRegenerate:!0,conversationVersion:t},{onData:e})},E=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_STOP,{conversationVersion:t,assisMsgId:e})},I=async function(t,e,i){return await this.call(u.MUJIAN_AI_CHAT_V2_RECOVER,{conversationVersion:t,assisMsgId:e},{onData:i})},g=async function(t){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_DELETE_ONE,{messageId:t})},f=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_EDIT_ONE,{messageId:t,content:e})},T=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_SWIPE,{messageId:t,swipeId:e})};async function M(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE,{fromCursor:t,pageSize:e})}let y=async function(){return await this.call(u.MUJIAN_AI_CHAT_PROJECT_GET_INFO)},N=async function(){return await this.call(u.MUJIAN_AI_SETTINGS_PERSONA_GET_ACTIVE)};async function C(){return await this.call(u.MUJIAN_GET_CONFIG)}let w=async function(){},v=async function(){};async function S(t){return await this.call(u.MUJIAN_UTILS_CLIPBOARD_WRITE_TEXT,t)}let b={i(...t){console.log("[MujianSDK] ",...t)},e(...t){console.error("[MujianSDK] ",...t)}};class O{constructor(){}static EVENT=u;static getInstance(){return window.$mujian||(window.$mujian=new O),window.$mujian}parent=null;ready=!1;get isReady(){return this.ready}pendingRequests=new Map;_config;get openapi(){return this._config?.openapi}initPromise=null;async init(){return this.initPromise||(this.initPromise=(async()=>{let t=new h.Model({reply:({id:t,complete:e,data:i,error:n})=>{let a=this.pendingRequests.get(t);if(a){if(n){a.reject(n),this.pendingRequests.delete(t);return}a.onData?.(i),e&&(a.onComplete?.(),a.resolve(i),this.pendingRequests.delete(t))}}});try{let e=await t;this.ready=!0,this.parent=e,b.i("mujian sdk client init"),await this.call(u.MUJIAN_INIT);let i=await this.ai.chat.project.getInfo();if(i.config?.customCss){let t=document.createElement("style");t.setAttribute("type","text/css"),t.setAttribute("id","mujian-custom-css"),t.textContent=i.config.customCss,document.head.appendChild(t)}if(i.config?.customJs){let t=document.createElement("script");t.setAttribute("type","text/javascript"),t.setAttribute("id","mujian-custom-js"),t.textContent=i.config.customJs,document.head.appendChild(t)}let n=await C.call(this);n&&(this._config=n)}catch(t){b.e("init error",t)}})()),this.initPromise}emit(t,e){if(!this.ready)throw Error("Mujian is not initialized");this.parent?.emit(t,e)}nextCallId=0;getCallId(){let t=this.nextCallId;return this.nextCallId+=1,t}async call(t,e,i){if(!this.ready)throw Error("Mujian is not initialized");let n=this.getCallId();return new Promise((a,s)=>{this.pendingRequests.set(n,{resolve:a,reject:s,...i}),this.emit(t,{id:n,data:e}),i?.signal?.addEventListener("abort",()=>{this.emit(u.MUJIAN_AI_CHAT_STOP,{id:n})})})}ai={chat:{project:{getInfo:y.bind(this)},settings:{persona:{getActive:N.bind(this)}},complete:_.bind(this),renderMessage:m.bind(this),continue:p.bind(this),regenerate:A.bind(this),stop:E.bind(this),recover:I.bind(this),message:{deleteOne:g.bind(this),editOne:f.bind(this),swipe:T.bind(this),getPage:M.bind(this)}},text:{complete:j.bind(this)},openai:{completions:{create:J.create.bind(this)},chat:{completions:{create:P.completions.create.bind(this)}},responses:{create:U.create.bind(this)},images:{generate:R.generate.bind(this)}}};ui={};utils={clipboard:{writeText:S.bind(this)}};hybrid={};player={};game={assets:()=>{console.log("assets")},saves:{saveGame:w.bind(this),loadGame:v.bind(this)},ranking:()=>{console.log("ranking")}}}let j=async function(t){return await this.call(O.EVENT.MUJIAN_AI_TEXT_GENERATE,{content:t})},P={completions:{create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_CHAT_COMPLETIONS_CREATE,{params:t,options:e},{onData:i,signal:n})}}},J={create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_COMPLETIONS_CREATE,{params:t,options:e},{onData:i,signal:n})}},U={create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_RESPONSES_CREATE,{params:t,options:e},{onData:i,signal:n})}},R={generate:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_IMAGES_GENERATE,{params:t,options:e},{onData:i,signal:n})}};class G{constructor(){}static EVENT=u;static getInstance(){return window.$mujian||(window.$mujian=new G),window.$mujian}parent=null;ready=!1;get isReady(){return this.ready}pendingRequests=new Map;_config;get openapi(){return this._config?.openapi}initPromise=null;async init(){return this.initPromise||(this.initPromise=(async()=>{let t=new h.Model({reply:({id:t,complete:e,data:i,error:n})=>{let a=this.pendingRequests.get(t);if(a){if(n){a.reject(n),this.pendingRequests.delete(t);return}a.onData?.(i),e&&(a.onComplete?.(),a.resolve(i),this.pendingRequests.delete(t))}}});try{let e=await t;this.ready=!0,this.parent=e,b.i("mujian sdk client init"),await this.call(u.MUJIAN_INIT);let i=await this.ai.chat.project.getInfo();if(i.config?.customCss){let t=document.createElement("style");t.setAttribute("type","text/css"),t.setAttribute("id","mujian-custom-css"),t.textContent=i.config.customCss,document.head.appendChild(t)}if(i.config?.customJs){let t=document.createElement("script");t.setAttribute("type","text/javascript"),t.setAttribute("id","mujian-custom-js"),t.textContent=i.config.customJs,document.head.appendChild(t)}let n=await C.call(this);n&&(this._config=n)}catch(t){b.e("init error",t)}})()),this.initPromise}emit(t,e){if(!this.ready)throw Error("Mujian is not initialized");this.parent?.emit(t,e)}nextCallId=0;getCallId(){let t=this.nextCallId;return this.nextCallId+=1,t}async call(t,e,i){if(!this.ready)throw Error("Mujian is not initialized");let n=this.getCallId();return new Promise((a,s)=>{this.pendingRequests.set(n,{resolve:a,reject:s,...i}),this.emit(t,{id:n,data:e}),i?.signal?.addEventListener("abort",()=>{this.emit(u.MUJIAN_AI_CHAT_STOP,{id:n})})})}ai={chat:{project:{getInfo:y.bind(this)},settings:{persona:{getActive:N.bind(this)}},complete:_.bind(this),renderMessage:m.bind(this),continue:p.bind(this),regenerate:A.bind(this),stop:E.bind(this),recover:I.bind(this),message:{deleteOne:g.bind(this),editOne:f.bind(this),swipe:T.bind(this),getPage:M.bind(this)}},text:{complete:j.bind(this)},openai:{completions:{create:J.create.bind(this)},chat:{completions:{create:P.completions.create.bind(this)}},responses:{create:U.create.bind(this)},images:{generate:R.generate.bind(this)}}};ui={};utils={clipboard:{writeText:S.bind(this)}};hybrid={};player={};game={assets:()=>{console.log("assets")},saves:{saveGame:w.bind(this),loadGame:v.bind(this)},ranking:()=>{console.log("ranking")}}}return i})());
2
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.MujianUMD=e():t.MujianUMD=e()}(globalThis,()=>(()=>{"use strict";var t,e={};e.d=(t,i)=>{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},e.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),e.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var i={};e.r(i),e.d(i,{MujianSdk:()=>G,EVENT:()=>u});var n="application/x-postmate-v1+json",a=0,s=function(t){var e=document.createElement("a");e.href=t;var i=e.protocol.length>4?e.protocol:window.location.protocol,n=e.host.length?"80"===e.port||"443"===e.port?e.hostname:e.host:window.location.host;return e.origin||i+"//"+n},r={handshake:1,"handshake-reply":1,call:1,emit:1,reply:1,request:1},o=function(t,e){return("string"!=typeof e||t.origin===e)&&!!t.data&&("object"!=typeof t.data||"postmate"in t.data)&&t.data.type===n&&!!r[t.data.postmate]},c=function(t,e){var i="function"==typeof t[e]?t[e]():t[e];return h.Promise.resolve(i)},l=function(){function t(t){var e=this;this.parent=t.parent,this.frame=t.frame,this.child=t.child,this.childOrigin=t.childOrigin,this.events={},this.listener=function(t){if(!o(t,e.childOrigin))return!1;var i=((t||{}).data||{}).value||{},n=i.data,a=i.name;"emit"===t.data.postmate&&a in e.events&&e.events[a].call(e,n)},this.parent.addEventListener("message",this.listener,!1)}var e=t.prototype;return e.get=function(t){var e=this;return new h.Promise(function(i){var s=++a;e.parent.addEventListener("message",function t(n){n.data.uid===s&&"reply"===n.data.postmate&&(e.parent.removeEventListener("message",t,!1),i(n.data.value))},!1),e.child.postMessage({postmate:"request",type:n,property:t,uid:s},e.childOrigin)})},e.call=function(t,e){this.child.postMessage({postmate:"call",type:n,property:t,data:e},this.childOrigin)},e.on=function(t,e){this.events[t]=e},e.destroy=function(){window.removeEventListener("message",this.listener,!1),this.frame.parentNode.removeChild(this.frame)},t}(),d=function(){function t(t){var e=this;this.model=t.model,this.parent=t.parent,this.parentOrigin=t.parentOrigin,this.child=t.child,this.child.addEventListener("message",function(t){if(o(t,e.parentOrigin)){var i=t.data,a=i.property,s=i.uid,r=i.data;if("call"===t.data.postmate){a in e.model&&"function"==typeof e.model[a]&&e.model[a](r);return}c(e.model,a).then(function(e){return t.source.postMessage({property:a,postmate:"reply",type:n,uid:s,value:e},t.origin)})}})}return t.prototype.emit=function(t,e){this.parent.postMessage({postmate:"emit",type:n,value:{name:t,data:e}},this.parentOrigin)},t}(),h=function(){function t(t){var e=t.container,i=void 0===e?void 0!==i?i:document.body:e,n=t.model,a=t.url,s=t.name,r=t.classListArray;return this.parent=window,this.frame=document.createElement("iframe"),this.frame.name=s||"",this.frame.classList.add.apply(this.frame.classList,void 0===r?[]:r),i.appendChild(this.frame),this.child=this.frame.contentWindow||this.frame.contentDocument.parentWindow,this.model=n||{},this.sendHandshake(a)}return t.prototype.sendHandshake=function(e){var i,a=this,r=s(e),c=0;return new t.Promise(function(t,s){a.parent.addEventListener("message",function e(n){return!!o(n,r)&&("handshake-reply"===n.data.postmate?(clearInterval(i),a.parent.removeEventListener("message",e,!1),a.childOrigin=n.origin,t(new l(a))):s("Failed handshake"))},!1);var d=function(){c++,a.child.postMessage({postmate:"handshake",type:n,model:a.model},r),5===c&&clearInterval(i)},h=function(){d(),i=setInterval(d,500)};a.frame.attachEvent?a.frame.attachEvent("onload",h):a.frame.onload=h,a.frame.src=e})},t}();h.debug=!1,h.Promise=function(){try{return window?window.Promise:Promise}catch(t){return null}}(),h.Model=function(){function t(t){return this.child=window,this.model=t,this.parent=this.child.parent,this.sendHandshakeReply()}return t.prototype.sendHandshakeReply=function(){var t=this;return new h.Promise(function(e,i){t.child.addEventListener("message",function a(s){if(s.data.postmate){if("handshake"===s.data.postmate){t.child.removeEventListener("message",a,!1),s.source.postMessage({postmate:"handshake-reply",type:n},s.origin),t.parentOrigin=s.origin;var r=s.data.model;return r&&Object.keys(r).forEach(function(e){t.model[e]=r[e]}),e(new d(t))}return i("Handshake Reply Failed")}},!1)})},t}();var u=((t={}).MUJIAN_INIT="mujian:init",t.MUJIAN_AI_CHAT_STOP="mujian:ai:chat:stop",t.MUJIAN_AI_CHAT_COMPLETE="mujian:ai:chat:complete",t.MUJIAN_AI_CHAT_APPLY_REGEX="mujian:ai:chat:applyRegex",t.MUJIAN_AI_CHAT_RENDER_MESSAGE="mujian:ai:chat:renderMessage",t.MUJIAN_AI_TEXT_GENERATE="mujian:ai:text:generate",t.MUJIAN_AI_OPENAI_COMPLETIONS_CREATE="mujian:ai:openai:completions:create",t.MUJIAN_AI_OPENAI_CHAT_COMPLETIONS_CREATE="mujian:ai:openai:chat:completions:create",t.MUJIAN_AI_OPENAI_RESPONSES_CREATE="mujian:ai:openai:responses:create",t.MUJIAN_AI_CHAT_MESSAGE_GET_ALL="mujian:ai:chat:message:getAll",t.MUJIAN_AI_CHAT_MESSAGE_GET_PAGE="mujian:ai:chat:message:getPage",t.MUJIAN_AI_CHAT_PROJECT_GET_INFO="mujian:ai:chat:project:getInfo",t.MUJIAN_AI_CHAT_V2_COMPLETE="mujian:ai:chat_v2:complete",t.MUJIAN_AI_CHAT_V2_RECOVER="mujian:ai:chat_v2:recover",t.MUJIAN_AI_CHAT_V2_STOP="mujian:ai:chat_v2:stop",t.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE="mujian:ai:chat_v2:message:getPage",t.MUJIAN_AI_CHAT_V2_RENDER_MESSAGE="mujian:ai:chat_v2:renderMessage",t.MUJIAN_AI_SETTINGS_PERSONA_GET_ACTIVE="mujian:ai:settings:persona:getActive",t.MUJIAN_AI_SETTINGS_PERSONA_SET_ACTIVE="mujian:ai:settings:persona:setActive",t.MUJIAN_AI_SETTINGS_MODEL_GET_ALL="mujian:ai:settings:model:getAll",t.MUJIAN_AI_SETTINGS_MODEL_SET_ACTIVE="mujian:ai:settings:model:setActive",t.MUJIAN_AI_SETTINGS_MODEL_GET_ACTIVE="mujian:ai:settings:model:getActive",t.MUJIAN_AI_CHAT_MESSAGE_DELETE_ONE="mujian:ai:chat:message:deleteOne",t.MUJIAN_AI_CHAT_MESSAGE_EDIT_ONE="mujian:ai:chat:message:editOne",t.MUJIAN_AI_CHAT_MESSAGE_SWIPE="mujian:ai:chat:message:swipe",t.MUJIAN_AI_OPENAI_IMAGES_GENERATE="mujian:ai:openai:images:generate",t.MUJIAN_UTILS_CLIPBOARD_WRITE_TEXT="mujian:utils:clipboard:writeText",t.MUJIAN_GET_CONFIG="mujian:getConfig",t);let _=async function(t,e,i){await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{content:t,conversationVersion:e},{onData:i})},m=async function(t){return await this.call(u.MUJIAN_AI_CHAT_V2_RENDER_MESSAGE,t)},p=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{isContinue:!0,conversationVersion:t},{onData:e})},A=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_COMPLETE,{isRegenerate:!0,conversationVersion:t},{onData:e})},E=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_V2_STOP,{conversationVersion:t,assisMsgId:e})},I=async function(t,e,i){return await this.call(u.MUJIAN_AI_CHAT_V2_RECOVER,{conversationVersion:t,assisMsgId:e},{onData:i})},g=async function(t){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_DELETE_ONE,{messageId:t})},f=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_EDIT_ONE,{messageId:t,content:e})},T=async function(t,e){return await this.call(u.MUJIAN_AI_CHAT_MESSAGE_SWIPE,{messageId:t,swipeId:e})};async function M(t,e){let i=await this.call(u.MUJIAN_AI_CHAT_V2_MESSAGE_GET_PAGE,{fromCursor:t,pageSize:e});return{...i,messages:i.messages.map(t=>({...t,swipes:t.swipes.map(t=>Object.assign(t.content,t)),content:t.swipes[t.activeSwipeId].content,role:t.isUser?"user":"assistant"}))}}let y=async function(){return await this.call(u.MUJIAN_AI_CHAT_PROJECT_GET_INFO)},N=async function(){return await this.call(u.MUJIAN_AI_SETTINGS_PERSONA_GET_ACTIVE)};async function C(){return await this.call(u.MUJIAN_GET_CONFIG)}let w=async function(){},v=async function(){};async function S(t){return await this.call(u.MUJIAN_UTILS_CLIPBOARD_WRITE_TEXT,t)}let b={i(...t){console.log("[MujianSDK] ",...t)},e(...t){console.error("[MujianSDK] ",...t)}};class O{constructor(){}static EVENT=u;static getInstance(){return window.$mujian||(window.$mujian=new O),window.$mujian}parent=null;ready=!1;get isReady(){return this.ready}pendingRequests=new Map;_config;get openapi(){return this._config?.openapi}initPromise=null;async init(){return this.initPromise||(this.initPromise=(async()=>{let t=new h.Model({reply:({id:t,complete:e,data:i,error:n})=>{let a=this.pendingRequests.get(t);if(a){if(n){a.reject(n),this.pendingRequests.delete(t);return}a.onData?.(i),e&&(a.onComplete?.(),a.resolve(i),this.pendingRequests.delete(t))}}});try{let e=await t;this.ready=!0,this.parent=e,b.i("mujian sdk client init"),await this.call(u.MUJIAN_INIT);let i=await this.ai.chat.project.getInfo();if(i.config?.customCss){let t=document.createElement("style");t.setAttribute("type","text/css"),t.setAttribute("id","mujian-custom-css"),t.textContent=i.config.customCss,document.head.appendChild(t)}if(i.config?.customJs){let t=document.createElement("script");t.setAttribute("type","text/javascript"),t.setAttribute("id","mujian-custom-js"),t.textContent=i.config.customJs,document.head.appendChild(t)}let n=await C.call(this);n&&(this._config=n)}catch(t){b.e("init error",t)}})()),this.initPromise}emit(t,e){if(!this.ready)throw Error("Mujian is not initialized");this.parent?.emit(t,e)}nextCallId=0;getCallId(){let t=this.nextCallId;return this.nextCallId+=1,t}async call(t,e,i){if(!this.ready)throw Error("Mujian is not initialized");let n=this.getCallId();return new Promise((a,s)=>{this.pendingRequests.set(n,{resolve:a,reject:s,...i}),this.emit(t,{id:n,data:e}),i?.signal?.addEventListener("abort",()=>{this.emit(u.MUJIAN_AI_CHAT_STOP,{id:n})})})}ai={chat:{project:{getInfo:y.bind(this)},settings:{persona:{getActive:N.bind(this)}},complete:_.bind(this),renderMessage:m.bind(this),continue:p.bind(this),regenerate:A.bind(this),stop:E.bind(this),recover:I.bind(this),message:{deleteOne:g.bind(this),editOne:f.bind(this),swipe:T.bind(this),getPage:M.bind(this)}},text:{complete:j.bind(this)},openai:{completions:{create:J.create.bind(this)},chat:{completions:{create:P.completions.create.bind(this)}},responses:{create:U.create.bind(this)},images:{generate:R.generate.bind(this)}}};ui={};utils={clipboard:{writeText:S.bind(this)}};hybrid={};player={};game={assets:()=>{console.log("assets")},saves:{saveGame:w.bind(this),loadGame:v.bind(this)},ranking:()=>{console.log("ranking")}}}let j=async function(t){return await this.call(O.EVENT.MUJIAN_AI_TEXT_GENERATE,{content:t})},P={completions:{create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_CHAT_COMPLETIONS_CREATE,{params:t,options:e},{onData:i,signal:n})}}},J={create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_COMPLETIONS_CREATE,{params:t,options:e},{onData:i,signal:n})}},U={create:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_RESPONSES_CREATE,{params:t,options:e},{onData:i,signal:n})}},R={generate:async function(t,e,i,n){return await this.call(O.EVENT.MUJIAN_AI_OPENAI_IMAGES_GENERATE,{params:t,options:e},{onData:i,signal:n})}};class G{constructor(){}static EVENT=u;static getInstance(){return window.$mujian||(window.$mujian=new G),window.$mujian}parent=null;ready=!1;get isReady(){return this.ready}pendingRequests=new Map;_config;get openapi(){return this._config?.openapi}initPromise=null;async init(){return this.initPromise||(this.initPromise=(async()=>{let t=new h.Model({reply:({id:t,complete:e,data:i,error:n})=>{let a=this.pendingRequests.get(t);if(a){if(n){a.reject(n),this.pendingRequests.delete(t);return}a.onData?.(i),e&&(a.onComplete?.(),a.resolve(i),this.pendingRequests.delete(t))}}});try{let e=await t;this.ready=!0,this.parent=e,b.i("mujian sdk client init"),await this.call(u.MUJIAN_INIT);let i=await this.ai.chat.project.getInfo();if(i.config?.customCss){let t=document.createElement("style");t.setAttribute("type","text/css"),t.setAttribute("id","mujian-custom-css"),t.textContent=i.config.customCss,document.head.appendChild(t)}if(i.config?.customJs){let t=document.createElement("script");t.setAttribute("type","text/javascript"),t.setAttribute("id","mujian-custom-js"),t.textContent=i.config.customJs,document.head.appendChild(t)}let n=await C.call(this);n&&(this._config=n)}catch(t){b.e("init error",t)}})()),this.initPromise}emit(t,e){if(!this.ready)throw Error("Mujian is not initialized");this.parent?.emit(t,e)}nextCallId=0;getCallId(){let t=this.nextCallId;return this.nextCallId+=1,t}async call(t,e,i){if(!this.ready)throw Error("Mujian is not initialized");let n=this.getCallId();return new Promise((a,s)=>{this.pendingRequests.set(n,{resolve:a,reject:s,...i}),this.emit(t,{id:n,data:e}),i?.signal?.addEventListener("abort",()=>{this.emit(u.MUJIAN_AI_CHAT_STOP,{id:n})})})}ai={chat:{project:{getInfo:y.bind(this)},settings:{persona:{getActive:N.bind(this)}},complete:_.bind(this),renderMessage:m.bind(this),continue:p.bind(this),regenerate:A.bind(this),stop:E.bind(this),recover:I.bind(this),message:{deleteOne:g.bind(this),editOne:f.bind(this),swipe:T.bind(this),getPage:M.bind(this)}},text:{complete:j.bind(this)},openai:{completions:{create:J.create.bind(this)},chat:{completions:{create:P.completions.create.bind(this)}},responses:{create:U.create.bind(this)},images:{generate:R.generate.bind(this)}}};ui={};utils={clipboard:{writeText:S.bind(this)}};hybrid={};player={};game={assets:()=>{console.log("assets")},saves:{saveGame:w.bind(this),loadGame:v.bind(this)},ranking:()=>{console.log("ranking")}}}return i})());