@copilotkit/runtime 1.10.7-next.0 → 1.50.0-beta.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 (134) hide show
  1. package/CHANGELOG.md +0 -6
  2. package/dist/index.d.ts +1655 -27
  3. package/dist/index.js +2172 -5049
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +5441 -99
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/v2/index.d.ts +1 -0
  8. package/dist/v2/index.js +15 -0
  9. package/dist/v2/index.js.map +1 -0
  10. package/dist/v2/index.mjs +4 -0
  11. package/dist/v2/index.mjs.map +1 -0
  12. package/package.json +33 -21
  13. package/src/graphql/message-conversion/agui-to-gql.test.ts +1263 -0
  14. package/src/graphql/message-conversion/agui-to-gql.ts +333 -0
  15. package/src/graphql/message-conversion/gql-to-agui.test.ts +1578 -0
  16. package/src/graphql/message-conversion/gql-to-agui.ts +278 -0
  17. package/src/graphql/message-conversion/index.ts +2 -0
  18. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +526 -0
  19. package/src/graphql/resolvers/copilot.resolver.ts +3 -48
  20. package/src/graphql/resolvers/state.resolver.ts +3 -2
  21. package/src/graphql/types/converted/index.ts +32 -6
  22. package/src/graphql/types/enums.ts +2 -2
  23. package/src/graphql/types/message-status.type.ts +3 -1
  24. package/src/lib/index.ts +1 -1
  25. package/src/lib/integrations/nextjs/app-router.ts +10 -11
  26. package/src/lib/integrations/nextjs/pages-router.ts +4 -11
  27. package/src/lib/integrations/node-http/index.ts +64 -5
  28. package/src/lib/integrations/shared.ts +1 -1
  29. package/src/lib/observability.ts +87 -0
  30. package/src/lib/runtime/{langgraph/langgraph-agent.ts → agent-integrations/langgraph.agent.ts} +5 -0
  31. package/src/lib/runtime/copilot-runtime.ts +346 -1333
  32. package/src/lib/runtime/types.ts +49 -0
  33. package/src/lib/runtime/utils.ts +87 -0
  34. package/src/lib/telemetry-client.ts +6 -5
  35. package/src/service-adapters/anthropic/anthropic-adapter.ts +5 -1
  36. package/src/service-adapters/bedrock/bedrock-adapter.ts +6 -1
  37. package/src/service-adapters/empty/empty-adapter.ts +3 -0
  38. package/src/service-adapters/events.ts +0 -254
  39. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +5 -1
  40. package/src/service-adapters/google/google-genai-adapter.ts +7 -1
  41. package/src/service-adapters/groq/groq-adapter.ts +5 -1
  42. package/src/service-adapters/langchain/langchain-adapter.ts +3 -0
  43. package/src/service-adapters/openai/openai-adapter.ts +5 -1
  44. package/src/service-adapters/openai/openai-assistant-adapter.ts +4 -0
  45. package/src/service-adapters/service-adapter.ts +3 -0
  46. package/src/service-adapters/unify/unify-adapter.ts +6 -1
  47. package/src/v2/index.ts +2 -0
  48. package/tsup.config.ts +2 -1
  49. package/dist/chunk-27JKTS6P.mjs +0 -1704
  50. package/dist/chunk-27JKTS6P.mjs.map +0 -1
  51. package/dist/chunk-2OZAGFV3.mjs +0 -43
  52. package/dist/chunk-2OZAGFV3.mjs.map +0 -1
  53. package/dist/chunk-5BW5IBTZ.mjs +0 -80
  54. package/dist/chunk-5BW5IBTZ.mjs.map +0 -1
  55. package/dist/chunk-AMUJQ6IR.mjs +0 -50
  56. package/dist/chunk-AMUJQ6IR.mjs.map +0 -1
  57. package/dist/chunk-BMIYSM5W.mjs +0 -25
  58. package/dist/chunk-BMIYSM5W.mjs.map +0 -1
  59. package/dist/chunk-FDTCG47E.mjs +0 -25
  60. package/dist/chunk-FDTCG47E.mjs.map +0 -1
  61. package/dist/chunk-FHD4JECV.mjs +0 -33
  62. package/dist/chunk-FHD4JECV.mjs.map +0 -1
  63. package/dist/chunk-LRCKLBMO.mjs +0 -6020
  64. package/dist/chunk-LRCKLBMO.mjs.map +0 -1
  65. package/dist/chunk-R7RMYEPZ.mjs +0 -175
  66. package/dist/chunk-R7RMYEPZ.mjs.map +0 -1
  67. package/dist/chunk-SHBDMA63.mjs +0 -141
  68. package/dist/chunk-SHBDMA63.mjs.map +0 -1
  69. package/dist/chunk-XWBDEXDA.mjs +0 -153
  70. package/dist/chunk-XWBDEXDA.mjs.map +0 -1
  71. package/dist/graphql/types/base/index.d.ts +0 -6
  72. package/dist/graphql/types/base/index.js +0 -63
  73. package/dist/graphql/types/base/index.js.map +0 -1
  74. package/dist/graphql/types/base/index.mjs +0 -8
  75. package/dist/graphql/types/base/index.mjs.map +0 -1
  76. package/dist/graphql/types/converted/index.d.ts +0 -2
  77. package/dist/graphql/types/converted/index.js +0 -200
  78. package/dist/graphql/types/converted/index.js.map +0 -1
  79. package/dist/graphql/types/converted/index.mjs +0 -19
  80. package/dist/graphql/types/converted/index.mjs.map +0 -1
  81. package/dist/groq-adapter-c8aec5c5.d.ts +0 -321
  82. package/dist/index-96b330da.d.ts +0 -119
  83. package/dist/langserve-0c6100e3.d.ts +0 -257
  84. package/dist/lib/cloud/index.d.ts +0 -6
  85. package/dist/lib/cloud/index.js +0 -18
  86. package/dist/lib/cloud/index.js.map +0 -1
  87. package/dist/lib/cloud/index.mjs +0 -1
  88. package/dist/lib/cloud/index.mjs.map +0 -1
  89. package/dist/lib/index.d.ts +0 -212
  90. package/dist/lib/index.js +0 -7843
  91. package/dist/lib/index.js.map +0 -1
  92. package/dist/lib/index.mjs +0 -76
  93. package/dist/lib/index.mjs.map +0 -1
  94. package/dist/lib/integrations/index.d.ts +0 -34
  95. package/dist/lib/integrations/index.js +0 -3052
  96. package/dist/lib/integrations/index.js.map +0 -1
  97. package/dist/lib/integrations/index.mjs +0 -37
  98. package/dist/lib/integrations/index.mjs.map +0 -1
  99. package/dist/lib/integrations/nest/index.d.ts +0 -15
  100. package/dist/lib/integrations/nest/index.js +0 -2959
  101. package/dist/lib/integrations/nest/index.js.map +0 -1
  102. package/dist/lib/integrations/nest/index.mjs +0 -14
  103. package/dist/lib/integrations/nest/index.mjs.map +0 -1
  104. package/dist/lib/integrations/node-express/index.d.ts +0 -15
  105. package/dist/lib/integrations/node-express/index.js +0 -2959
  106. package/dist/lib/integrations/node-express/index.js.map +0 -1
  107. package/dist/lib/integrations/node-express/index.mjs +0 -14
  108. package/dist/lib/integrations/node-express/index.mjs.map +0 -1
  109. package/dist/lib/integrations/node-http/index.d.ts +0 -15
  110. package/dist/lib/integrations/node-http/index.js +0 -2945
  111. package/dist/lib/integrations/node-http/index.js.map +0 -1
  112. package/dist/lib/integrations/node-http/index.mjs +0 -13
  113. package/dist/lib/integrations/node-http/index.mjs.map +0 -1
  114. package/dist/service-adapters/index.d.ts +0 -162
  115. package/dist/service-adapters/index.js +0 -1787
  116. package/dist/service-adapters/index.js.map +0 -1
  117. package/dist/service-adapters/index.mjs +0 -34
  118. package/dist/service-adapters/index.mjs.map +0 -1
  119. package/dist/service-adapters/shared/index.d.ts +0 -9
  120. package/dist/service-adapters/shared/index.js +0 -72
  121. package/dist/service-adapters/shared/index.js.map +0 -1
  122. package/dist/service-adapters/shared/index.mjs +0 -8
  123. package/dist/service-adapters/shared/index.mjs.map +0 -1
  124. package/dist/shared-0a7346ce.d.ts +0 -466
  125. package/dist/utils/index.d.ts +0 -65
  126. package/dist/utils/index.js +0 -175
  127. package/dist/utils/index.js.map +0 -1
  128. package/dist/utils/index.mjs +0 -12
  129. package/dist/utils/index.mjs.map +0 -1
  130. package/src/lib/runtime/__tests__/remote-action-constructors.test.ts +0 -246
  131. package/src/lib/runtime/agui-action.ts +0 -180
  132. package/src/lib/runtime/remote-action-constructors.ts +0 -331
  133. package/src/lib/runtime/remote-actions.ts +0 -217
  134. package/src/lib/runtime/remote-lg-action.ts +0 -1006
@@ -1,331 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import {
3
- CopilotKitEndpoint,
4
- RemoteAgentHandlerParams,
5
- RemoteActionInfoResponse,
6
- LangGraphPlatformEndpoint,
7
- } from "./remote-actions";
8
- import { GraphQLContext } from "../integrations";
9
- import { Logger } from "pino";
10
- import { Message } from "../../graphql/types/converted";
11
- import { AgentStateInput } from "../../graphql/inputs/agent-state.input";
12
- import { Observable } from "rxjs";
13
- import { RuntimeEvent, RuntimeEventSubject } from "../../service-adapters/events";
14
- import telemetry from "../telemetry-client";
15
- import { RemoteLangGraphEventSource } from "../../agents/langgraph/event-source";
16
- import { Action } from "@copilotkit/shared";
17
- import { execute } from "./remote-lg-action";
18
- import { CopilotKitError, CopilotKitLowLevelError } from "@copilotkit/shared";
19
- import { writeJsonLineResponseToEventStream } from "../streaming";
20
- import { CopilotKitApiDiscoveryError, ResolvedCopilotKitError } from "@copilotkit/shared";
21
- import { parseJson, tryMap } from "@copilotkit/shared";
22
- import { ActionInput } from "../../graphql/inputs/action.input";
23
- import { fetchWithRetry } from "./retry-utils";
24
-
25
- // Import the utility function from remote-lg-action
26
- import { isUserConfigurationError } from "./remote-lg-action";
27
-
28
- export function constructLGCRemoteAction({
29
- endpoint,
30
- graphqlContext,
31
- logger,
32
- messages,
33
- agentStates,
34
- }: {
35
- endpoint: LangGraphPlatformEndpoint;
36
- graphqlContext: GraphQLContext;
37
- logger: Logger;
38
- messages: Message[];
39
- agentStates?: AgentStateInput[];
40
- }) {
41
- const agents = endpoint.agents.map((agent) => ({
42
- name: agent.name,
43
- description: agent.description,
44
- parameters: [],
45
- handler: async (_args: any) => {},
46
- remoteAgentHandler: async ({
47
- name,
48
- actionInputsWithoutAgents,
49
- threadId,
50
- nodeName,
51
- additionalMessages = [],
52
- metaEvents,
53
- }: RemoteAgentHandlerParams): Promise<Observable<RuntimeEvent>> => {
54
- logger.debug({ actionName: agent.name }, "Executing LangGraph Platform agent");
55
-
56
- telemetry.capture("oss.runtime.remote_action_executed", {
57
- agentExecution: true,
58
- type: "langgraph-platform",
59
- agentsAmount: endpoint.agents.length,
60
- hashedLgcKey: endpoint.langsmithApiKey
61
- ? createHash("sha256").update(endpoint.langsmithApiKey).digest("hex")
62
- : null,
63
- });
64
-
65
- let state = {};
66
- let config = {};
67
- if (agentStates) {
68
- const jsonState = agentStates.find((state) => state.agentName === name);
69
- if (jsonState) {
70
- state = parseJson(jsonState.state, {});
71
- config = parseJson(jsonState.config, {});
72
- }
73
- }
74
-
75
- try {
76
- const response = await execute({
77
- logger: logger.child({ component: "remote-actions.remote-lg-action.streamEvents" }),
78
- deploymentUrl: endpoint.deploymentUrl,
79
- langsmithApiKey: endpoint.langsmithApiKey,
80
- agent,
81
- threadId,
82
- nodeName,
83
- messages: [...messages, ...additionalMessages],
84
- state,
85
- config,
86
- properties: graphqlContext.properties,
87
- actions: tryMap(actionInputsWithoutAgents, (action: ActionInput) => ({
88
- name: action.name,
89
- description: action.description,
90
- parameters: JSON.parse(action.jsonSchema),
91
- })),
92
- metaEvents,
93
- });
94
-
95
- const eventSource = new RemoteLangGraphEventSource();
96
- writeJsonLineResponseToEventStream(response, eventSource.eventStream$);
97
- return eventSource.processLangGraphEvents();
98
- } catch (error) {
99
- // Preserve structured CopilotKit errors with semantic information
100
- if (error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError) {
101
- // Distinguish between user errors and system errors for logging
102
- if (isUserConfigurationError(error)) {
103
- logger.debug(
104
- { url: endpoint.deploymentUrl, error: error.message, code: error.code },
105
- "User configuration error in LangGraph Platform agent",
106
- );
107
- } else {
108
- logger.error(
109
- { url: endpoint.deploymentUrl, error: error.message, type: error.constructor.name },
110
- "LangGraph Platform agent error",
111
- );
112
- }
113
- throw error; // Re-throw the structured error to preserve semantic information
114
- }
115
-
116
- // For other errors, log and wrap them
117
- logger.error(
118
- { url: endpoint.deploymentUrl, status: 500, body: error.message },
119
- "Failed to execute LangGraph Platform agent",
120
- );
121
- throw new CopilotKitLowLevelError({
122
- error: error instanceof Error ? error : new Error(String(error)),
123
- url: endpoint.deploymentUrl,
124
- message: "Failed to execute LangGraph Platform agent",
125
- });
126
- }
127
- },
128
- }));
129
-
130
- return [...agents];
131
- }
132
-
133
- export enum RemoteAgentType {
134
- LangGraph = "langgraph",
135
- CrewAI = "crewai",
136
- }
137
-
138
- export function constructRemoteActions({
139
- json,
140
- url,
141
- onBeforeRequest,
142
- graphqlContext,
143
- logger,
144
- messages,
145
- agentStates,
146
- }: {
147
- json: RemoteActionInfoResponse;
148
- url: string;
149
- onBeforeRequest?: CopilotKitEndpoint["onBeforeRequest"];
150
- graphqlContext: GraphQLContext;
151
- logger: Logger;
152
- messages: Message[];
153
- agentStates?: AgentStateInput[];
154
- }): Action<any>[] {
155
- const totalAgents = Array.isArray(json["agents"]) ? json["agents"].length : 0;
156
-
157
- const actions = json["actions"].map((action) => ({
158
- name: action.name,
159
- description: action.description,
160
- parameters: action.parameters,
161
- handler: async (args: any) => {
162
- logger.debug({ actionName: action.name, args }, "Executing remote action");
163
-
164
- const headers = createHeaders(onBeforeRequest, graphqlContext);
165
- telemetry.capture("oss.runtime.remote_action_executed", {
166
- agentExecution: false,
167
- type: "self-hosted",
168
- agentsAmount: totalAgents,
169
- });
170
-
171
- const fetchUrl = `${url}/actions/execute`;
172
- try {
173
- const response = await fetchWithRetry(
174
- fetchUrl,
175
- {
176
- method: "POST",
177
- headers,
178
- body: JSON.stringify({
179
- name: action.name,
180
- arguments: args,
181
- properties: graphqlContext.properties,
182
- }),
183
- },
184
- logger,
185
- );
186
-
187
- if (!response.ok) {
188
- logger.error(
189
- { url, status: response.status, body: await response.text() },
190
- "Failed to execute remote action",
191
- );
192
- if (response.status === 404) {
193
- throw new CopilotKitApiDiscoveryError({ url: fetchUrl });
194
- }
195
- throw new ResolvedCopilotKitError({
196
- status: response.status,
197
- url: fetchUrl,
198
- isRemoteEndpoint: true,
199
- });
200
- }
201
-
202
- const requestResult = await response.json();
203
-
204
- const result = requestResult["result"];
205
- logger.debug({ actionName: action.name, result }, "Executed remote action");
206
- return result;
207
- } catch (error) {
208
- if (error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError) {
209
- throw error;
210
- }
211
- throw new CopilotKitLowLevelError({ error, url: fetchUrl });
212
- }
213
- },
214
- }));
215
-
216
- const agents = totalAgents
217
- ? json["agents"].map((agent) => ({
218
- name: agent.name,
219
- description: agent.description,
220
- parameters: [],
221
- handler: async (_args: any) => {},
222
-
223
- remoteAgentHandler: async ({
224
- name,
225
- actionInputsWithoutAgents,
226
- threadId,
227
- nodeName,
228
- additionalMessages = [],
229
- metaEvents,
230
- }: RemoteAgentHandlerParams): Promise<Observable<RuntimeEvent>> => {
231
- logger.debug({ actionName: agent.name }, "Executing remote agent");
232
-
233
- const headers = createHeaders(onBeforeRequest, graphqlContext);
234
- telemetry.capture("oss.runtime.remote_action_executed", {
235
- agentExecution: true,
236
- type: "self-hosted",
237
- agentsAmount: json["agents"].length,
238
- });
239
-
240
- let state = {};
241
- let config = {};
242
- if (agentStates) {
243
- const jsonState = agentStates.find((state) => state.agentName === name);
244
- if (jsonState) {
245
- state = parseJson(jsonState.state, {});
246
- config = parseJson(jsonState.config, {});
247
- }
248
- }
249
-
250
- const fetchUrl = `${url}/agents/execute`;
251
- try {
252
- const response = await fetchWithRetry(
253
- fetchUrl,
254
- {
255
- method: "POST",
256
- headers,
257
- body: JSON.stringify({
258
- name,
259
- threadId,
260
- nodeName,
261
- messages: [...messages, ...additionalMessages],
262
- state,
263
- config,
264
- properties: graphqlContext.properties,
265
- actions: tryMap(actionInputsWithoutAgents, (action: ActionInput) => ({
266
- name: action.name,
267
- description: action.description,
268
- parameters: JSON.parse(action.jsonSchema),
269
- })),
270
- metaEvents,
271
- }),
272
- },
273
- logger,
274
- );
275
-
276
- if (!response.ok) {
277
- logger.error(
278
- { url, status: response.status, body: await response.text() },
279
- "Failed to execute remote agent",
280
- );
281
- if (response.status === 404) {
282
- throw new CopilotKitApiDiscoveryError({ url: fetchUrl });
283
- }
284
- throw new ResolvedCopilotKitError({
285
- status: response.status,
286
- url: fetchUrl,
287
- isRemoteEndpoint: true,
288
- });
289
- }
290
-
291
- if (agent.type === RemoteAgentType.LangGraph) {
292
- const eventSource = new RemoteLangGraphEventSource();
293
- writeJsonLineResponseToEventStream(response.body!, eventSource.eventStream$);
294
- return eventSource.processLangGraphEvents();
295
- } else if (agent.type === RemoteAgentType.CrewAI) {
296
- const eventStream$ = new RuntimeEventSubject();
297
- writeJsonLineResponseToEventStream(response.body!, eventStream$);
298
- return eventStream$;
299
- } else {
300
- throw new Error("Unsupported agent type");
301
- }
302
- } catch (error) {
303
- if (error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError) {
304
- throw error;
305
- }
306
- throw new CopilotKitLowLevelError({ error, url: fetchUrl });
307
- }
308
- },
309
- }))
310
- : [];
311
-
312
- return [...actions, ...agents];
313
- }
314
-
315
- export function createHeaders(
316
- onBeforeRequest: CopilotKitEndpoint["onBeforeRequest"],
317
- graphqlContext: GraphQLContext,
318
- ) {
319
- const headers = {
320
- "Content-Type": "application/json",
321
- };
322
-
323
- if (onBeforeRequest) {
324
- const { headers: additionalHeaders } = onBeforeRequest({ ctx: graphqlContext });
325
- if (additionalHeaders) {
326
- Object.assign(headers, additionalHeaders);
327
- }
328
- }
329
-
330
- return headers;
331
- }
@@ -1,217 +0,0 @@
1
- import { Action, CopilotKitErrorCode } from "@copilotkit/shared";
2
- import { GraphQLContext } from "../integrations/shared";
3
- import { Logger } from "pino";
4
- import { Message } from "../../graphql/types/converted";
5
- import { ActionInput } from "../../graphql/inputs/action.input";
6
- import { AgentStateInput } from "../../graphql/inputs/agent-state.input";
7
- import {
8
- constructLGCRemoteAction,
9
- constructRemoteActions,
10
- createHeaders,
11
- } from "./remote-action-constructors";
12
- import {
13
- CopilotKitLowLevelError,
14
- ResolvedCopilotKitError,
15
- CopilotKitError,
16
- } from "@copilotkit/shared";
17
- import { MetaEventInput } from "../../graphql/inputs/meta-event.input";
18
- import { AbstractAgent } from "@ag-ui/client";
19
- import { constructAGUIRemoteAction, RemoteAgentAction } from "./agui-action";
20
- import { CopilotContextInput } from "../../graphql/inputs/copilot-context.input";
21
-
22
- export type EndpointDefinition = CopilotKitEndpoint | LangGraphPlatformEndpoint;
23
-
24
- export enum EndpointType {
25
- CopilotKit = "copilotKit",
26
- LangGraphPlatform = "langgraph-platform",
27
- }
28
-
29
- export interface BaseEndpointDefinition<TActionType extends EndpointType> {
30
- type?: TActionType;
31
- }
32
-
33
- export interface CopilotKitEndpoint extends BaseEndpointDefinition<EndpointType.CopilotKit> {
34
- url: string;
35
- onBeforeRequest?: ({ ctx }: { ctx: GraphQLContext }) => {
36
- headers?: Record<string, string> | undefined;
37
- };
38
- }
39
-
40
- export interface LangGraphPlatformAgent {
41
- name: string;
42
- description: string;
43
- assistantId?: string;
44
- }
45
-
46
- export interface LangGraphPlatformEndpoint
47
- extends BaseEndpointDefinition<EndpointType.LangGraphPlatform> {
48
- deploymentUrl: string;
49
- langsmithApiKey?: string | null;
50
- agents: LangGraphPlatformAgent[];
51
- }
52
-
53
- export type RemoteActionInfoResponse = {
54
- actions: any[];
55
- agents: any[];
56
- };
57
-
58
- export type RemoteAgentHandlerParams = {
59
- name: string;
60
- actionInputsWithoutAgents: ActionInput[];
61
- threadId?: string;
62
- nodeName?: string;
63
- additionalMessages?: Message[];
64
- metaEvents?: MetaEventInput[];
65
- };
66
-
67
- export function isRemoteAgentAction(action: Action<any>): action is RemoteAgentAction {
68
- if (!action) {
69
- return false;
70
- }
71
- return typeof (action as RemoteAgentAction).remoteAgentHandler === "function";
72
- }
73
-
74
- async function fetchRemoteInfo({
75
- url,
76
- onBeforeRequest,
77
- graphqlContext,
78
- logger,
79
- frontendUrl,
80
- }: {
81
- url: string;
82
- onBeforeRequest?: CopilotKitEndpoint["onBeforeRequest"];
83
- graphqlContext: GraphQLContext;
84
- logger: Logger;
85
- frontendUrl?: string;
86
- }): Promise<RemoteActionInfoResponse> {
87
- logger.debug({ url }, "Fetching actions from url");
88
- const headers = createHeaders(onBeforeRequest, graphqlContext);
89
-
90
- const fetchUrl = `${url}/info`;
91
- try {
92
- const response = await fetch(fetchUrl, {
93
- method: "POST",
94
- headers,
95
- body: JSON.stringify({ properties: graphqlContext.properties, frontendUrl }),
96
- });
97
-
98
- if (!response.ok) {
99
- logger.error(
100
- { url, status: response.status, body: await response.text() },
101
- "Failed to fetch actions from url",
102
- );
103
- throw new ResolvedCopilotKitError({
104
- status: response.status,
105
- url: fetchUrl,
106
- isRemoteEndpoint: true,
107
- });
108
- }
109
-
110
- const json = await response.json();
111
- logger.debug({ json }, "Fetched actions from url");
112
- return json;
113
- } catch (error) {
114
- if (error instanceof CopilotKitError) {
115
- throw error;
116
- }
117
- throw new CopilotKitLowLevelError({ error, url: fetchUrl });
118
- }
119
- }
120
-
121
- export async function setupRemoteActions({
122
- remoteEndpointDefinitions,
123
- graphqlContext,
124
- messages,
125
- agentStates,
126
- frontendUrl,
127
- agents,
128
- metaEvents,
129
- nodeName,
130
- context,
131
- }: {
132
- remoteEndpointDefinitions: EndpointDefinition[];
133
- graphqlContext: GraphQLContext;
134
- messages: Message[];
135
- agentStates?: AgentStateInput[];
136
- frontendUrl?: string;
137
- agents: Record<string, AbstractAgent>;
138
- metaEvents?: MetaEventInput[];
139
- nodeName?: string;
140
- context?: CopilotContextInput[];
141
- }): Promise<Action<any>[]> {
142
- const logger = graphqlContext.logger.child({ component: "remote-actions.fetchRemoteActions" });
143
- logger.debug({ remoteEndpointDefinitions }, "Fetching from remote endpoints");
144
-
145
- const threadMetadata = (graphqlContext.properties?.threadMetadata as Record<string, any>) || {};
146
-
147
- // Remove duplicates of remoteEndpointDefinitions.url
148
- const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
149
- if (value.type === EndpointType.LangGraphPlatform) {
150
- return value;
151
- }
152
- return index === self.findIndex((t: CopilotKitEndpoint) => t.url === value.url);
153
- });
154
-
155
- const result = await Promise.all(
156
- filtered.map(async (endpoint) => {
157
- // Check for properties that can distinguish LG platform from other actions
158
- if (endpoint.type === EndpointType.LangGraphPlatform) {
159
- return constructLGCRemoteAction({
160
- endpoint,
161
- messages,
162
- graphqlContext,
163
- logger: logger.child({
164
- component: "remote-actions.constructLGCRemoteAction",
165
- endpoint,
166
- }),
167
- agentStates,
168
- });
169
- }
170
-
171
- const json = await fetchRemoteInfo({
172
- url: endpoint.url,
173
- onBeforeRequest: endpoint.onBeforeRequest,
174
- graphqlContext,
175
- logger: logger.child({ component: "remote-actions.fetchActionsFromUrl", endpoint }),
176
- frontendUrl,
177
- });
178
-
179
- return constructRemoteActions({
180
- json,
181
- messages,
182
- url: endpoint.url,
183
- onBeforeRequest: endpoint.onBeforeRequest,
184
- graphqlContext,
185
- logger: logger.child({ component: "remote-actions.constructActions", endpoint }),
186
- agentStates,
187
- });
188
- }),
189
- );
190
-
191
- for (const [key, agent] of Object.entries(agents)) {
192
- if (agent.agentId !== undefined && agent.agentId !== key) {
193
- throw new CopilotKitError({
194
- message: `Agent ${key} has agentId ${agent.agentId} which does not match the key ${key}`,
195
- code: CopilotKitErrorCode.UNKNOWN,
196
- });
197
- } else if (agent.agentId === undefined) {
198
- agent.agentId = key;
199
- }
200
-
201
- result.push(
202
- constructAGUIRemoteAction({
203
- logger,
204
- messages,
205
- agentStates,
206
- agent: agent,
207
- metaEvents,
208
- threadMetadata,
209
- nodeName,
210
- graphqlContext,
211
- context,
212
- }),
213
- );
214
- }
215
-
216
- return result.flat();
217
- }