@copilotz/chat-adapter 0.1.18 → 0.1.20

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
@@ -1,5 +1,5 @@
1
1
  import React, { ReactNode } from 'react';
2
- import { ChatUserContext, ChatConfig, ChatCallbacks, MemoryItem, AgentOption, ChatMessage, ChatThread, MediaAttachment } from '@copilotz/chat-ui';
2
+ import { MediaAttachment, ChatUserContext, ChatConfig, ChatCallbacks, MemoryItem, AgentOption, ChatMessage, ChatThread } from '@copilotz/chat-ui';
3
3
  export { ChatCallbacks, ChatConfig, ChatMessage, ChatThread, ChatUserContext, MediaAttachment, MemoryItem } from '@copilotz/chat-ui';
4
4
 
5
5
  /**
@@ -105,9 +105,88 @@ type EventInterceptorResult = void | {
105
105
  type EventInterceptor = (event: unknown) => EventInterceptorResult;
106
106
  type RunErrorInterceptor = (error: unknown) => SpecialChatState | null | undefined;
107
107
 
108
+ type RequestHeadersProvider = () => Record<string, string> | Promise<Record<string, string>>;
109
+ type RestThread = {
110
+ id: string;
111
+ name?: string | null;
112
+ externalId?: string | null;
113
+ description?: string | null;
114
+ participants?: string[] | null;
115
+ status?: string | null;
116
+ metadata?: Record<string, unknown> | null;
117
+ createdAt?: string;
118
+ updatedAt?: string;
119
+ };
120
+ type RestMessage = {
121
+ id: string;
122
+ threadId: string;
123
+ senderId?: string | null;
124
+ senderType: string;
125
+ senderUserId?: string | null;
126
+ content?: string | null;
127
+ metadata?: Record<string, unknown> | null;
128
+ toolCalls?: Array<Record<string, unknown>> | null;
129
+ createdAt?: string;
130
+ updatedAt?: string;
131
+ };
132
+ type StreamCallbacks = {
133
+ onToken?: (token: string, isComplete: boolean, raw?: any) => void;
134
+ onMessageEvent?: (payload: any) => void;
135
+ onAssetEvent?: (payload: any) => void;
136
+ signal?: AbortSignal;
137
+ };
138
+ type RunOptions = {
139
+ threadId?: string;
140
+ threadExternalId?: string;
141
+ content: string;
142
+ user: {
143
+ externalId: string;
144
+ name?: string;
145
+ email?: string;
146
+ metadata?: Record<string, unknown>;
147
+ };
148
+ attachments?: MediaAttachment[];
149
+ metadata?: Record<string, unknown>;
150
+ threadMetadata?: Record<string, unknown>;
151
+ toolCalls?: Array<{
152
+ name: string;
153
+ args: Record<string, unknown>;
154
+ id?: string;
155
+ }>;
156
+ selectedAgent?: string | null;
157
+ getRequestHeaders?: RequestHeadersProvider;
158
+ } & StreamCallbacks;
159
+ type CopilotzStreamResult = {
160
+ text: string;
161
+ messages: any[];
162
+ media: Record<string, string> | null;
163
+ };
164
+ declare class CopilotzRequestError extends Error {
165
+ status: number;
166
+ code?: string;
167
+ details?: unknown;
168
+ constructor(message: string, options: {
169
+ status: number;
170
+ code?: string;
171
+ details?: unknown;
172
+ });
173
+ }
174
+ declare function runCopilotzStream(options: RunOptions): Promise<CopilotzStreamResult>;
175
+ declare function fetchThreads(userId: string, getRequestHeaders?: RequestHeadersProvider): Promise<RestThread[]>;
176
+ declare function fetchThreadMessages(threadId: string, getRequestHeaders?: RequestHeadersProvider): Promise<RestMessage[]>;
177
+ declare function updateThread(threadId: string, updates: Partial<RestThread>, getRequestHeaders?: RequestHeadersProvider): Promise<any>;
178
+ declare function deleteMessagesByThreadId(threadId: string, getRequestHeaders?: RequestHeadersProvider): Promise<void>;
179
+ declare function deleteThread(threadId: string, getRequestHeaders?: RequestHeadersProvider): Promise<boolean>;
180
+ declare const copilotzService: {
181
+ runCopilotzStream: typeof runCopilotzStream;
182
+ fetchThreads: typeof fetchThreads;
183
+ fetchThreadMessages: typeof fetchThreadMessages;
184
+ updateThread: typeof updateThread;
185
+ deleteThread: typeof deleteThread;
186
+ };
187
+
108
188
  interface CopilotzChatProps {
109
189
  userId: string;
110
- authToken?: string | null;
111
190
  userName?: string;
112
191
  userAvatar?: string;
113
192
  userEmail?: string;
@@ -150,6 +229,7 @@ interface CopilotzChatProps {
150
229
  agentOptions?: AgentOption[];
151
230
  selectedAgentId?: string | null;
152
231
  onSelectAgent?: (agentId: string) => void;
232
+ getRequestHeaders?: RequestHeadersProvider;
153
233
  className?: string;
154
234
  eventInterceptor?: EventInterceptor;
155
235
  runErrorInterceptor?: RunErrorInterceptor;
@@ -187,7 +267,6 @@ declare const CopilotzChat: React.FC<CopilotzChatProps>;
187
267
 
188
268
  interface UseCopilotzOptions {
189
269
  userId: string | null;
190
- authToken?: string | null;
191
270
  initialContext?: ChatUserContext;
192
271
  bootstrap?: {
193
272
  initialMessage?: string;
@@ -199,6 +278,7 @@ interface UseCopilotzOptions {
199
278
  defaultThreadName?: string;
200
279
  onToolOutput?: (output: Record<string, unknown>) => void;
201
280
  preferredAgentName?: string | null;
281
+ getRequestHeaders?: RequestHeadersProvider;
202
282
  eventInterceptor?: EventInterceptor;
203
283
  runErrorInterceptor?: RunErrorInterceptor;
204
284
  /**
@@ -219,7 +299,7 @@ interface UseCopilotzOptions {
219
299
  */
220
300
  urlSync?: UrlSyncConfig;
221
301
  }
222
- declare function useCopilotz({ userId, authToken, initialContext, bootstrap, defaultThreadName, onToolOutput, preferredAgentName, eventInterceptor, runErrorInterceptor, urlSync, }: UseCopilotzOptions): {
302
+ declare function useCopilotz({ userId, initialContext, bootstrap, defaultThreadName, onToolOutput, preferredAgentName, getRequestHeaders, eventInterceptor, runErrorInterceptor, urlSync, }: UseCopilotzOptions): {
223
303
  messages: ChatMessage[];
224
304
  isMessagesLoading: boolean;
225
305
  threads: ChatThread[];
@@ -248,85 +328,6 @@ declare function useCopilotz({ userId, authToken, initialContext, bootstrap, def
248
328
  setUrlAgentId: (agentId: string | null) => void;
249
329
  };
250
330
 
251
- type RestThread = {
252
- id: string;
253
- name?: string | null;
254
- externalId?: string | null;
255
- description?: string | null;
256
- participants?: string[] | null;
257
- status?: string | null;
258
- metadata?: Record<string, unknown> | null;
259
- createdAt?: string;
260
- updatedAt?: string;
261
- };
262
- type RestMessage = {
263
- id: string;
264
- threadId: string;
265
- senderId?: string | null;
266
- senderType: string;
267
- senderUserId?: string | null;
268
- content?: string | null;
269
- metadata?: Record<string, unknown> | null;
270
- toolCalls?: Array<Record<string, unknown>> | null;
271
- createdAt?: string;
272
- updatedAt?: string;
273
- };
274
- type StreamCallbacks = {
275
- onToken?: (token: string, isComplete: boolean, raw?: any) => void;
276
- onMessageEvent?: (payload: any) => void;
277
- onAssetEvent?: (payload: any) => void;
278
- signal?: AbortSignal;
279
- };
280
- type RunOptions = {
281
- authToken?: string | null;
282
- threadId?: string;
283
- threadExternalId?: string;
284
- content: string;
285
- user: {
286
- externalId: string;
287
- name?: string;
288
- email?: string;
289
- metadata?: Record<string, unknown>;
290
- };
291
- attachments?: MediaAttachment[];
292
- metadata?: Record<string, unknown>;
293
- threadMetadata?: Record<string, unknown>;
294
- toolCalls?: Array<{
295
- name: string;
296
- args: Record<string, unknown>;
297
- id?: string;
298
- }>;
299
- selectedAgent?: string | null;
300
- } & StreamCallbacks;
301
- type CopilotzStreamResult = {
302
- text: string;
303
- messages: any[];
304
- media: Record<string, string> | null;
305
- };
306
- declare class CopilotzRequestError extends Error {
307
- status: number;
308
- code?: string;
309
- details?: unknown;
310
- constructor(message: string, options: {
311
- status: number;
312
- code?: string;
313
- details?: unknown;
314
- });
315
- }
316
- declare function runCopilotzStream(options: RunOptions): Promise<CopilotzStreamResult>;
317
- declare function fetchThreads(userId: string, authToken?: string | null): Promise<RestThread[]>;
318
- declare function fetchThreadMessages(threadId: string, authToken?: string | null): Promise<RestMessage[]>;
319
- declare function updateThread(threadId: string, updates: Partial<RestThread>, authToken?: string | null): Promise<any>;
320
- declare function deleteMessagesByThreadId(threadId: string, authToken?: string | null): Promise<void>;
321
- declare function deleteThread(threadId: string, authToken?: string | null): Promise<boolean>;
322
- declare const copilotzService: {
323
- runCopilotzStream: typeof runCopilotzStream;
324
- fetchThreads: typeof fetchThreads;
325
- fetchThreadMessages: typeof fetchThreadMessages;
326
- updateThread: typeof updateThread;
327
- deleteThread: typeof deleteThread;
328
- };
329
-
330
331
  declare function getAssetDataUrl(refOrId: string): Promise<{
331
332
  dataUrl: string;
332
333
  mime?: string;
@@ -337,4 +338,4 @@ type WithMetadata = {
337
338
  };
338
339
  declare function resolveAssetsInMessages<T extends WithMetadata>(messages: T[]): Promise<T[]>;
339
340
 
340
- export { CopilotzChat, CopilotzRequestError, type CopilotzStreamResult, type EventInterceptor, type EventInterceptorResult, type RenderSpecialState, type RunErrorInterceptor, type SpecialChatState, type SpecialStateControls, type UrlParamsConfig, type UrlState, type UrlSyncConfig, type UseUrlStateReturn, copilotzService, deleteMessagesByThreadId, deleteThread, fetchThreadMessages, fetchThreads, getAssetDataUrl, resolveAssetsInMessages, runCopilotzStream, updateThread, useCopilotz, useUrlState };
341
+ export { CopilotzChat, CopilotzRequestError, type CopilotzStreamResult, type EventInterceptor, type EventInterceptorResult, type RenderSpecialState, type RequestHeadersProvider, type RunErrorInterceptor, type SpecialChatState, type SpecialStateControls, type UrlParamsConfig, type UrlState, type UrlSyncConfig, type UseUrlStateReturn, copilotzService, deleteMessagesByThreadId, deleteThread, fetchThreadMessages, fetchThreads, getAssetDataUrl, resolveAssetsInMessages, runCopilotzStream, updateThread, useCopilotz, useUrlState };
package/dist/index.js CHANGED
@@ -118,10 +118,13 @@ var API_KEY = (() => {
118
118
  ];
119
119
  return candidates.find((value) => typeof value === "string" && value.length > 0);
120
120
  })();
121
- var withAuthHeaders = (headers = {}, authToken) => {
122
- const token = authToken || API_KEY;
123
- if (token) {
124
- return { ...headers, Authorization: `Bearer ${token}` };
121
+ var withAuthHeaders = async (headers = {}, getRequestHeaders) => {
122
+ const providedHeaders = getRequestHeaders ? await getRequestHeaders() : void 0;
123
+ if (providedHeaders && Object.keys(providedHeaders).length > 0) {
124
+ return { ...headers, ...providedHeaders };
125
+ }
126
+ if (API_KEY) {
127
+ return { ...headers, Authorization: `Bearer ${API_KEY}` };
125
128
  }
126
129
  return headers;
127
130
  };
@@ -272,7 +275,6 @@ var convertAudioDataUrlToWavBase64 = async (dataUrl) => {
272
275
  };
273
276
  async function runCopilotzStream(options) {
274
277
  const {
275
- authToken,
276
278
  threadId,
277
279
  threadExternalId,
278
280
  content,
@@ -282,6 +284,7 @@ async function runCopilotzStream(options) {
282
284
  threadMetadata,
283
285
  toolCalls,
284
286
  selectedAgent,
287
+ getRequestHeaders,
285
288
  onToken,
286
289
  onMessageEvent,
287
290
  onAssetEvent,
@@ -379,9 +382,9 @@ async function runCopilotzStream(options) {
379
382
  };
380
383
  const response = await fetch(apiUrl("/v1/providers/web"), {
381
384
  method: "POST",
382
- headers: withAuthHeaders({
385
+ headers: await withAuthHeaders({
383
386
  "Content-Type": "application/json"
384
- }, authToken),
387
+ }, getRequestHeaders),
385
388
  body: JSON.stringify(payload),
386
389
  signal: controller.signal
387
390
  });
@@ -491,12 +494,12 @@ async function runCopilotzStream(options) {
491
494
  media: collectedMedia
492
495
  };
493
496
  }
494
- async function fetchThreads(userId, authToken) {
497
+ async function fetchThreads(userId, getRequestHeaders) {
495
498
  const params = new URLSearchParams();
496
499
  params.set("filters", JSON.stringify({ "metadata.userExternalId": userId }));
497
500
  params.set("sort", "-updatedAt");
498
501
  const res = await fetch(apiUrl(`/v1/rest/threads?${params.toString()}`), {
499
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
502
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
500
503
  });
501
504
  if (!res.ok) {
502
505
  const errorText = await res.text().catch(() => res.statusText);
@@ -508,13 +511,13 @@ async function fetchThreads(userId, authToken) {
508
511
  }
509
512
  return data;
510
513
  }
511
- async function fetchThreadMessages(threadId, authToken) {
514
+ async function fetchThreadMessages(threadId, getRequestHeaders) {
512
515
  const graphParams = new URLSearchParams();
513
516
  graphParams.set("threadId", threadId);
514
517
  graphParams.set("limit", "500");
515
518
  try {
516
519
  const graphRes = await fetch(apiUrl(`/v1/messages?${graphParams.toString()}`), {
517
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
520
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
518
521
  });
519
522
  if (graphRes.ok) {
520
523
  const graphData = await graphRes.json();
@@ -540,7 +543,7 @@ async function fetchThreadMessages(threadId, authToken) {
540
543
  params.set("filters", JSON.stringify({ threadId }));
541
544
  params.set("sort", "createdAt:asc");
542
545
  const res = await fetch(apiUrl(`/v1/rest/messages?${params.toString()}`), {
543
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
546
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
544
547
  });
545
548
  if (!res.ok) {
546
549
  const errorText = await res.text().catch(() => res.statusText);
@@ -552,10 +555,10 @@ async function fetchThreadMessages(threadId, authToken) {
552
555
  }
553
556
  return data;
554
557
  }
555
- async function updateThread(threadId, updates, authToken) {
558
+ async function updateThread(threadId, updates, getRequestHeaders) {
556
559
  const res = await fetch(apiUrl(`/v1/rest/threads/${threadId}`), {
557
560
  method: "PUT",
558
- headers: withAuthHeaders({ "Content-Type": "application/json", Accept: "application/json" }, authToken),
561
+ headers: await withAuthHeaders({ "Content-Type": "application/json", Accept: "application/json" }, getRequestHeaders),
559
562
  body: JSON.stringify(updates)
560
563
  });
561
564
  if (!res.ok) {
@@ -565,13 +568,13 @@ async function updateThread(threadId, updates, authToken) {
565
568
  const data = await res.json();
566
569
  return data?.body ?? data;
567
570
  }
568
- async function deleteMessagesByThreadId(threadId, authToken) {
571
+ async function deleteMessagesByThreadId(threadId, getRequestHeaders) {
569
572
  const graphParams = new URLSearchParams();
570
573
  graphParams.set("threadId", threadId);
571
574
  try {
572
575
  const graphRes = await fetch(apiUrl(`/v1/messages?${graphParams.toString()}`), {
573
576
  method: "DELETE",
574
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
577
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
575
578
  });
576
579
  if (!graphRes.ok && ![404, 405, 501].includes(graphRes.status)) {
577
580
  const errorText = await graphRes.text().catch(() => graphRes.statusText);
@@ -586,7 +589,7 @@ async function deleteMessagesByThreadId(threadId, authToken) {
586
589
  const params = new URLSearchParams();
587
590
  params.set("filters", JSON.stringify({ threadId }));
588
591
  const res = await fetch(apiUrl(`/v1/rest/messages?${params.toString()}`), {
589
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
592
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
590
593
  });
591
594
  if (!res.ok) {
592
595
  console.warn("Could not fetch messages for deletion:", res.status);
@@ -601,18 +604,18 @@ async function deleteMessagesByThreadId(threadId, authToken) {
601
604
  try {
602
605
  await fetch(apiUrl(`/v1/rest/messages/${msg.id}`), {
603
606
  method: "DELETE",
604
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
607
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
605
608
  });
606
609
  } catch {
607
610
  }
608
611
  }
609
612
  }
610
613
  }
611
- async function deleteThread(threadId, authToken) {
612
- await deleteMessagesByThreadId(threadId, authToken);
614
+ async function deleteThread(threadId, getRequestHeaders) {
615
+ await deleteMessagesByThreadId(threadId, getRequestHeaders);
613
616
  const res = await fetch(apiUrl(`/v1/rest/threads/${threadId}`), {
614
617
  method: "DELETE",
615
- headers: withAuthHeaders({ Accept: "application/json" }, authToken)
618
+ headers: await withAuthHeaders({ Accept: "application/json" }, getRequestHeaders)
616
619
  });
617
620
  if (!res.ok) {
618
621
  const errorText = await res.text().catch(() => res.statusText);
@@ -943,6 +946,7 @@ var convertServerMessage = (msg) => {
943
946
  });
944
947
  const role = msg.senderType === "agent" ? "assistant" : msg.senderType === "user" ? "user" : "assistant";
945
948
  const parsedToolCalls = extractToolCallsFromServerMessage(msg);
949
+ const shouldRenderToolCalls = msg.senderType !== "tool";
946
950
  const mappedToolCalls = parsedToolCalls.map((toolCall) => ({
947
951
  id: toolCall.id ?? generateId(),
948
952
  name: toolCall.name,
@@ -950,7 +954,7 @@ var convertServerMessage = (msg) => {
950
954
  status: toolCall.status,
951
955
  ...toolCall.result !== void 0 ? { result: toolCall.result } : {}
952
956
  }));
953
- const hasToolCalls = mappedToolCalls.length > 0;
957
+ const hasToolCalls = shouldRenderToolCalls && mappedToolCalls.length > 0;
954
958
  const isToolSender = msg.senderType === "tool";
955
959
  const content = isToolSender ? "" : (msg.content ?? "") || (hasToolCalls ? "" : "");
956
960
  return {
@@ -967,12 +971,12 @@ var convertServerMessage = (msg) => {
967
971
  };
968
972
  function useCopilotz({
969
973
  userId,
970
- authToken,
971
974
  initialContext,
972
975
  bootstrap,
973
976
  defaultThreadName,
974
977
  onToolOutput,
975
978
  preferredAgentName,
979
+ getRequestHeaders,
976
980
  eventInterceptor,
977
981
  runErrorInterceptor,
978
982
  urlSync
@@ -1034,7 +1038,7 @@ function useCopilotz({
1034
1038
  if (!eventInterceptor) return void 0;
1035
1039
  try {
1036
1040
  const result = eventInterceptor(event);
1037
- if (result && typeof result === "object" && result.specialState) {
1041
+ if (result?.specialState) {
1038
1042
  setSpecialState(result.specialState);
1039
1043
  }
1040
1044
  return result;
@@ -1169,20 +1173,20 @@ function useCopilotz({
1169
1173
  }, []);
1170
1174
  const fetchAndSetThreadsState = useCallback2(async (uid, preferredExternalId) => {
1171
1175
  try {
1172
- const rawThreads = await fetchThreads(uid, authToken);
1176
+ const rawThreads = await fetchThreads(uid, getRequestHeaders);
1173
1177
  return updateThreadsState(rawThreads, preferredExternalId);
1174
1178
  } catch (error) {
1175
1179
  if (isAbortError(error)) return;
1176
1180
  console.error("Error loading threads", error);
1177
1181
  return null;
1178
1182
  }
1179
- }, [authToken, updateThreadsState]);
1183
+ }, [updateThreadsState, getRequestHeaders]);
1180
1184
  const loadThreadMessages = useCallback2(async (threadId) => {
1181
1185
  const requestId = messagesRequestRef.current + 1;
1182
1186
  messagesRequestRef.current = requestId;
1183
1187
  setIsMessagesLoading(true);
1184
1188
  try {
1185
- const rawMessages = await fetchThreadMessages(threadId, authToken);
1189
+ const rawMessages = await fetchThreadMessages(threadId, getRequestHeaders);
1186
1190
  const resolvedMessages = await resolveAssetsInMessages(rawMessages);
1187
1191
  if (messagesRequestRef.current !== requestId) return;
1188
1192
  resolvedMessages.forEach((msg) => {
@@ -1214,7 +1218,7 @@ function useCopilotz({
1214
1218
  setIsMessagesLoading(false);
1215
1219
  }
1216
1220
  }
1217
- }, [authToken, processToolOutput]);
1221
+ }, [processToolOutput, getRequestHeaders]);
1218
1222
  const handleSelectThread = useCallback2(async (threadId) => {
1219
1223
  setCurrentThreadId(threadId);
1220
1224
  setMessages([]);
@@ -1257,7 +1261,7 @@ function useCopilotz({
1257
1261
  }));
1258
1262
  } else {
1259
1263
  try {
1260
- await updateThread(threadId, { name: trimmedTitle }, authToken);
1264
+ await updateThread(threadId, { name: trimmedTitle }, getRequestHeaders);
1261
1265
  } catch (error) {
1262
1266
  console.error("Failed to rename thread:", error);
1263
1267
  if (userId) {
@@ -1265,7 +1269,7 @@ function useCopilotz({
1265
1269
  }
1266
1270
  }
1267
1271
  }
1268
- }, [authToken, userId, fetchAndSetThreadsState]);
1272
+ }, [userId, fetchAndSetThreadsState, getRequestHeaders]);
1269
1273
  const handleArchiveThread = useCallback2(async (threadId) => {
1270
1274
  const thread = threadsRef.current.find((t) => t.id === threadId);
1271
1275
  if (!thread) return;
@@ -1277,7 +1281,7 @@ function useCopilotz({
1277
1281
  const isPlaceholder = extMap[threadId] === threadId;
1278
1282
  if (!isPlaceholder) {
1279
1283
  try {
1280
- await updateThread(threadId, { status: newArchivedStatus ? "archived" : "active" }, authToken);
1284
+ await updateThread(threadId, { status: newArchivedStatus ? "archived" : "active" }, getRequestHeaders);
1281
1285
  } catch (error) {
1282
1286
  console.error("Failed to archive thread:", error);
1283
1287
  if (userId) {
@@ -1285,7 +1289,7 @@ function useCopilotz({
1285
1289
  }
1286
1290
  }
1287
1291
  }
1288
- }, [authToken, userId, fetchAndSetThreadsState]);
1292
+ }, [userId, fetchAndSetThreadsState, getRequestHeaders]);
1289
1293
  const handleDeleteThread = useCallback2(async (threadId) => {
1290
1294
  const extMap = threadExternalIdMapRef.current;
1291
1295
  const isPlaceholder = extMap[threadId] === threadId;
@@ -1314,7 +1318,7 @@ function useCopilotz({
1314
1318
  }
1315
1319
  if (!isPlaceholder) {
1316
1320
  try {
1317
- await deleteThread(threadId, authToken);
1321
+ await deleteThread(threadId, getRequestHeaders);
1318
1322
  } catch (error) {
1319
1323
  console.error("Failed to delete thread:", error);
1320
1324
  if (userId) {
@@ -1322,7 +1326,7 @@ function useCopilotz({
1322
1326
  }
1323
1327
  }
1324
1328
  }
1325
- }, [authToken, userId, fetchAndSetThreadsState, loadThreadMessages]);
1329
+ }, [userId, fetchAndSetThreadsState, loadThreadMessages, getRequestHeaders]);
1326
1330
  const handleStop = useCallback2(() => {
1327
1331
  abortControllerRef.current?.abort();
1328
1332
  abortControllerRef.current = null;
@@ -1525,7 +1529,6 @@ function useCopilotz({
1525
1529
  };
1526
1530
  const finalMetadata = Object.keys(mergedMetadata).length > 0 ? mergedMetadata : void 0;
1527
1531
  await runCopilotzStream({
1528
- authToken,
1529
1532
  threadId: params.threadId ?? void 0,
1530
1533
  threadExternalId: params.threadExternalId ?? void 0,
1531
1534
  content: requestContent,
@@ -1542,10 +1545,11 @@ function useCopilotz({
1542
1545
  threadMetadata: params.threadMetadata ?? threadMetadata,
1543
1546
  toolCalls: params.toolCalls,
1544
1547
  selectedAgent: params.agentName ?? preferredAgentRef.current ?? null,
1548
+ getRequestHeaders,
1545
1549
  onToken: (token) => updateStreamingMessage(token),
1546
1550
  onMessageEvent: async (event) => {
1547
1551
  const intercepted = applyEventInterceptor(event);
1548
- if (intercepted && typeof intercepted === "object" && intercepted.handled) {
1552
+ if (intercepted?.handled) {
1549
1553
  return;
1550
1554
  }
1551
1555
  const type = event?.type || "";
@@ -1681,7 +1685,7 @@ function useCopilotz({
1681
1685
  },
1682
1686
  onAssetEvent: async (payload) => {
1683
1687
  const intercepted = applyEventInterceptor({ type: "ASSET_CREATED", payload });
1684
- if (intercepted && typeof intercepted === "object" && intercepted.handled) {
1688
+ if (intercepted?.handled) {
1685
1689
  return;
1686
1690
  }
1687
1691
  await (async () => {
@@ -1708,7 +1712,7 @@ function useCopilotz({
1708
1712
  abortControllerRef.current = null;
1709
1713
  }
1710
1714
  return currentAssistantId;
1711
- }, [authToken, applyEventInterceptor, handleStreamMessageEvent, handleStreamAssetEvent]);
1715
+ }, [applyEventInterceptor, handleStreamMessageEvent, handleStreamAssetEvent, getRequestHeaders]);
1712
1716
  const handleSendMessage = useCallback2(async (content, attachments = []) => {
1713
1717
  if (!content.trim() && attachments.length === 0) return;
1714
1718
  if (!userId) return;
@@ -1815,7 +1819,7 @@ function useCopilotz({
1815
1819
  ];
1816
1820
  });
1817
1821
  }
1818
- }, [userId, authToken, fetchAndSetThreadsState, loadThreadMessages, sendCopilotzMessage, getSpecialStateFromError]);
1822
+ }, [userId, fetchAndSetThreadsState, loadThreadMessages, sendCopilotzMessage, getSpecialStateFromError]);
1819
1823
  const bootstrapConversation = useCallback2(async (uid) => {
1820
1824
  if (!bootstrap?.initialToolCalls && !bootstrap?.initialMessage) return;
1821
1825
  const bootstrapThreadExternalId = generateId();
@@ -1858,7 +1862,7 @@ function useCopilotz({
1858
1862
  }
1859
1863
  ]);
1860
1864
  }
1861
- }, [authToken, fetchAndSetThreadsState, loadThreadMessages, sendCopilotzMessage, bootstrap, defaultThreadName, getSpecialStateFromError]);
1865
+ }, [fetchAndSetThreadsState, loadThreadMessages, sendCopilotzMessage, bootstrap, defaultThreadName, getSpecialStateFromError]);
1862
1866
  const reset = useCallback2(() => {
1863
1867
  messagesRequestRef.current += 1;
1864
1868
  setThreads([]);
@@ -1893,7 +1897,7 @@ function useCopilotz({
1893
1897
  initializationRef.current = { userId: null, started: false };
1894
1898
  reset();
1895
1899
  }
1896
- }, [userId, authToken, fetchAndSetThreadsState, loadThreadMessages, bootstrapConversation, reset, bootstrap, isUrlSyncEnabled, urlState.threadId]);
1900
+ }, [userId, fetchAndSetThreadsState, loadThreadMessages, bootstrapConversation, reset, bootstrap, isUrlSyncEnabled, urlState.threadId]);
1897
1901
  useEffect2(() => {
1898
1902
  if (!isUrlSyncEnabled) return;
1899
1903
  if (!initializationRef.current.started) return;
@@ -1942,7 +1946,6 @@ function useCopilotz({
1942
1946
  import { jsx } from "react/jsx-runtime";
1943
1947
  var CopilotzChat = ({
1944
1948
  userId,
1945
- authToken,
1946
1949
  userName,
1947
1950
  userAvatar,
1948
1951
  userEmail,
@@ -1961,6 +1964,7 @@ var CopilotzChat = ({
1961
1964
  agentOptions = [],
1962
1965
  selectedAgentId = null,
1963
1966
  onSelectAgent,
1967
+ getRequestHeaders,
1964
1968
  className,
1965
1969
  eventInterceptor,
1966
1970
  runErrorInterceptor,
@@ -1990,12 +1994,12 @@ var CopilotzChat = ({
1990
1994
  setUrlAgentId
1991
1995
  } = useCopilotz({
1992
1996
  userId,
1993
- authToken,
1994
1997
  initialContext,
1995
1998
  bootstrap,
1996
1999
  defaultThreadName: userConfig?.labels?.defaultThreadName,
1997
2000
  onToolOutput,
1998
2001
  preferredAgentName: selectedAgent?.name ?? null,
2002
+ getRequestHeaders,
1999
2003
  eventInterceptor,
2000
2004
  runErrorInterceptor,
2001
2005
  urlSync