@copilotkit/runtime 1.3.12-fix-tool-call-dynamic-parameters.0 → 1.3.12-lgc-alpha-1.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +3 -4
  2. package/dist/{chunk-SIMJ6TZU.mjs → chunk-6B3NPPSR.mjs} +2 -2
  3. package/dist/{chunk-OSJXQNII.mjs → chunk-6HXQC7IT.mjs} +36 -9
  4. package/dist/chunk-6HXQC7IT.mjs.map +1 -0
  5. package/dist/{chunk-24WEOOFX.mjs → chunk-7MQDBRXJ.mjs} +2 -2
  6. package/dist/{chunk-AOYYOKTP.mjs → chunk-E6ZFCM3B.mjs} +561 -133
  7. package/dist/chunk-E6ZFCM3B.mjs.map +1 -0
  8. package/dist/{chunk-UYORVPCQ.mjs → chunk-TM7ZRU3M.mjs} +2 -2
  9. package/dist/{chunk-ZEHCLFJ2.mjs → chunk-V7SK6QZN.mjs} +6 -9
  10. package/dist/chunk-V7SK6QZN.mjs.map +1 -0
  11. package/dist/{chunk-HKLL7TTP.mjs → chunk-XMDH5MKI.mjs} +2 -2
  12. package/dist/{copilot-runtime-df3527ad.d.ts → copilot-runtime-aba7d4b4.d.ts} +27 -5
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +638 -186
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +13 -9
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/lib/index.d.ts +1 -1
  19. package/dist/lib/index.js +638 -186
  20. package/dist/lib/index.js.map +1 -1
  21. package/dist/lib/index.mjs +13 -9
  22. package/dist/lib/integrations/index.d.ts +2 -2
  23. package/dist/lib/integrations/index.js +5 -4
  24. package/dist/lib/integrations/index.js.map +1 -1
  25. package/dist/lib/integrations/index.mjs +5 -5
  26. package/dist/lib/integrations/nest/index.d.ts +1 -1
  27. package/dist/lib/integrations/nest/index.js +5 -4
  28. package/dist/lib/integrations/nest/index.js.map +1 -1
  29. package/dist/lib/integrations/nest/index.mjs +3 -3
  30. package/dist/lib/integrations/node-express/index.d.ts +1 -1
  31. package/dist/lib/integrations/node-express/index.js +5 -4
  32. package/dist/lib/integrations/node-express/index.js.map +1 -1
  33. package/dist/lib/integrations/node-express/index.mjs +3 -3
  34. package/dist/lib/integrations/node-http/index.d.ts +1 -1
  35. package/dist/lib/integrations/node-http/index.js +5 -4
  36. package/dist/lib/integrations/node-http/index.js.map +1 -1
  37. package/dist/lib/integrations/node-http/index.mjs +2 -2
  38. package/dist/service-adapters/index.js +5 -8
  39. package/dist/service-adapters/index.js.map +1 -1
  40. package/dist/service-adapters/index.mjs +2 -2
  41. package/package.json +7 -6
  42. package/src/agents/langgraph/event-source.ts +22 -67
  43. package/src/lib/runtime/copilot-runtime.ts +58 -11
  44. package/src/lib/runtime/remote-action-constructors.ts +283 -0
  45. package/src/lib/runtime/remote-actions.ts +65 -159
  46. package/src/lib/runtime/remote-lg-cloud-action.ts +441 -0
  47. package/src/service-adapters/events.ts +1 -5
  48. package/src/service-adapters/langchain/utils.ts +5 -10
  49. package/dist/chunk-AOYYOKTP.mjs.map +0 -1
  50. package/dist/chunk-OSJXQNII.mjs.map +0 -1
  51. package/dist/chunk-ZEHCLFJ2.mjs.map +0 -1
  52. package/src/service-adapters/langchain/utils.test.ts +0 -169
  53. /package/dist/{chunk-SIMJ6TZU.mjs.map → chunk-6B3NPPSR.mjs.map} +0 -0
  54. /package/dist/{chunk-24WEOOFX.mjs.map → chunk-7MQDBRXJ.mjs.map} +0 -0
  55. /package/dist/{chunk-UYORVPCQ.mjs.map → chunk-TM7ZRU3M.mjs.map} +0 -0
  56. /package/dist/{chunk-HKLL7TTP.mjs.map → chunk-XMDH5MKI.mjs.map} +0 -0
@@ -15,63 +15,7 @@ interface LangGraphEventWithState {
15
15
  }
16
16
 
17
17
  export class RemoteLangGraphEventSource {
18
- private eventStream$ = new ReplaySubject<LangGraphEvent>();
19
-
20
- async streamResponse(response: Response) {
21
- const reader = response.body!.getReader();
22
- const decoder = new TextDecoder();
23
- let buffer = [];
24
- const eventStream$ = this.eventStream$;
25
-
26
- function flushBuffer() {
27
- const currentBuffer = buffer.join("");
28
- if (currentBuffer.trim().length === 0) {
29
- return;
30
- }
31
- const parts = currentBuffer.split("\n");
32
- if (parts.length === 0) {
33
- return;
34
- }
35
-
36
- const lastPartIsComplete = currentBuffer.endsWith("\n");
37
-
38
- // truncate buffer
39
- buffer = [];
40
-
41
- if (!lastPartIsComplete) {
42
- // put back the last part
43
- buffer.push(parts.pop());
44
- }
45
-
46
- parts
47
- .map((part) => part.trim())
48
- .filter((part) => part != "")
49
- .forEach((part) => {
50
- eventStream$.next(JSON.parse(part));
51
- });
52
- }
53
-
54
- try {
55
- while (true) {
56
- const { done, value } = await reader.read();
57
-
58
- if (!done) {
59
- buffer.push(decoder.decode(value, { stream: true }));
60
- }
61
-
62
- flushBuffer();
63
-
64
- if (done) {
65
- break;
66
- }
67
- }
68
- } catch (error) {
69
- console.error("Error in stream", error);
70
- eventStream$.error(error);
71
- return;
72
- }
73
- eventStream$.complete();
74
- }
18
+ public eventStream$ = new ReplaySubject<LangGraphEvent>();
75
19
 
76
20
  private shouldEmitToolCall(
77
21
  shouldEmitToolCalls: string | string[] | boolean,
@@ -93,7 +37,7 @@ export class RemoteLangGraphEventSource {
93
37
  scan(
94
38
  (acc, event) => {
95
39
  if (event.event === LangGraphEventTypes.OnChatModelStream) {
96
- // @ts-ignore
40
+ // @ts-expect-error -- LangGraph Cloud implementation stores data outside of kwargs
97
41
  const content = event.data?.chunk?.kwargs?.content ?? event.data?.chunk?.content;
98
42
 
99
43
  if (typeof content === "string") {
@@ -104,20 +48,28 @@ export class RemoteLangGraphEventSource {
104
48
  acc.content = null;
105
49
  }
106
50
 
107
- if (event.data?.chunk?.kwargs?.tool_call_chunks) {
51
+ const toolCallChunks =
52
+ // @ts-expect-error -- LangGraph Cloud implementation stores data outside of kwargs
53
+ event.data?.chunk?.kwargs?.tool_call_chunks ?? event.data?.chunk?.tool_call_chunks;
54
+
55
+ const toolCallMessageId =
56
+ event.data?.chunk?.kwargs?.id ??
57
+ (event.data?.chunk?.id as unknown as string | undefined);
58
+
59
+ if (toolCallChunks && toolCallChunks.length > 0) {
108
60
  acc.prevToolCallMessageId = acc.toolCallMessageId;
109
- acc.toolCallMessageId = event.data.chunk.kwargs?.id;
110
- if (event.data.chunk.kwargs.tool_call_chunks[0]?.name) {
111
- acc.toolCallName = event.data.chunk.kwargs.tool_call_chunks[0].name;
61
+ acc.toolCallMessageId = toolCallMessageId;
62
+ if (toolCallChunks[0]?.name) {
63
+ acc.toolCallName = toolCallChunks[0].name;
112
64
  }
113
- if (event.data.chunk.kwargs.tool_call_chunks[0]?.id) {
114
- acc.toolCallId = event.data.chunk.kwargs.tool_call_chunks[0].id;
65
+ if (toolCallChunks[0]?.id) {
66
+ acc.toolCallId = toolCallChunks[0].id;
115
67
  }
116
68
  acc.prevMessageId = acc.messageId;
117
- acc.messageId = event.data?.chunk?.kwargs?.id;
69
+ acc.messageId = toolCallMessageId;
118
70
  } else if (acc.content && acc.content != "") {
119
71
  acc.prevMessageId = acc.messageId;
120
- acc.messageId = event.data?.chunk?.kwargs?.id;
72
+ acc.messageId = toolCallMessageId;
121
73
  } else {
122
74
  acc.prevToolCallMessageId = acc.toolCallMessageId;
123
75
  acc.prevMessageId = acc.messageId;
@@ -266,7 +218,10 @@ export class RemoteLangGraphEventSource {
266
218
  }
267
219
  }
268
220
 
269
- const args = eventWithState.event.data?.chunk?.kwargs?.tool_call_chunks?.[0]?.args;
221
+ const args =
222
+ eventWithState.event.data?.chunk?.kwargs?.tool_call_chunks?.[0]?.args ??
223
+ // @ts-expect-error -- sdf
224
+ eventWithState.event.data?.chunk?.tool_call_chunks?.[0]?.args;
270
225
  const content = eventWithState.content;
271
226
 
272
227
  // Tool call args: emit ActionExecutionArgs
@@ -12,19 +12,22 @@
12
12
  * ```
13
13
  */
14
14
 
15
- import { Action, actionParametersToJsonSchema, Parameter, randomId } from "@copilotkit/shared";
16
- import { RemoteChain, RemoteChainParameters, CopilotServiceAdapter } from "../../service-adapters";
15
+ import { Action, actionParametersToJsonSchema, Parameter } from "@copilotkit/shared";
16
+ import { CopilotServiceAdapter, RemoteChain, RemoteChainParameters } from "../../service-adapters";
17
17
  import { MessageInput } from "../../graphql/inputs/message.input";
18
18
  import { ActionInput } from "../../graphql/inputs/action.input";
19
19
  import { RuntimeEventSource } from "../../service-adapters/events";
20
20
  import { convertGqlInputToMessages } from "../../service-adapters/conversion";
21
- import { AgentStateMessage, Message } from "../../graphql/types/converted";
21
+ import { Message } from "../../graphql/types/converted";
22
22
  import { ForwardedParametersInput } from "../../graphql/inputs/forwarded-parameters.input";
23
23
  import {
24
- setupRemoteActions,
25
- RemoteActionDefinition,
26
- LangGraphAgentAction,
27
24
  isLangGraphAgentAction,
25
+ LangGraphAgentAction,
26
+ EndpointType,
27
+ setupRemoteActions,
28
+ EndpointDefinition,
29
+ CopilotKitEndpoint,
30
+ LangGraphCloudEndpoint,
28
31
  } from "./remote-actions";
29
32
  import { GraphQLContext } from "../integrations/shared";
30
33
  import { AgentSessionInput } from "../../graphql/inputs/agent-session.input";
@@ -121,10 +124,15 @@ export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []
121
124
  */
122
125
  actions?: ActionsConfiguration<T>;
123
126
 
127
+ /*
128
+ * Deprecated: See `remoteEndpoints`.
129
+ */
130
+ remoteActions?: EndpointDefinition[];
131
+
124
132
  /*
125
133
  * A list of remote actions that can be executed.
126
134
  */
127
- remoteActions?: RemoteActionDefinition[];
135
+ remoteEndpoints?: EndpointDefinition[];
128
136
 
129
137
  /*
130
138
  * An array of LangServer URLs.
@@ -134,7 +142,7 @@ export interface CopilotRuntimeConstructorParams<T extends Parameter[] | [] = []
134
142
 
135
143
  export class CopilotRuntime<const T extends Parameter[] | [] = []> {
136
144
  public actions: ActionsConfiguration<T>;
137
- private remoteActionDefinitions: RemoteActionDefinition[];
145
+ private remoteEndpointDefinitions: EndpointDefinition[];
138
146
  private langserve: Promise<Action<any>>[] = [];
139
147
  private onBeforeRequest?: OnBeforeRequestHandler;
140
148
  private onAfterRequest?: OnAfterRequestHandler;
@@ -147,7 +155,7 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
147
155
  this.langserve.push(remoteChain.toAction());
148
156
  }
149
157
 
150
- this.remoteActionDefinitions = params?.remoteActions || [];
158
+ this.remoteEndpointDefinitions = params?.remoteEndpoints || [];
151
159
 
152
160
  this.onBeforeRequest = params?.middleware?.onBeforeRequest;
153
161
  this.onAfterRequest = params?.middleware?.onAfterRequest;
@@ -244,7 +252,7 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
244
252
  request: CopilotRuntimeRequest,
245
253
  ): Promise<CopilotRuntimeResponse> {
246
254
  const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;
247
- const { threadId = randomId(), agentName, nodeName } = agentSession;
255
+ const { threadId, agentName, nodeName } = agentSession;
248
256
  const serverSideActions = await this.getServerSideActions(request);
249
257
 
250
258
  const messages = convertGqlInputToMessages(rawMessages);
@@ -331,8 +339,17 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
331
339
  console.error("Error loading langserve chain:", error);
332
340
  }
333
341
  }
342
+
343
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map(
344
+ (endpoint) =>
345
+ ({
346
+ ...endpoint,
347
+ type: this.resolveEndpointType(endpoint),
348
+ }) as EndpointDefinition,
349
+ );
350
+
334
351
  const remoteActions = await setupRemoteActions({
335
- remoteActionDefinitions: this.remoteActionDefinitions,
352
+ remoteEndpointDefinitions,
336
353
  graphqlContext,
337
354
  messages: inputMessages,
338
355
  agentStates,
@@ -346,6 +363,19 @@ export class CopilotRuntime<const T extends Parameter[] | [] = []> {
346
363
 
347
364
  return [...configuredActions, ...langserveFunctions, ...remoteActions];
348
365
  }
366
+
367
+ private resolveEndpointType(endpoint: EndpointDefinition) {
368
+ if (
369
+ !endpoint.type &&
370
+ "langsmithApiKey" in endpoint &&
371
+ "deploymentUrl" in endpoint &&
372
+ "agents" in endpoint
373
+ ) {
374
+ return EndpointType.LangGraphCloud;
375
+ }
376
+
377
+ return endpoint.type;
378
+ }
349
379
  }
350
380
 
351
381
  export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): ActionInput[] {
@@ -359,3 +389,20 @@ export function flattenToolCallsNoDuplicates(toolsByPriority: ActionInput[]): Ac
359
389
  }
360
390
  return allTools;
361
391
  }
392
+
393
+ // The two functions below are "factory functions", meant to create the action objects that adhere to the expected interfaces
394
+ export function copilotKitEndpoint(config: Omit<CopilotKitEndpoint, "type">): CopilotKitEndpoint {
395
+ return {
396
+ ...config,
397
+ type: EndpointType.CopilotKit,
398
+ };
399
+ }
400
+
401
+ export function langGraphCloudEndpoint(
402
+ config: Omit<LangGraphCloudEndpoint, "type">,
403
+ ): LangGraphCloudEndpoint {
404
+ return {
405
+ ...config,
406
+ type: EndpointType.LangGraphCloud,
407
+ };
408
+ }
@@ -0,0 +1,283 @@
1
+ import {
2
+ CopilotKitEndpoint,
3
+ LangGraphAgentHandlerParams,
4
+ RemoteActionInfoResponse,
5
+ LangGraphCloudEndpoint,
6
+ } from "./remote-actions";
7
+ import { GraphQLContext } from "../integrations";
8
+ import { Logger } from "pino";
9
+ import { Message } from "../../graphql/types/converted";
10
+ import { AgentStateInput } from "../../graphql/inputs/agent-state.input";
11
+ import { Observable, ReplaySubject } from "rxjs";
12
+ import { RuntimeEvent } from "../../service-adapters/events";
13
+ import telemetry from "../telemetry-client";
14
+ import { RemoteLangGraphEventSource } from "../../agents/langgraph/event-source";
15
+ import { Action } from "@copilotkit/shared";
16
+ import { LangGraphEvent } from "../../agents/langgraph/events";
17
+ import { execute } from "./remote-lg-cloud-action";
18
+
19
+ export function constructLGCRemoteAction({
20
+ endpoint,
21
+ graphqlContext,
22
+ logger,
23
+ messages,
24
+ agentStates,
25
+ }: {
26
+ endpoint: LangGraphCloudEndpoint;
27
+ graphqlContext: GraphQLContext;
28
+ logger: Logger;
29
+ messages: Message[];
30
+ agentStates?: AgentStateInput[];
31
+ }) {
32
+ const agents = endpoint.agents.map((agent) => ({
33
+ name: agent.name,
34
+ description: agent.description,
35
+ parameters: [],
36
+ handler: async (_args: any) => {},
37
+ langGraphAgentHandler: async ({
38
+ name,
39
+ actionInputsWithoutAgents,
40
+ threadId,
41
+ nodeName,
42
+ }: LangGraphAgentHandlerParams): Promise<Observable<RuntimeEvent>> => {
43
+ logger.debug({ actionName: agent.name }, "Executing LangGraph Cloud agent");
44
+
45
+ telemetry.capture("oss.runtime.remote_action_executed", {});
46
+
47
+ let state = {};
48
+ if (agentStates) {
49
+ const jsonState = agentStates.find((state) => state.agentName === name)?.state;
50
+ if (jsonState) {
51
+ state = JSON.parse(jsonState);
52
+ }
53
+ }
54
+
55
+ try {
56
+ const response = await execute({
57
+ deploymentUrl: endpoint.deploymentUrl,
58
+ langsmithApiKey: endpoint.langsmithApiKey,
59
+ agent,
60
+ threadId,
61
+ nodeName,
62
+ messages,
63
+ state,
64
+ properties: graphqlContext.properties,
65
+ actions: actionInputsWithoutAgents.map((action) => ({
66
+ name: action.name,
67
+ description: action.description,
68
+ parameters: JSON.parse(action.jsonSchema) as string,
69
+ })),
70
+ });
71
+
72
+ const eventSource = new RemoteLangGraphEventSource();
73
+ streamResponse(response, eventSource.eventStream$);
74
+ return eventSource.processLangGraphEvents();
75
+ } catch (error) {
76
+ logger.error(
77
+ { url: endpoint.deploymentUrl, status: 500, body: error.message },
78
+ "Failed to execute LangGraph Cloud agent",
79
+ );
80
+ throw new Error("Failed to execute LangGraph Cloud agent");
81
+ }
82
+ },
83
+ }));
84
+
85
+ return [...agents];
86
+ }
87
+
88
+ export function constructRemoteActions({
89
+ json,
90
+ url,
91
+ onBeforeRequest,
92
+ graphqlContext,
93
+ logger,
94
+ messages,
95
+ agentStates,
96
+ }: {
97
+ json: RemoteActionInfoResponse;
98
+ url: string;
99
+ onBeforeRequest?: CopilotKitEndpoint["onBeforeRequest"];
100
+ graphqlContext: GraphQLContext;
101
+ logger: Logger;
102
+ messages: Message[];
103
+ agentStates?: AgentStateInput[];
104
+ }): Action<any>[] {
105
+ const actions = json["actions"].map((action) => ({
106
+ name: action.name,
107
+ description: action.description,
108
+ parameters: action.parameters,
109
+ handler: async (args: any) => {
110
+ logger.debug({ actionName: action.name, args }, "Executing remote action");
111
+
112
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
113
+ telemetry.capture("oss.runtime.remote_action_executed", {});
114
+
115
+ try {
116
+ const response = await fetch(`${url}/actions/execute`, {
117
+ method: "POST",
118
+ headers,
119
+ body: JSON.stringify({
120
+ name: action.name,
121
+ arguments: args,
122
+ properties: graphqlContext.properties,
123
+ }),
124
+ });
125
+
126
+ if (!response.ok) {
127
+ logger.error(
128
+ { url, status: response.status, body: await response.text() },
129
+ "Failed to execute remote action",
130
+ );
131
+ return "Failed to execute remote action";
132
+ }
133
+
134
+ const requestResult = await response.json();
135
+
136
+ const result = requestResult["result"];
137
+ logger.debug({ actionName: action.name, result }, "Executed remote action");
138
+ return result;
139
+ } catch (error) {
140
+ logger.error(
141
+ { error: error.message ? error.message : error + "" },
142
+ "Failed to execute remote action",
143
+ );
144
+ return "Failed to execute remote action";
145
+ }
146
+ },
147
+ }));
148
+
149
+ const agents = json["agents"].map((agent) => ({
150
+ name: agent.name,
151
+ description: agent.description,
152
+ parameters: [],
153
+ handler: async (_args: any) => {},
154
+
155
+ langGraphAgentHandler: async ({
156
+ name,
157
+ actionInputsWithoutAgents,
158
+ threadId,
159
+ nodeName,
160
+ }: LangGraphAgentHandlerParams): Promise<Observable<RuntimeEvent>> => {
161
+ logger.debug({ actionName: agent.name }, "Executing remote agent");
162
+
163
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
164
+ telemetry.capture("oss.runtime.remote_action_executed", {});
165
+
166
+ let state = {};
167
+ if (agentStates) {
168
+ const jsonState = agentStates.find((state) => state.agentName === name)?.state;
169
+ if (jsonState) {
170
+ state = JSON.parse(jsonState);
171
+ }
172
+ }
173
+
174
+ const response = await fetch(`${url}/agents/execute`, {
175
+ method: "POST",
176
+ headers,
177
+ body: JSON.stringify({
178
+ name,
179
+ threadId,
180
+ nodeName,
181
+ messages,
182
+ state,
183
+ properties: graphqlContext.properties,
184
+ actions: actionInputsWithoutAgents.map((action) => ({
185
+ name: action.name,
186
+ description: action.description,
187
+ parameters: JSON.parse(action.jsonSchema),
188
+ })),
189
+ }),
190
+ });
191
+
192
+ if (!response.ok) {
193
+ logger.error(
194
+ { url, status: response.status, body: await response.text() },
195
+ "Failed to execute remote agent",
196
+ );
197
+ throw new Error("Failed to execute remote agent");
198
+ }
199
+
200
+ const eventSource = new RemoteLangGraphEventSource();
201
+ streamResponse(response.body!, eventSource.eventStream$);
202
+ return eventSource.processLangGraphEvents();
203
+ },
204
+ }));
205
+
206
+ return [...actions, ...agents];
207
+ }
208
+
209
+ async function streamResponse(
210
+ response: ReadableStream<Uint8Array>,
211
+ eventStream$: ReplaySubject<LangGraphEvent>,
212
+ ) {
213
+ const reader = response.getReader();
214
+ const decoder = new TextDecoder();
215
+ let buffer = [];
216
+
217
+ function flushBuffer() {
218
+ const currentBuffer = buffer.join("");
219
+ if (currentBuffer.trim().length === 0) {
220
+ return;
221
+ }
222
+ const parts = currentBuffer.split("\n");
223
+ if (parts.length === 0) {
224
+ return;
225
+ }
226
+
227
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
228
+
229
+ // truncate buffer
230
+ buffer = [];
231
+
232
+ if (!lastPartIsComplete) {
233
+ // put back the last part
234
+ buffer.push(parts.pop());
235
+ }
236
+
237
+ parts
238
+ .map((part) => part.trim())
239
+ .filter((part) => part != "")
240
+ .forEach((part) => {
241
+ eventStream$.next(JSON.parse(part));
242
+ });
243
+ }
244
+
245
+ try {
246
+ while (true) {
247
+ const { done, value } = await reader.read();
248
+
249
+ if (!done) {
250
+ buffer.push(decoder.decode(value, { stream: true }));
251
+ }
252
+
253
+ flushBuffer();
254
+
255
+ if (done) {
256
+ break;
257
+ }
258
+ }
259
+ } catch (error) {
260
+ console.error("Error in stream", error);
261
+ eventStream$.error(error);
262
+ return;
263
+ }
264
+ eventStream$.complete();
265
+ }
266
+
267
+ export function createHeaders(
268
+ onBeforeRequest: CopilotKitEndpoint["onBeforeRequest"],
269
+ graphqlContext: GraphQLContext,
270
+ ) {
271
+ const headers = {
272
+ "Content-Type": "application/json",
273
+ };
274
+
275
+ if (onBeforeRequest) {
276
+ const { headers: additionalHeaders } = onBeforeRequest({ ctx: graphqlContext });
277
+ if (additionalHeaders) {
278
+ Object.assign(headers, additionalHeaders);
279
+ }
280
+ }
281
+
282
+ return headers;
283
+ }