@copilotkit/react-core 1.4.1-pre.6 → 1.4.2-tyler-reset-chat.0
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/CHANGELOG.md +57 -0
- package/dist/{chunk-LODRWFMB.mjs → chunk-2JP64U3A.mjs} +10 -2
- package/dist/{chunk-LODRWFMB.mjs.map → chunk-2JP64U3A.mjs.map} +1 -1
- package/dist/{chunk-XINZBP3J.mjs → chunk-3AYELZJS.mjs} +2 -2
- package/dist/{chunk-MWZO6TUR.mjs → chunk-3R4J2TPH.mjs} +2 -2
- package/dist/{chunk-JDQCJCAQ.mjs → chunk-6EN7J4V2.mjs} +37 -15
- package/dist/chunk-6EN7J4V2.mjs.map +1 -0
- package/dist/{chunk-P6VS7ST4.mjs → chunk-6QKA3SNN.mjs} +12 -3
- package/dist/{chunk-P6VS7ST4.mjs.map → chunk-6QKA3SNN.mjs.map} +1 -1
- package/dist/{chunk-DT52QX4H.mjs → chunk-CZMEZR6F.mjs} +36 -6
- package/dist/chunk-CZMEZR6F.mjs.map +1 -0
- package/dist/{chunk-LMFSB5D5.mjs → chunk-JR55I3FL.mjs} +2 -2
- package/dist/{chunk-V22C3DOQ.mjs → chunk-SEPYQHH7.mjs} +23 -5
- package/dist/{chunk-V22C3DOQ.mjs.map → chunk-SEPYQHH7.mjs.map} +1 -1
- package/dist/{chunk-QDGDXRRJ.mjs → chunk-USL3EHJB.mjs} +2 -2
- package/dist/{chunk-H4VZMKR6.mjs → chunk-XUPO37VH.mjs} +2 -2
- package/dist/components/copilot-provider/copilotkit.js +19 -2
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +2 -2
- package/dist/components/copilot-provider/index.js +19 -2
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +2 -2
- package/dist/components/index.js +19 -2
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +2 -2
- package/dist/context/copilot-context.d.ts +6 -0
- package/dist/context/copilot-context.js +9 -1
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.js +9 -1
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/hooks/index.d.ts +2 -1
- package/dist/hooks/index.js +99 -18
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +15 -9
- package/dist/hooks/use-chat.d.ts +20 -0
- package/dist/hooks/use-chat.js +36 -14
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +1 -1
- package/dist/hooks/use-coagent-state-render.js +9 -1
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-coagent.d.ts +14 -1
- package/dist/hooks/use-coagent.js +99 -18
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +11 -5
- package/dist/hooks/use-copilot-action.js +9 -1
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-chat.d.ts +1 -0
- package/dist/hooks/use-copilot-chat.js +77 -17
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +4 -4
- package/dist/hooks/use-copilot-readable.js +9 -1
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-make-copilot-document-readable.js +9 -1
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +109 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +16 -10
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +3 -3
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +3 -3
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +2 -2
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +2 -2
- package/package.json +5 -5
- package/src/components/copilot-provider/copilotkit.tsx +10 -0
- package/src/context/copilot-context.tsx +22 -0
- package/src/hooks/index.ts +1 -1
- package/src/hooks/use-chat.ts +56 -13
- package/src/hooks/use-coagent.ts +21 -4
- package/src/hooks/use-copilot-chat.ts +36 -3
- package/dist/chunk-DT52QX4H.mjs.map +0 -1
- package/dist/chunk-JDQCJCAQ.mjs.map +0 -1
- /package/dist/{chunk-XINZBP3J.mjs.map → chunk-3AYELZJS.mjs.map} +0 -0
- /package/dist/{chunk-MWZO6TUR.mjs.map → chunk-3R4J2TPH.mjs.map} +0 -0
- /package/dist/{chunk-LMFSB5D5.mjs.map → chunk-JR55I3FL.mjs.map} +0 -0
- /package/dist/{chunk-QDGDXRRJ.mjs.map → chunk-USL3EHJB.mjs.map} +0 -0
- /package/dist/{chunk-H4VZMKR6.mjs.map → chunk-XUPO37VH.mjs.map} +0 -0
|
@@ -135,6 +135,18 @@ export interface CopilotContextParams {
|
|
|
135
135
|
agentSession: AgentSession | null;
|
|
136
136
|
setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
|
|
137
137
|
|
|
138
|
+
agentLock: string | null;
|
|
139
|
+
|
|
140
|
+
threadId: string | null;
|
|
141
|
+
setThreadId: React.Dispatch<React.SetStateAction<string | null>>;
|
|
142
|
+
|
|
143
|
+
runId: string | null;
|
|
144
|
+
setRunId: React.Dispatch<React.SetStateAction<string | null>>;
|
|
145
|
+
|
|
146
|
+
// The chat abort controller can be used to stop generation globally,
|
|
147
|
+
// i.e. when using `stop()` from `useChat`
|
|
148
|
+
chatAbortControllerRef: React.MutableRefObject<AbortController | null>;
|
|
149
|
+
|
|
138
150
|
// runtime
|
|
139
151
|
runtimeClient: CopilotRuntimeClient;
|
|
140
152
|
}
|
|
@@ -189,6 +201,16 @@ const emptyCopilotContext: CopilotContextParams = {
|
|
|
189
201
|
|
|
190
202
|
agentSession: null,
|
|
191
203
|
setAgentSession: () => {},
|
|
204
|
+
|
|
205
|
+
agentLock: null,
|
|
206
|
+
|
|
207
|
+
threadId: null,
|
|
208
|
+
setThreadId: () => {},
|
|
209
|
+
|
|
210
|
+
runId: null,
|
|
211
|
+
setRunId: () => {},
|
|
212
|
+
|
|
213
|
+
chatAbortControllerRef: { current: null },
|
|
192
214
|
};
|
|
193
215
|
|
|
194
216
|
export const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);
|
package/src/hooks/index.ts
CHANGED
|
@@ -7,5 +7,5 @@ export { useCoAgentStateRender } from "./use-coagent-state-render";
|
|
|
7
7
|
export { useMakeCopilotDocumentReadable } from "./use-make-copilot-document-readable";
|
|
8
8
|
export { type UseChatHelpers } from "./use-chat";
|
|
9
9
|
export { useCopilotReadable } from "./use-copilot-readable";
|
|
10
|
-
export { useCoAgent } from "./use-coagent";
|
|
10
|
+
export { useCoAgent, type HintFunction, runAgent, startAgent, stopAgent } from "./use-coagent";
|
|
11
11
|
export { useCopilotRuntimeClient } from "./use-copilot-runtime-client";
|
package/src/hooks/use-chat.ts
CHANGED
|
@@ -97,6 +97,27 @@ export type UseChatOptions = {
|
|
|
97
97
|
* setState-powered method to update the agent session
|
|
98
98
|
*/
|
|
99
99
|
setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The current thread ID.
|
|
103
|
+
*/
|
|
104
|
+
threadId: string | null;
|
|
105
|
+
/**
|
|
106
|
+
* set the current thread ID
|
|
107
|
+
*/
|
|
108
|
+
setThreadId: (threadId: string | null) => void;
|
|
109
|
+
/**
|
|
110
|
+
* The current run ID.
|
|
111
|
+
*/
|
|
112
|
+
runId: string | null;
|
|
113
|
+
/**
|
|
114
|
+
* set the current run ID
|
|
115
|
+
*/
|
|
116
|
+
setRunId: (runId: string | null) => void;
|
|
117
|
+
/**
|
|
118
|
+
* The global chat abort controller.
|
|
119
|
+
*/
|
|
120
|
+
chatAbortControllerRef: React.MutableRefObject<AbortController | null>;
|
|
100
121
|
};
|
|
101
122
|
|
|
102
123
|
export type UseChatHelpers = {
|
|
@@ -134,11 +155,16 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
134
155
|
coagentStates,
|
|
135
156
|
agentSession,
|
|
136
157
|
setAgentSession,
|
|
158
|
+
threadId,
|
|
159
|
+
setThreadId,
|
|
160
|
+
runId,
|
|
161
|
+
setRunId,
|
|
162
|
+
chatAbortControllerRef,
|
|
137
163
|
} = options;
|
|
138
164
|
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
165
|
+
const abortController = new AbortController();
|
|
166
|
+
chatAbortControllerRef.current = abortController;
|
|
167
|
+
|
|
142
168
|
const { addGraphQLErrorsToast } = useToast();
|
|
143
169
|
|
|
144
170
|
const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();
|
|
@@ -149,6 +175,10 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
149
175
|
coagentStatesRef.current = coagentStates;
|
|
150
176
|
const agentSessionRef = useRef<AgentSession | null>(agentSession);
|
|
151
177
|
agentSessionRef.current = agentSession;
|
|
178
|
+
const threadIdRef = useRef<string | null>(threadId);
|
|
179
|
+
threadIdRef.current = threadId;
|
|
180
|
+
const runIdRef = useRef<string | null>(runId);
|
|
181
|
+
runIdRef.current = runId;
|
|
152
182
|
|
|
153
183
|
const publicApiKey = copilotConfig.publicApiKey;
|
|
154
184
|
|
|
@@ -175,8 +205,8 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
175
205
|
role: Role.Assistant,
|
|
176
206
|
}),
|
|
177
207
|
];
|
|
178
|
-
|
|
179
|
-
|
|
208
|
+
|
|
209
|
+
chatAbortControllerRef.current = new AbortController();
|
|
180
210
|
|
|
181
211
|
setMessages([...previousMessages, ...newMessages]);
|
|
182
212
|
|
|
@@ -247,7 +277,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
247
277
|
})),
|
|
248
278
|
},
|
|
249
279
|
properties: copilotConfig.properties,
|
|
250
|
-
signal:
|
|
280
|
+
signal: chatAbortControllerRef.current?.signal,
|
|
251
281
|
}),
|
|
252
282
|
);
|
|
253
283
|
|
|
@@ -273,6 +303,9 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
273
303
|
}
|
|
274
304
|
|
|
275
305
|
if (done) {
|
|
306
|
+
if (chatAbortControllerRef.current.signal.aborted) {
|
|
307
|
+
return newMessages.slice();
|
|
308
|
+
}
|
|
276
309
|
break;
|
|
277
310
|
}
|
|
278
311
|
|
|
@@ -283,6 +316,9 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
283
316
|
threadIdRef.current = value.generateCopilotResponse.threadId || null;
|
|
284
317
|
runIdRef.current = value.generateCopilotResponse.runId || null;
|
|
285
318
|
|
|
319
|
+
setThreadId(threadIdRef.current);
|
|
320
|
+
setRunId(runIdRef.current);
|
|
321
|
+
|
|
286
322
|
const messages = convertGqlOutputToMessages(
|
|
287
323
|
filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),
|
|
288
324
|
);
|
|
@@ -334,12 +370,19 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
334
370
|
followUp = action.followUp;
|
|
335
371
|
}
|
|
336
372
|
|
|
337
|
-
const result = await
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
373
|
+
const result = await Promise.race([
|
|
374
|
+
onFunctionCall({
|
|
375
|
+
messages: previousMessages,
|
|
376
|
+
name: message.name,
|
|
377
|
+
args: message.arguments,
|
|
378
|
+
}),
|
|
379
|
+
new Promise((_, reject) => chatAbortControllerRef.current?.signal.addEventListener('abort', () => reject(new Error('Operation was aborted'))))
|
|
380
|
+
])
|
|
381
|
+
if (chatAbortControllerRef.current.signal.aborted){
|
|
382
|
+
actionResults[message.id] = "";
|
|
383
|
+
} else {
|
|
384
|
+
actionResults[message.id] = result;
|
|
385
|
+
}
|
|
343
386
|
} catch (e) {
|
|
344
387
|
actionResults[message.id] = `Failed to execute action ${message.name}`;
|
|
345
388
|
console.error(`Failed to execute action ${message.name}: ${e}`);
|
|
@@ -466,7 +509,7 @@ export function useChat(options: UseChatOptions): UseChatHelpers {
|
|
|
466
509
|
};
|
|
467
510
|
|
|
468
511
|
const stop = (): void => {
|
|
469
|
-
|
|
512
|
+
chatAbortControllerRef.current?.abort("Stop was called");
|
|
470
513
|
};
|
|
471
514
|
|
|
472
515
|
return {
|
package/src/hooks/use-coagent.ts
CHANGED
|
@@ -266,7 +266,11 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
|
|
|
266
266
|
} else if (coagentStates[name] === undefined) {
|
|
267
267
|
setState(options.initialState === undefined ? {} : options.initialState);
|
|
268
268
|
}
|
|
269
|
-
}, [
|
|
269
|
+
}, [
|
|
270
|
+
isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined,
|
|
271
|
+
// reset initialstate on reset
|
|
272
|
+
coagentStates === undefined,
|
|
273
|
+
]);
|
|
270
274
|
|
|
271
275
|
// Return the state and setState function
|
|
272
276
|
return {
|
|
@@ -287,23 +291,36 @@ export function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentRe
|
|
|
287
291
|
};
|
|
288
292
|
}
|
|
289
293
|
|
|
290
|
-
function startAgent(name: string, context: CopilotContextParams) {
|
|
294
|
+
export function startAgent(name: string, context: CopilotContextParams) {
|
|
291
295
|
const { setAgentSession } = context;
|
|
292
296
|
setAgentSession({
|
|
293
297
|
agentName: name,
|
|
294
298
|
});
|
|
295
299
|
}
|
|
296
300
|
|
|
297
|
-
function stopAgent(name: string, context: CopilotContextParams) {
|
|
301
|
+
export function stopAgent(name: string, context: CopilotContextParams) {
|
|
298
302
|
const { agentSession, setAgentSession } = context;
|
|
299
303
|
if (agentSession && agentSession.agentName === name) {
|
|
300
304
|
setAgentSession(null);
|
|
305
|
+
context.setCoagentStates((prevAgentStates) => {
|
|
306
|
+
return {
|
|
307
|
+
...prevAgentStates,
|
|
308
|
+
[name]: {
|
|
309
|
+
...prevAgentStates[name],
|
|
310
|
+
running: false,
|
|
311
|
+
active: false,
|
|
312
|
+
threadId: undefined,
|
|
313
|
+
nodeName: undefined,
|
|
314
|
+
runId: undefined,
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
});
|
|
301
318
|
} else {
|
|
302
319
|
console.warn(`No agent session found for ${name}`);
|
|
303
320
|
}
|
|
304
321
|
}
|
|
305
322
|
|
|
306
|
-
async function runAgent(
|
|
323
|
+
export async function runAgent(
|
|
307
324
|
name: string,
|
|
308
325
|
context: CopilotContextParams & CopilotMessagesContextParams,
|
|
309
326
|
appendMessage: (message: Message) => Promise<void>,
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
* ```
|
|
40
40
|
*/
|
|
41
41
|
import { useRef, useEffect, useCallback } from "react";
|
|
42
|
-
import { useCopilotContext } from "../context/copilot-context";
|
|
42
|
+
import { AgentSession, useCopilotContext } from "../context/copilot-context";
|
|
43
43
|
import { Message, Role, TextMessage } from "@copilotkit/runtime-client-gql";
|
|
44
44
|
import { SystemMessageFunction } from "../types";
|
|
45
45
|
import { useChat } from "./use-chat";
|
|
@@ -78,6 +78,7 @@ export interface UseCopilotChatReturn {
|
|
|
78
78
|
deleteMessage: (messageId: string) => void;
|
|
79
79
|
reloadMessages: () => Promise<void>;
|
|
80
80
|
stopGeneration: () => void;
|
|
81
|
+
reset: () => void;
|
|
81
82
|
isLoading: boolean;
|
|
82
83
|
}
|
|
83
84
|
|
|
@@ -99,6 +100,12 @@ export function useCopilotChat({
|
|
|
99
100
|
coAgentStateRenders,
|
|
100
101
|
agentSession,
|
|
101
102
|
setAgentSession,
|
|
103
|
+
agentLock,
|
|
104
|
+
threadId,
|
|
105
|
+
setThreadId,
|
|
106
|
+
runId,
|
|
107
|
+
setRunId,
|
|
108
|
+
chatAbortControllerRef,
|
|
102
109
|
} = useCopilotContext();
|
|
103
110
|
const { messages, setMessages } = useCopilotMessagesContext();
|
|
104
111
|
|
|
@@ -157,11 +164,16 @@ export function useCopilotChat({
|
|
|
157
164
|
setCoagentStates,
|
|
158
165
|
agentSession,
|
|
159
166
|
setAgentSession,
|
|
167
|
+
threadId,
|
|
168
|
+
setThreadId,
|
|
169
|
+
runId,
|
|
170
|
+
setRunId,
|
|
171
|
+
chatAbortControllerRef,
|
|
160
172
|
});
|
|
161
173
|
|
|
162
|
-
// this is a workaround born out of a bug that Athena
|
|
174
|
+
// this is a workaround born out of a bug that Athena incessantly ran into.
|
|
163
175
|
// We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --
|
|
164
|
-
// it
|
|
176
|
+
// it referenced the old state of the messages array, and not the latest one.
|
|
165
177
|
//
|
|
166
178
|
// We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.
|
|
167
179
|
//
|
|
@@ -201,12 +213,33 @@ export function useCopilotChat({
|
|
|
201
213
|
[latestSetMessages],
|
|
202
214
|
);
|
|
203
215
|
|
|
216
|
+
const reset = useCallback(() => {
|
|
217
|
+
latestStopFunc();
|
|
218
|
+
setMessages([]);
|
|
219
|
+
setThreadId(null);
|
|
220
|
+
setRunId(null);
|
|
221
|
+
setCoagentStates({});
|
|
222
|
+
let initialAgentSession: AgentSession | null = null;
|
|
223
|
+
if (agentLock) {
|
|
224
|
+
initialAgentSession = {
|
|
225
|
+
agentName: agentLock,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
setAgentSession(initialAgentSession);
|
|
229
|
+
}, [latestStopFunc, setMessages, setThreadId, setCoagentStates, setAgentSession, agentLock]);
|
|
230
|
+
|
|
231
|
+
const latestReset = useUpdatedRef(reset);
|
|
232
|
+
const latestResetFunc = useCallback(() => {
|
|
233
|
+
return latestReset.current();
|
|
234
|
+
}, [latestReset]);
|
|
235
|
+
|
|
204
236
|
return {
|
|
205
237
|
visibleMessages: messages,
|
|
206
238
|
appendMessage: latestAppendFunc,
|
|
207
239
|
setMessages: latestSetMessagesFunc,
|
|
208
240
|
reloadMessages: latestReloadFunc,
|
|
209
241
|
stopGeneration: latestStopFunc,
|
|
242
|
+
reset: latestResetFunc,
|
|
210
243
|
deleteMessage: latestDeleteFunc,
|
|
211
244
|
isLoading,
|
|
212
245
|
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-copilot-chat.ts"],"sourcesContent":["/**\n * `useCopilotChat` is a React hook that lets you directly interact with the\n * Copilot instance. Use to implement a fully custom UI (headless UI) or to\n * programmatically interact with the Copilot instance managed by the default\n * UI.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCopilotChat } from \"@copilotkit/react-core\";\n * import { Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\n *\n * export function YourComponent() {\n * const { appendMessage } = useCopilotChat();\n *\n * appendMessage(\n * new TextMessage({\n * content: \"Hello World\",\n * role: Role.User,\n * }),\n * );\n * }\n * ```\n *\n * `useCopilotChat` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * visibleMessages, // An array of messages that are currently visible in the chat.\n * appendMessage, // A function to append a message to the chat.\n * setMessages, // A function to set the messages in the chat.\n * deleteMessage, // A function to delete a message from the chat.\n * reloadMessages, // A function to reload the messages from the API.\n * stopGeneration, // A function to stop the generation of the next message.\n * isLoading, // A boolean indicating if the chat is loading.\n * } = useCopilotChat();\n * ```\n */\nimport { useRef, useEffect, useCallback } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { Message, Role, TextMessage } from \"@copilotkit/runtime-client-gql\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useChat } from \"./use-chat\";\nimport { defaultCopilotContextCategories } from \"../components\";\nimport { MessageStatusCode } from \"@copilotkit/runtime-client-gql\";\nimport { CoAgentStateRenderHandlerArguments } from \"@copilotkit/shared\";\nimport { useCopilotMessagesContext } from \"../context\";\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n}\n\nexport interface UseCopilotChatReturn {\n visibleMessages: Message[];\n appendMessage: (message: Message) => Promise<void>;\n setMessages: (messages: Message[]) => void;\n deleteMessage: (messageId: string) => void;\n reloadMessages: () => Promise<void>;\n stopGeneration: () => void;\n isLoading: boolean;\n}\n\nexport function useCopilotChat({\n makeSystemMessage,\n ...options\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const {\n getContextString,\n getFunctionCallHandler,\n copilotApiConfig,\n isLoading,\n setIsLoading,\n chatInstructions,\n actions,\n\n coagentStates,\n setCoagentStates,\n coAgentStateRenders,\n agentSession,\n setAgentSession,\n } = useCopilotContext();\n const { messages, setMessages } = useCopilotMessagesContext();\n\n // We need to ensure that makeSystemMessageCallback always uses the latest\n // useCopilotReadable data.\n const latestGetContextString = useUpdatedRef(getContextString);\n const deleteMessage = useCallback(\n (messageId: string) => {\n setMessages((prev) => prev.filter((message) => message.id !== messageId));\n },\n [setMessages],\n );\n\n const makeSystemMessageCallback = useCallback(() => {\n const systemMessageMaker = makeSystemMessage || defaultSystemMessage;\n // this always gets the latest context string\n const contextString = latestGetContextString.current([], defaultCopilotContextCategories); // TODO: make the context categories configurable\n\n return new TextMessage({\n content: systemMessageMaker(contextString, chatInstructions),\n role: Role.System,\n });\n }, [getContextString, makeSystemMessage, chatInstructions]);\n\n const onCoAgentStateRender = useCallback(\n async (args: CoAgentStateRenderHandlerArguments) => {\n const { name, nodeName, state } = args;\n let action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && action.nodeName === nodeName,\n );\n if (!action) {\n action = Object.values(coAgentStateRenders).find(\n (action) => action.name === name && !action.nodeName,\n );\n }\n if (action) {\n await action.handler?.({ state, nodeName });\n }\n },\n [coAgentStateRenders],\n );\n\n const { append, reload, stop } = useChat({\n ...options,\n actions: Object.values(actions),\n copilotConfig: copilotApiConfig,\n initialMessages: options.initialMessages || [],\n onFunctionCall: getFunctionCallHandler(),\n onCoAgentStateRender,\n messages,\n setMessages,\n makeSystemMessageCallback,\n isLoading,\n setIsLoading,\n coagentStates,\n setCoagentStates,\n agentSession,\n setAgentSession,\n });\n\n // this is a workaround born out of a bug that Athena insessently ran into.\n // We could not find the origin of the bug, however, it was clear that an outdated version of the append function was being used somehow --\n // it referecned the old state of the messages array, and not the latest one.\n //\n // We want to make copilotkit as abuse-proof as possible, so we are adding this workaround to ensure that the latest version of the append function is always used.\n //\n // How does this work?\n // we store the relevant function in a ref that is always up-to-date, and then we use that ref in the callback.\n const latestAppend = useUpdatedRef(append);\n const latestAppendFunc = useCallback(\n (message: Message) => {\n return latestAppend.current(message);\n },\n [latestAppend],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useCallback(() => {\n return latestReload.current();\n }, [latestReload]);\n\n const latestStop = useUpdatedRef(stop);\n const latestStopFunc = useCallback(() => {\n return latestStop.current();\n }, [latestStop]);\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const latestSetMessages = useUpdatedRef(setMessages);\n const latestSetMessagesFunc = useCallback(\n (messages: Message[]) => {\n return latestSetMessages.current(messages);\n },\n [latestSetMessages],\n );\n\n return {\n visibleMessages: messages,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n deleteMessage: latestDeleteFunc,\n isLoading,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,QAAQ,WAAW,mBAAmB;AAE/C,SAAkB,MAAM,mBAAmB;AAyCpC,SAAS,eAAe,KAGJ,CAAC,GAAyB;AAHtB,eAC7B;AAAA;AAAA,EApFF,IAmF+B,IAE1B,oBAF0B,IAE1B;AAAA,IADH;AAAA;AAGA,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,kBAAkB;AACtB,QAAM,EAAE,UAAU,YAAY,IAAI,0BAA0B;AAI5D,QAAM,yBAAyB,cAAc,gBAAgB;AAC7D,QAAM,gBAAgB;AAAA,IACpB,CAAC,cAAsB;AACrB,kBAAY,CAAC,SAAS,KAAK,OAAO,CAAC,YAAY,QAAQ,OAAO,SAAS,CAAC;AAAA,IAC1E;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAEA,QAAM,4BAA4B,YAAY,MAAM;AAClD,UA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,QAAM,eAAe,cAAc,MAAM;AACzC,QAAM,mBAAmB,YAAY,MAAM;AACzC,WAAO,aAAa,QAAQ;AAAA,EAC9B,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,aAAa,cAAc,IAAI;AACrC,QAAM,iBAAiB,YAAY,MAAM;AACvC,WAAO,WAAW,QAAQ;AAAA,EAC5B,GAAG,CAAC,UAAU,CAAC;AAEf,QAAM,eAAe,cAAc,aAAa;AAChD,QAAM,mBAAmB;AAAA,IACvB,CAAC,cAAsB;AACrB,aAAO,aAAa,QAAQ,SAAS;AAAA,IACvC;AAAA,IACA,CAAC,YAAY;AAAA,EACf;AAEA,QAAM,oBAAoB,cAAc,WAAW;AACnD,QAAM,wBAAwB;AAAA,IAC5B,CAACE,cAAwB;AACvB,aAAO,kBAAkB,QAAQA,SAAQ;AAAA,IAC3C;AAAA,IACA,CAAC,iBAAiB;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf;AAAA,EACF;AACF;AAIA,SAAS,cAAiB,OAAU;AAClC,QAAM,MAAM,OAAO,KAAK;AAExB,YAAU,MAAM;AACd,QAAI,UAAU;AAAA,EAChB,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO;AACT;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAUG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["_a","action","messages"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-chat.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport {\n FunctionCallHandler,\n COPILOT_CLOUD_PUBLIC_API_KEY_HEADER,\n actionParametersToJsonSchema,\n CoAgentStateRenderHandler,\n} from \"@copilotkit/shared\";\nimport {\n Message,\n TextMessage,\n ResultMessage,\n convertMessagesToGqlInput,\n filterAdjacentAgentStateMessages,\n filterAgentStateMessages,\n convertGqlOutputToMessages,\n MessageStatusCode,\n MessageRole,\n Role,\n CopilotRequestType,\n ActionInputAvailability,\n} from \"@copilotkit/runtime-client-gql\";\n\nimport { CopilotApiConfig } from \"../context\";\nimport { FrontendAction } from \"../types/frontend-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport { AgentSession } from \"../context/copilot-context\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCopilotRuntimeClient } from \"./use-copilot-runtime-client\";\n\nexport type UseChatOptions = {\n /**\n * System messages of the chat. Defaults to an empty array.\n */\n initialMessages?: Message[];\n /**\n * Callback function to be called when a function call is received.\n * If the function returns a `ChatRequest` object, the request will be sent\n * automatically to the API and will be used to update the chat.\n */\n onFunctionCall?: FunctionCallHandler;\n\n /**\n * Callback function to be called when a coagent action is received.\n */\n onCoAgentStateRender?: CoAgentStateRenderHandler;\n\n /**\n * Function definitions to be sent to the API.\n */\n actions: FrontendAction<any>[];\n\n /**\n * The CopilotKit API configuration.\n */\n copilotConfig: CopilotApiConfig;\n\n /**\n * The current list of messages in the chat.\n */\n messages: Message[];\n /**\n * The setState-powered method to update the chat messages.\n */\n setMessages: React.Dispatch<React.SetStateAction<Message[]>>;\n\n /**\n * A callback to get the latest system message.\n */\n makeSystemMessageCallback: () => TextMessage;\n\n /**\n * Whether the API request is in progress\n */\n isLoading: boolean;\n\n /**\n * setState-powered method to update the isChatLoading value\n */\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n /**\n * The current list of coagent states.\n */\n coagentStates: Record<string, CoagentState>;\n\n /**\n * setState-powered method to update the agent states\n */\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n\n /**\n * The current agent session.\n */\n agentSession: AgentSession | null;\n\n /**\n * setState-powered method to update the agent session\n */\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n};\n\nexport type UseChatHelpers = {\n /**\n * Append a user message to the chat list. This triggers the API call to fetch\n * the assistant's response.\n * @param message The message to append\n */\n append: (message: Message) => Promise<void>;\n /**\n * Reload the last AI chat response for the given chat history. If the last\n * message isn't from the assistant, it will request the API to generate a\n * new response.\n */\n reload: () => Promise<void>;\n /**\n * Abort the current request immediately, keep the generated tokens if any.\n */\n stop: () => void;\n};\n\nexport function useChat(options: UseChatOptions): UseChatHelpers {\n const {\n messages,\n setMessages,\n makeSystemMessageCallback,\n copilotConfig,\n setIsLoading,\n initialMessages,\n isLoading,\n actions,\n onFunctionCall,\n onCoAgentStateRender,\n setCoagentStates,\n coagentStates,\n agentSession,\n setAgentSession,\n } = options;\n\n const abortControllerRef = useRef<AbortController>();\n const threadIdRef = useRef<string | null>(null);\n const runIdRef = useRef<string | null>(null);\n const { addGraphQLErrorsToast } = useToast();\n\n const runChatCompletionRef = useRef<(previousMessages: Message[]) => Promise<Message[]>>();\n // We need to keep a ref of coagent states because of renderAndWait - making sure\n // the latest state is sent to the API\n // This is a workaround and needs to be addressed in the future\n const coagentStatesRef = useRef<Record<string, CoagentState>>(coagentStates);\n coagentStatesRef.current = coagentStates;\n const agentSessionRef = useRef<AgentSession | null>(agentSession);\n agentSessionRef.current = agentSession;\n\n const publicApiKey = copilotConfig.publicApiKey;\n\n const headers = {\n ...(copilotConfig.headers || {}),\n ...(publicApiKey ? { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}),\n };\n\n const runtimeClient = useCopilotRuntimeClient({\n url: copilotConfig.chatApiEndpoint,\n publicApiKey: copilotConfig.publicApiKey,\n headers,\n credentials: copilotConfig.credentials,\n });\n\n const runChatCompletion = async (previousMessages: Message[]): Promise<Message[]> => {\n setIsLoading(true);\n\n // this message is just a placeholder. It will disappear once the first real message\n // is received\n let newMessages: Message[] = [\n new TextMessage({\n content: \"\",\n role: Role.Assistant,\n }),\n ];\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setMessages([...previousMessages, ...newMessages]);\n\n const systemMessage = makeSystemMessageCallback();\n\n const messagesWithContext = [systemMessage, ...(initialMessages || []), ...previousMessages];\n\n const stream = runtimeClient.asStream(\n runtimeClient.generateCopilotResponse({\n data: {\n frontend: {\n actions: actions\n .filter(\n (action) =>\n action.available !== ActionInputAvailability.Disabled || !action.disabled,\n )\n .map((action) => {\n let available: ActionInputAvailability | undefined =\n ActionInputAvailability.Enabled;\n if (action.disabled) {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"disabled\") {\n available = ActionInputAvailability.Disabled;\n } else if (action.available === \"remote\") {\n available = ActionInputAvailability.Remote;\n }\n return {\n name: action.name,\n description: action.description || \"\",\n jsonSchema: JSON.stringify(actionParametersToJsonSchema(action.parameters || [])),\n available,\n };\n }),\n url: window.location.href,\n },\n threadId: threadIdRef.current,\n runId: runIdRef.current,\n messages: convertMessagesToGqlInput(filterAgentStateMessages(messagesWithContext)),\n ...(copilotConfig.cloud\n ? {\n cloud: {\n ...(copilotConfig.cloud.guardrails?.input?.restrictToTopic?.enabled\n ? {\n guardrails: {\n inputValidationRules: {\n allowList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,\n denyList:\n copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics,\n },\n },\n }\n : {}),\n },\n }\n : {}),\n metadata: {\n requestType: CopilotRequestType.Chat,\n },\n ...(agentSessionRef.current\n ? {\n agentSession: agentSessionRef.current,\n }\n : {}),\n agentStates: Object.values(coagentStatesRef.current).map((state) => ({\n agentName: state.name,\n state: JSON.stringify(state.state),\n })),\n },\n properties: copilotConfig.properties,\n signal: abortControllerRef.current?.signal,\n }),\n );\n\n const guardrailsEnabled =\n copilotConfig.cloud?.guardrails?.input?.restrictToTopic.enabled || false;\n\n const reader = stream.getReader();\n\n let actionResults: { [id: string]: string } = {};\n let executedCoAgentStateRenders: string[] = [];\n let followUp: FrontendAction[\"followUp\"] = undefined;\n\n try {\n while (true) {\n let done, value;\n\n try {\n const readResult = await reader.read();\n done = readResult.done;\n value = readResult.value;\n } catch (readError) {\n break;\n }\n\n if (done) {\n break;\n }\n\n if (!value?.generateCopilotResponse) {\n continue;\n }\n\n threadIdRef.current = value.generateCopilotResponse.threadId || null;\n runIdRef.current = value.generateCopilotResponse.runId || null;\n\n const messages = convertGqlOutputToMessages(\n filterAdjacentAgentStateMessages(value.generateCopilotResponse.messages),\n );\n\n if (messages.length === 0) {\n continue;\n }\n\n newMessages = [];\n\n // request failed, display error message\n if (\n value.generateCopilotResponse.status?.__typename === \"FailedResponseStatus\" &&\n value.generateCopilotResponse.status.reason === \"GUARDRAILS_VALIDATION_FAILED\"\n ) {\n newMessages = [\n new TextMessage({\n role: MessageRole.Assistant,\n content: value.generateCopilotResponse.status.details?.guardrailsReason || \"\",\n }),\n ];\n }\n\n // add messages to the chat\n else {\n for (const message of messages) {\n newMessages.push(message);\n // execute regular action executions\n if (\n message.isActionExecutionMessage() &&\n message.status.code !== MessageStatusCode.Pending &&\n message.scope === \"client\" &&\n onFunctionCall\n ) {\n if (!(message.id in actionResults)) {\n // Do not execute a function call if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute action\n try {\n // We update the message state before calling the handler so that the render\n // function can be called with `executing` state\n setMessages([...previousMessages, ...newMessages]);\n\n const action = actions.find((action) => action.name === message.name);\n\n if (action) {\n followUp = action.followUp;\n }\n\n const result = await onFunctionCall({\n messages: previousMessages,\n name: message.name,\n args: message.arguments,\n });\n actionResults[message.id] = result;\n } catch (e) {\n actionResults[message.id] = `Failed to execute action ${message.name}`;\n console.error(`Failed to execute action ${message.name}: ${e}`);\n }\n }\n // add the result message\n newMessages.push(\n new ResultMessage({\n result: ResultMessage.encodeResult(actionResults[message.id]),\n actionExecutionId: message.id,\n actionName: message.name,\n }),\n );\n }\n // execute coagent actions\n if (\n message.isAgentStateMessage() &&\n !message.active &&\n !executedCoAgentStateRenders.includes(message.id) &&\n onCoAgentStateRender\n ) {\n // Do not execute a coagent action if guardrails are enabled but the status is not known\n if (guardrailsEnabled && value.generateCopilotResponse.status === undefined) {\n break;\n }\n // execute coagent action\n await onCoAgentStateRender({\n name: message.agentName,\n nodeName: message.nodeName,\n state: message.state,\n });\n executedCoAgentStateRenders.push(message.id);\n }\n }\n\n const lastAgentStateMessage = [...messages]\n .reverse()\n .find((message) => message.isAgentStateMessage());\n\n if (lastAgentStateMessage) {\n setCoagentStates((prevAgentStates) => ({\n ...prevAgentStates,\n [lastAgentStateMessage.agentName]: {\n name: lastAgentStateMessage.agentName,\n state: lastAgentStateMessage.state,\n running: lastAgentStateMessage.running,\n active: lastAgentStateMessage.active,\n threadId: lastAgentStateMessage.threadId,\n nodeName: lastAgentStateMessage.nodeName,\n runId: lastAgentStateMessage.runId,\n },\n }));\n if (lastAgentStateMessage.running) {\n setAgentSession({\n threadId: lastAgentStateMessage.threadId,\n agentName: lastAgentStateMessage.agentName,\n nodeName: lastAgentStateMessage.nodeName,\n });\n } else {\n setAgentSession(null);\n }\n }\n }\n\n if (newMessages.length > 0) {\n // Update message state\n setMessages([...previousMessages, ...newMessages]);\n }\n }\n\n if (\n // if followUp is not explicitly false\n followUp !== false &&\n // if we have client side results\n (Object.values(actionResults).length ||\n // or the last message we received is a result\n (newMessages.length && newMessages[newMessages.length - 1].isResultMessage()))\n ) {\n // run the completion again and return the result\n\n // wait for next tick to make sure all the react state updates\n // - tried using react-dom's flushSync, but it did not work\n await new Promise((resolve) => setTimeout(resolve, 10));\n\n return await runChatCompletionRef.current!([...previousMessages, ...newMessages]);\n } else {\n return newMessages.slice();\n }\n } finally {\n setIsLoading(false);\n }\n };\n\n runChatCompletionRef.current = runChatCompletion;\n\n const runChatCompletionAndHandleFunctionCall = async (messages: Message[]): Promise<void> => {\n await runChatCompletionRef.current!(messages);\n };\n\n const append = async (message: Message): Promise<void> => {\n if (isLoading) {\n return;\n }\n\n const newMessages = [...messages, message];\n setMessages(newMessages);\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const reload = async (): Promise<void> => {\n if (isLoading || messages.length === 0) {\n return;\n }\n let newMessages = [...messages];\n const lastMessage = messages[messages.length - 1];\n\n if (lastMessage.isTextMessage() && lastMessage.role === \"assistant\") {\n newMessages = newMessages.slice(0, -1);\n }\n\n setMessages(newMessages);\n\n return runChatCompletionAndHandleFunctionCall(newMessages);\n };\n\n const stop = (): void => {\n abortControllerRef.current?.abort();\n };\n\n return {\n append,\n reload,\n stop,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAoGA,SAAS,QAAQ,SAAyC;AAC/D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,qBAAqB,OAAwB;AACnD,QAAM,cAAc,OAAsB,IAAI;AAC9C,QAAM,WAAW,OAAsB,IAAI;AAC3C,QAAM,EAAE,sBAAsB,IAAI,SAAS;AAE3C,QAAM,uBAAuB,OAA4D;AAIzF,QAAM,mBAAmB,OAAqC,aAAa;AAC3E,mBAAiB,UAAU;AAC3B,QAAM,kBAAkB,OAA4B,YAAY;AAChE,kBAAgB,UAAU;AAE1B,QAAM,eAAe,cAAc;AAEnC,QAAM,UAAU,kCACV,cAAc,WAAW,CAAC,IAC1B,eAAe,EAAE,CAAC,mCAAmC,GAAG,aAAa,IAAI,CAAC;AAGhF,QAAM,gBAAgB,wBAAwB;AA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,OAAO,OAAO,aAAa,EAAE;AAAA,QAE3B,YAAY,UAAU,YAAY,YAAY,SAAS,CAAC,EAAE,gBAAgB;AAAA,QAC7E;AAKA,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAEtD,eAAO,MAAM,qBAAqB,QAAS,CAAC,GAAG,kBAAkB,GAAG,WAAW,CAAC;AAAA,MAClF,OAAO;AACL,eAAO,YAAY,MAAM;AAAA,MAC3B;AAAA,IACF,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF;AAEA,uBAAqB,UAAU;AAE/B,QAAM,yCAAyC,CAAOA,cAAuC;AAC3F,UAAM,qBAAqB,QAASA,SAAQ;AAAA,EAC9C;AAEA,QAAM,SAAS,CAAO,YAAoC;AACxD,QAAI,WAAW;AACb;AAAA,IACF;AAEA,UAAM,cAAc,CAAC,GAAG,UAAU,OAAO;AACzC,gBAAY,WAAW;AACvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,SAAS,MAA2B;AACxC,QAAI,aAAa,SAAS,WAAW,GAAG;AACtC;AAAA,IACF;AACA,QAAI,cAAc,CAAC,GAAG,QAAQ;AAC9B,UAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,QAAI,YAAY,cAAc,KAAK,YAAY,SAAS,aAAa;AACnE,oBAAc,YAAY,MAAM,GAAG,EAAE;AAAA,IACvC;AAEA,gBAAY,WAAW;AAEvB,WAAO,uCAAuC,WAAW;AAAA,EAC3D;AAEA,QAAM,OAAO,MAAY;AAnd3B;AAodI,6BAAmB,YAAnB,mBAA4B;AAAA,EAC9B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["messages","action"]}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|