@copilotkit/runtime 1.3.16-mme-reset-chat.2 → 1.4.0-feat-langgraph-cloud.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 (66) hide show
  1. package/CHANGELOG.md +4 -17
  2. package/__snapshots__/schema/schema.graphql +1 -0
  3. package/dist/{chunk-DX45O7PM.mjs → chunk-AEUECXAW.mjs} +675 -151
  4. package/dist/chunk-AEUECXAW.mjs.map +1 -0
  5. package/dist/{chunk-MYZHUCL6.mjs → chunk-B74M7FXG.mjs} +1 -1
  6. package/dist/chunk-B74M7FXG.mjs.map +1 -0
  7. package/dist/{chunk-KFO5XSPV.mjs → chunk-BLB2XDIL.mjs} +2 -2
  8. package/dist/{chunk-STQIVH2M.mjs → chunk-DP7YGMSZ.mjs} +37 -10
  9. package/dist/chunk-DP7YGMSZ.mjs.map +1 -0
  10. package/dist/{chunk-7LIN2NIO.mjs → chunk-ITCPKBTK.mjs} +2 -2
  11. package/dist/{chunk-SMVZ2NQP.mjs → chunk-VGYN7TGZ.mjs} +19 -29
  12. package/dist/{chunk-SMVZ2NQP.mjs.map → chunk-VGYN7TGZ.mjs.map} +1 -1
  13. package/dist/{chunk-AXHCROTL.mjs → chunk-WQFBGT3B.mjs} +2 -2
  14. package/dist/{copilot-runtime-df3527ad.d.ts → copilot-runtime-543a59ae.d.ts} +29 -7
  15. package/dist/graphql/types/converted/index.d.ts +1 -1
  16. package/dist/graphql/types/converted/index.js.map +1 -1
  17. package/dist/graphql/types/converted/index.mjs +1 -1
  18. package/dist/{groq-adapter-b122e71f.d.ts → groq-adapter-7aa25931.d.ts} +4 -2
  19. package/dist/{index-cff31380.d.ts → index-83ee522f.d.ts} +3 -2
  20. package/dist/index.d.ts +4 -4
  21. package/dist/index.js +765 -224
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +13 -9
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{langserve-a14a6849.d.ts → langserve-f00629d2.d.ts} +1 -1
  26. package/dist/lib/index.d.ts +4 -4
  27. package/dist/lib/index.js +765 -224
  28. package/dist/lib/index.js.map +1 -1
  29. package/dist/lib/index.mjs +13 -9
  30. package/dist/lib/integrations/index.d.ts +4 -4
  31. package/dist/lib/integrations/index.js +4 -1
  32. package/dist/lib/integrations/index.js.map +1 -1
  33. package/dist/lib/integrations/index.mjs +5 -5
  34. package/dist/lib/integrations/nest/index.d.ts +3 -3
  35. package/dist/lib/integrations/nest/index.js +4 -1
  36. package/dist/lib/integrations/nest/index.js.map +1 -1
  37. package/dist/lib/integrations/nest/index.mjs +3 -3
  38. package/dist/lib/integrations/node-express/index.d.ts +3 -3
  39. package/dist/lib/integrations/node-express/index.js +4 -1
  40. package/dist/lib/integrations/node-express/index.js.map +1 -1
  41. package/dist/lib/integrations/node-express/index.mjs +3 -3
  42. package/dist/lib/integrations/node-http/index.d.ts +3 -3
  43. package/dist/lib/integrations/node-http/index.js +4 -1
  44. package/dist/lib/integrations/node-http/index.js.map +1 -1
  45. package/dist/lib/integrations/node-http/index.mjs +2 -2
  46. package/dist/service-adapters/index.d.ts +4 -4
  47. package/dist/service-adapters/index.js +18 -28
  48. package/dist/service-adapters/index.js.map +1 -1
  49. package/dist/service-adapters/index.mjs +1 -1
  50. package/package.json +6 -4
  51. package/src/agents/langgraph/event-source.ts +62 -94
  52. package/src/agents/langgraph/events.ts +27 -17
  53. package/src/graphql/types/converted/index.ts +5 -1
  54. package/src/graphql/types/enums.ts +1 -0
  55. package/src/lib/runtime/copilot-runtime.ts +58 -11
  56. package/src/lib/runtime/remote-action-constructors.ts +284 -0
  57. package/src/lib/runtime/remote-actions.ts +65 -159
  58. package/src/lib/runtime/remote-lg-cloud-action.ts +613 -0
  59. package/src/service-adapters/google/google-genai-adapter.ts +2 -2
  60. package/src/service-adapters/langchain/langchain-adapter.ts +19 -23
  61. package/dist/chunk-DX45O7PM.mjs.map +0 -1
  62. package/dist/chunk-MYZHUCL6.mjs.map +0 -1
  63. package/dist/chunk-STQIVH2M.mjs.map +0 -1
  64. /package/dist/{chunk-KFO5XSPV.mjs.map → chunk-BLB2XDIL.mjs.map} +0 -0
  65. /package/dist/{chunk-7LIN2NIO.mjs.map → chunk-ITCPKBTK.mjs.map} +0 -0
  66. /package/dist/{chunk-AXHCROTL.mjs.map → chunk-WQFBGT3B.mjs.map} +0 -0
package/dist/lib/index.js CHANGED
@@ -44,7 +44,7 @@ var require_package = __commonJS({
44
44
  publishConfig: {
45
45
  access: "public"
46
46
  },
47
- version: "1.3.16-mme-reset-chat.2",
47
+ version: "1.4.0-feat-langgraph-cloud.0",
48
48
  sideEffects: false,
49
49
  main: "./dist/index.js",
50
50
  module: "./dist/index.mjs",
@@ -87,6 +87,7 @@ var require_package = __commonJS({
87
87
  "@langchain/community": "^0.0.53",
88
88
  "@langchain/core": "^0.3.13",
89
89
  "@langchain/google-gauth": "^0.1.0",
90
+ "@langchain/langgraph-sdk": "^0.0.16",
90
91
  "@langchain/openai": "^0.0.28",
91
92
  "class-transformer": "^0.5.1",
92
93
  express: "^4.19.2",
@@ -96,6 +97,7 @@ var require_package = __commonJS({
96
97
  "groq-sdk": "^0.5.0",
97
98
  langchain: "^0.3.3",
98
99
  openai: "^4.50.0",
100
+ "partial-json": "^0.1.7",
99
101
  pino: "^9.2.0",
100
102
  "pino-pretty": "^11.2.1",
101
103
  "reflect-metadata": "^0.2.2",
@@ -131,6 +133,7 @@ __export(lib_exports, {
131
133
  UnifyAdapter: () => UnifyAdapter,
132
134
  buildSchema: () => buildSchema,
133
135
  config: () => config,
136
+ copilotKitEndpoint: () => copilotKitEndpoint,
134
137
  copilotRuntimeNestEndpoint: () => copilotRuntimeNestEndpoint,
135
138
  copilotRuntimeNextJSAppRouterEndpoint: () => copilotRuntimeNextJSAppRouterEndpoint,
136
139
  copilotRuntimeNextJSPagesRouterEndpoint: () => copilotRuntimeNextJSPagesRouterEndpoint,
@@ -138,7 +141,8 @@ __export(lib_exports, {
138
141
  copilotRuntimeNodeHttpEndpoint: () => copilotRuntimeNodeHttpEndpoint,
139
142
  createContext: () => createContext,
140
143
  flattenToolCallsNoDuplicates: () => flattenToolCallsNoDuplicates,
141
- getCommonConfig: () => getCommonConfig
144
+ getCommonConfig: () => getCommonConfig,
145
+ langGraphCloudEndpoint: () => langGraphCloudEndpoint
142
146
  });
143
147
  module.exports = __toCommonJS(lib_exports);
144
148
 
@@ -668,7 +672,6 @@ __name(encodeResult, "encodeResult");
668
672
 
669
673
  // src/service-adapters/langchain/langchain-adapter.ts
670
674
  var import_shared3 = require("@copilotkit/shared");
671
- var import_promises = require("@langchain/core/callbacks/promises");
672
675
  var LangChainAdapter = class {
673
676
  options;
674
677
  /**
@@ -678,28 +681,23 @@ var LangChainAdapter = class {
678
681
  this.options = options;
679
682
  }
680
683
  async process(request) {
681
- try {
682
- const { eventSource, model, actions, messages, runId } = request;
683
- const threadId = request.threadId ?? (0, import_shared3.randomId)();
684
- const result = await this.options.chainFn({
685
- messages: messages.map(convertMessageToLangChainMessage),
686
- tools: actions.map(convertActionInputToLangChainTool),
687
- model,
688
- threadId,
689
- runId
690
- });
691
- eventSource.stream(async (eventStream$) => {
692
- await streamLangChainResponse({
693
- result,
694
- eventStream$
695
- });
684
+ const { eventSource, model, actions, messages, threadId, runId } = request;
685
+ const result = await this.options.chainFn({
686
+ messages: messages.map(convertMessageToLangChainMessage),
687
+ tools: actions.map(convertActionInputToLangChainTool),
688
+ model,
689
+ threadId,
690
+ runId
691
+ });
692
+ eventSource.stream(async (eventStream$) => {
693
+ await streamLangChainResponse({
694
+ result,
695
+ eventStream$
696
696
  });
697
- return {
698
- threadId
699
- };
700
- } finally {
701
- await (0, import_promises.awaitAllCallbacks)();
702
- }
697
+ });
698
+ return {
699
+ threadId: threadId || (0, import_shared3.randomId)()
700
+ };
703
701
  }
704
702
  };
705
703
  __name(LangChainAdapter, "LangChainAdapter");
@@ -709,16 +707,12 @@ var import_google_gauth = require("@langchain/google-gauth");
709
707
  var GoogleGenerativeAIAdapter = class extends LangChainAdapter {
710
708
  constructor(options) {
711
709
  super({
712
- chainFn: async ({ messages, tools, threadId }) => {
710
+ chainFn: async ({ messages, tools }) => {
713
711
  const model = new import_google_gauth.ChatGoogle({
714
712
  modelName: (options == null ? void 0 : options.model) ?? "gemini-1.5-pro",
715
713
  apiVersion: "v1beta"
716
714
  }).bindTools(tools);
717
- return model.stream(messages, {
718
- metadata: {
719
- conversation_id: threadId
720
- }
721
- });
715
+ return model.stream(messages);
722
716
  }
723
717
  });
724
718
  }
@@ -1090,58 +1084,20 @@ var LangGraphEventTypes;
1090
1084
  LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
1091
1085
  LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
1092
1086
  LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
1093
- LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
1094
- LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
1087
+ LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
1095
1088
  })(LangGraphEventTypes || (LangGraphEventTypes = {}));
1089
+ var CustomEventNames;
1090
+ (function(CustomEventNames2) {
1091
+ CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
1092
+ CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
1093
+ CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
1094
+ CustomEventNames2["CopilotKitExit"] = "copilotkit_exit";
1095
+ })(CustomEventNames || (CustomEventNames = {}));
1096
1096
 
1097
1097
  // src/agents/langgraph/event-source.ts
1098
1098
  var import_shared7 = require("@copilotkit/shared");
1099
1099
  var RemoteLangGraphEventSource = class {
1100
1100
  eventStream$ = new import_rxjs.ReplaySubject();
1101
- async streamResponse(response) {
1102
- const reader = response.body.getReader();
1103
- const decoder = new TextDecoder();
1104
- let buffer = [];
1105
- const eventStream$ = this.eventStream$;
1106
- function flushBuffer() {
1107
- const currentBuffer = buffer.join("");
1108
- if (currentBuffer.trim().length === 0) {
1109
- return;
1110
- }
1111
- const parts = currentBuffer.split("\n");
1112
- if (parts.length === 0) {
1113
- return;
1114
- }
1115
- const lastPartIsComplete = currentBuffer.endsWith("\n");
1116
- buffer = [];
1117
- if (!lastPartIsComplete) {
1118
- buffer.push(parts.pop());
1119
- }
1120
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1121
- eventStream$.next(JSON.parse(part));
1122
- });
1123
- }
1124
- __name(flushBuffer, "flushBuffer");
1125
- try {
1126
- while (true) {
1127
- const { done, value } = await reader.read();
1128
- if (!done) {
1129
- buffer.push(decoder.decode(value, {
1130
- stream: true
1131
- }));
1132
- }
1133
- flushBuffer();
1134
- if (done) {
1135
- break;
1136
- }
1137
- }
1138
- } catch (error) {
1139
- console.error("Error in stream", error);
1140
- eventStream$.error(error);
1141
- return;
1142
- }
1143
- eventStream$.complete();
1144
- }
1145
1101
  shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1146
1102
  if (typeof shouldEmitToolCalls === "boolean") {
1147
1103
  return shouldEmitToolCalls;
@@ -1164,20 +1120,25 @@ var RemoteLangGraphEventSource = class {
1164
1120
  } else {
1165
1121
  acc.content = null;
1166
1122
  }
1167
- if ((_h = (_g = (_f = event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.kwargs) == null ? void 0 : _h.tool_call_chunks) {
1123
+ const toolCallChunks = (
1124
+ // @ts-expect-error -- LangGraph Cloud implementation stores data outside of kwargs
1125
+ ((_h = (_g = (_f = event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.kwargs) == null ? void 0 : _h.tool_call_chunks) ?? ((_j = (_i = event.data) == null ? void 0 : _i.chunk) == null ? void 0 : _j.tool_call_chunks)
1126
+ );
1127
+ const toolCallMessageId = ((_m = (_l = (_k = event.data) == null ? void 0 : _k.chunk) == null ? void 0 : _l.kwargs) == null ? void 0 : _m.id) ?? ((_o = (_n = event.data) == null ? void 0 : _n.chunk) == null ? void 0 : _o.id);
1128
+ if (toolCallChunks && toolCallChunks.length > 0) {
1168
1129
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1169
- acc.toolCallMessageId = (_i = event.data.chunk.kwargs) == null ? void 0 : _i.id;
1170
- if ((_j = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _j.name) {
1171
- acc.toolCallName = event.data.chunk.kwargs.tool_call_chunks[0].name;
1130
+ acc.toolCallMessageId = toolCallMessageId;
1131
+ if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1132
+ acc.toolCallName = toolCallChunks[0].name;
1172
1133
  }
1173
- if ((_k = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _k.id) {
1174
- acc.toolCallId = event.data.chunk.kwargs.tool_call_chunks[0].id;
1134
+ if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1135
+ acc.toolCallId = toolCallChunks[0].id;
1175
1136
  }
1176
1137
  acc.prevMessageId = acc.messageId;
1177
- acc.messageId = (_n = (_m = (_l = event.data) == null ? void 0 : _l.chunk) == null ? void 0 : _m.kwargs) == null ? void 0 : _n.id;
1138
+ acc.messageId = toolCallMessageId;
1178
1139
  } else if (acc.content && acc.content != "") {
1179
1140
  acc.prevMessageId = acc.messageId;
1180
- acc.messageId = (_q = (_p = (_o = event.data) == null ? void 0 : _o.chunk) == null ? void 0 : _p.kwargs) == null ? void 0 : _q.id;
1141
+ acc.messageId = toolCallMessageId;
1181
1142
  } else {
1182
1143
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1183
1144
  acc.prevMessageId = acc.messageId;
@@ -1202,7 +1163,7 @@ var RemoteLangGraphEventSource = class {
1202
1163
  prevMessageId: null,
1203
1164
  content: null
1204
1165
  }), (0, import_rxjs.mergeMap)((eventWithState) => {
1205
- var _a, _b, _c, _d, _e;
1166
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1206
1167
  const events = [];
1207
1168
  let shouldEmitMessages = true;
1208
1169
  let shouldEmitToolCalls = false;
@@ -1225,32 +1186,33 @@ var RemoteLangGraphEventSource = class {
1225
1186
  });
1226
1187
  }
1227
1188
  switch (eventWithState.event.event) {
1228
- case LangGraphEventTypes.OnCopilotKitEmitMessage:
1229
- events.push({
1230
- type: RuntimeEventTypes.TextMessageStart,
1231
- messageId: eventWithState.event.message_id
1232
- });
1233
- events.push({
1234
- type: RuntimeEventTypes.TextMessageContent,
1235
- content: eventWithState.event.message
1236
- });
1237
- events.push({
1238
- type: RuntimeEventTypes.TextMessageEnd
1239
- });
1240
- break;
1241
- case LangGraphEventTypes.OnCopilotKitEmitToolCall:
1242
- events.push({
1243
- type: RuntimeEventTypes.ActionExecutionStart,
1244
- actionExecutionId: eventWithState.event.id,
1245
- actionName: eventWithState.event.name
1246
- });
1247
- events.push({
1248
- type: RuntimeEventTypes.ActionExecutionArgs,
1249
- args: JSON.stringify(eventWithState.event.args)
1250
- });
1251
- events.push({
1252
- type: RuntimeEventTypes.ActionExecutionEnd
1253
- });
1189
+ case LangGraphEventTypes.OnCustomEvent:
1190
+ if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1191
+ events.push({
1192
+ type: RuntimeEventTypes.TextMessageStart,
1193
+ messageId: eventWithState.event.data.message_id
1194
+ });
1195
+ events.push({
1196
+ type: RuntimeEventTypes.TextMessageContent,
1197
+ content: eventWithState.event.data.message
1198
+ });
1199
+ events.push({
1200
+ type: RuntimeEventTypes.TextMessageEnd
1201
+ });
1202
+ } else if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1203
+ events.push({
1204
+ type: RuntimeEventTypes.ActionExecutionStart,
1205
+ actionExecutionId: eventWithState.event.data.id,
1206
+ actionName: eventWithState.event.data.name
1207
+ });
1208
+ events.push({
1209
+ type: RuntimeEventTypes.ActionExecutionArgs,
1210
+ args: JSON.stringify(eventWithState.event.data.args)
1211
+ });
1212
+ events.push({
1213
+ type: RuntimeEventTypes.ActionExecutionEnd
1214
+ });
1215
+ }
1254
1216
  break;
1255
1217
  case LangGraphEventTypes.OnCopilotKitStateSync:
1256
1218
  events.push({
@@ -1285,7 +1247,8 @@ var RemoteLangGraphEventSource = class {
1285
1247
  });
1286
1248
  }
1287
1249
  }
1288
- const args = (_e = (_d = (_c = (_b = (_a = eventWithState.event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) == null ? void 0 : _d[0]) == null ? void 0 : _e.args;
1250
+ const args = ((_e = (_d = (_c = (_b = (_a = eventWithState.event.data) == null ? void 0 : _a.chunk) == null ? void 0 : _b.kwargs) == null ? void 0 : _c.tool_call_chunks) == null ? void 0 : _d[0]) == null ? void 0 : _e.args) ?? // @ts-expect-error -- sdf
1251
+ ((_i = (_h = (_g = (_f = eventWithState.event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.tool_call_chunks) == null ? void 0 : _h[0]) == null ? void 0 : _i.args);
1289
1252
  const content = eventWithState.content;
1290
1253
  if (args) {
1291
1254
  if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
@@ -1336,70 +1299,528 @@ var RemoteLangGraphEventSource = class {
1336
1299
  };
1337
1300
  __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1338
1301
 
1339
- // src/lib/runtime/remote-actions.ts
1340
- function isLangGraphAgentAction(action) {
1341
- if (!action) {
1342
- return false;
1343
- }
1344
- return typeof action.langGraphAgentHandler === "function";
1302
+ // src/lib/runtime/remote-lg-cloud-action.ts
1303
+ var import_langgraph_sdk = require("@langchain/langgraph-sdk");
1304
+ var import_node_crypto = require("crypto");
1305
+ var import_partial_json = require("partial-json");
1306
+
1307
+ // src/graphql/types/enums.ts
1308
+ var import_type_graphql = require("type-graphql");
1309
+ var MessageRole;
1310
+ (function(MessageRole2) {
1311
+ MessageRole2["user"] = "user";
1312
+ MessageRole2["assistant"] = "assistant";
1313
+ MessageRole2["system"] = "system";
1314
+ MessageRole2["tool"] = "tool";
1315
+ })(MessageRole || (MessageRole = {}));
1316
+ var ActionExecutionScope;
1317
+ (function(ActionExecutionScope2) {
1318
+ ActionExecutionScope2["server"] = "server";
1319
+ ActionExecutionScope2["client"] = "client";
1320
+ ActionExecutionScope2["passThrough"] = "passThrough";
1321
+ })(ActionExecutionScope || (ActionExecutionScope = {}));
1322
+ var CopilotRequestType;
1323
+ (function(CopilotRequestType2) {
1324
+ CopilotRequestType2["Chat"] = "Chat";
1325
+ CopilotRequestType2["Task"] = "Task";
1326
+ CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
1327
+ CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
1328
+ CopilotRequestType2["Suggestion"] = "Suggestion";
1329
+ })(CopilotRequestType || (CopilotRequestType = {}));
1330
+ (0, import_type_graphql.registerEnumType)(MessageRole, {
1331
+ name: "MessageRole",
1332
+ description: "The role of the message"
1333
+ });
1334
+ (0, import_type_graphql.registerEnumType)(ActionExecutionScope, {
1335
+ name: "ActionExecutionScope",
1336
+ description: "The scope of the action"
1337
+ });
1338
+ (0, import_type_graphql.registerEnumType)(CopilotRequestType, {
1339
+ name: "CopilotRequestType",
1340
+ description: "The type of Copilot request"
1341
+ });
1342
+
1343
+ // src/lib/runtime/remote-lg-cloud-action.ts
1344
+ async function execute(args) {
1345
+ return new ReadableStream({
1346
+ async start(controller) {
1347
+ try {
1348
+ await streamEvents(controller, args);
1349
+ controller.close();
1350
+ } catch (err) {
1351
+ }
1352
+ }
1353
+ });
1345
1354
  }
1346
- __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1347
- function createHeaders(onBeforeRequest, graphqlContext) {
1348
- const headers = {
1349
- "Content-Type": "application/json"
1355
+ __name(execute, "execute");
1356
+ async function streamEvents(controller, args) {
1357
+ const { deploymentUrl, langsmithApiKey, threadId: agrsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, messages, actions, logger: logger2 } = args;
1358
+ let nodeName = initialNodeName;
1359
+ let state = initialState;
1360
+ const { name, assistantId: initialAssistantId } = agent;
1361
+ const client = new import_langgraph_sdk.Client({
1362
+ apiUrl: deploymentUrl,
1363
+ apiKey: langsmithApiKey
1364
+ });
1365
+ let initialThreadId = agrsInitialThreadId;
1366
+ const wasInitiatedWithExistingThread = !!initialThreadId;
1367
+ if (initialThreadId && initialThreadId.startsWith("ck-")) {
1368
+ initialThreadId = initialThreadId.substring(3);
1369
+ }
1370
+ const assistants = await client.assistants.search();
1371
+ const retrievedAssistant = assistants.find((a) => a.name === name);
1372
+ const threadId = initialThreadId ?? (0, import_node_crypto.randomUUID)();
1373
+ if (initialThreadId === threadId) {
1374
+ await client.threads.get(threadId);
1375
+ } else {
1376
+ await client.threads.create({
1377
+ threadId
1378
+ });
1379
+ }
1380
+ let agentState = {
1381
+ values: {}
1350
1382
  };
1351
- if (onBeforeRequest) {
1352
- const { headers: additionalHeaders } = onBeforeRequest({
1353
- ctx: graphqlContext
1383
+ if (wasInitiatedWithExistingThread) {
1384
+ agentState = await client.threads.getState(threadId);
1385
+ }
1386
+ const agentStateValues = agentState.values;
1387
+ state.messages = agentStateValues.messages;
1388
+ const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1389
+ let formattedMessages = [];
1390
+ try {
1391
+ formattedMessages = formatMessages(messages);
1392
+ } catch (e) {
1393
+ logger2.error(e, `Error event thrown: ${e.message}`);
1394
+ }
1395
+ state = langGraphDefaultMergeState(state, formattedMessages, actions, name);
1396
+ if (mode === "continue") {
1397
+ await client.threads.updateState(threadId, {
1398
+ values: state,
1399
+ asNode: nodeName
1354
1400
  });
1355
- if (additionalHeaders) {
1356
- Object.assign(headers, additionalHeaders);
1401
+ }
1402
+ const assistantId = initialAssistantId ?? (retrievedAssistant == null ? void 0 : retrievedAssistant.assistant_id);
1403
+ if (!assistantId) {
1404
+ console.error(`
1405
+ No agent found for the agent name specified in CopilotKit provider
1406
+ Please check your available agents or provide an agent ID in the LangGraph Cloud endpoint definition.
1407
+
1408
+
1409
+ These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
1410
+ `);
1411
+ throw new Error("No agent id found");
1412
+ }
1413
+ const graphInfo = await client.assistants.getGraph(assistantId);
1414
+ const streamInput = mode === "start" ? state : null;
1415
+ let streamingStateExtractor = new StreamingStateExtractor([]);
1416
+ let prevNodeName = null;
1417
+ let emitIntermediateStateUntilEnd = null;
1418
+ let shouldExit = null;
1419
+ let externalRunId = null;
1420
+ const streamResponse2 = client.runs.stream(threadId, assistantId, {
1421
+ input: streamInput,
1422
+ streamMode: [
1423
+ "events",
1424
+ "values"
1425
+ ]
1426
+ });
1427
+ const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
1428
+ let latestStateValues = {};
1429
+ try {
1430
+ for await (const chunk of streamResponse2) {
1431
+ if (![
1432
+ "events",
1433
+ "values",
1434
+ "error"
1435
+ ].includes(chunk.event))
1436
+ continue;
1437
+ if (chunk.event === "error") {
1438
+ logger2.error(chunk, `Error event thrown: ${chunk.data.message}`);
1439
+ throw new Error(`Error event thrown: ${chunk.data.message}`);
1440
+ }
1441
+ if (chunk.event === "values") {
1442
+ latestStateValues = chunk.data;
1443
+ continue;
1444
+ }
1445
+ const event = chunk.data;
1446
+ const currentNodeName = event.name;
1447
+ const eventType = event.event;
1448
+ const runId = event.metadata.run_id;
1449
+ externalRunId = runId;
1450
+ const metadata = event.metadata;
1451
+ shouldExit = shouldExit != null ? shouldExit : eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitExit;
1452
+ const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
1453
+ const manuallyEmitIntermediateState = eventType === LangGraphEventTypes.OnCustomEvent && event.name === CustomEventNames.CopilotKitManuallyEmitIntermediateState;
1454
+ if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
1455
+ nodeName = currentNodeName;
1456
+ }
1457
+ if (!nodeName) {
1458
+ continue;
1459
+ }
1460
+ if (manuallyEmitIntermediateState) {
1461
+ if (eventType === LangGraphEventTypes.OnChainEnd) {
1462
+ state = event.data.output;
1463
+ emit(getStateSyncEvent({
1464
+ threadId,
1465
+ runId,
1466
+ agentName: agent.name,
1467
+ nodeName,
1468
+ state: event.data.output,
1469
+ running: true,
1470
+ active: true
1471
+ }));
1472
+ }
1473
+ continue;
1474
+ }
1475
+ if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
1476
+ emitIntermediateStateUntilEnd = nodeName;
1477
+ }
1478
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStart) {
1479
+ streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
1480
+ }
1481
+ let updatedState = latestStateValues;
1482
+ if (emitIntermediateState && eventType === LangGraphEventTypes.OnChatModelStream) {
1483
+ streamingStateExtractor.bufferToolCalls(event);
1484
+ }
1485
+ if (emitIntermediateStateUntilEnd !== null) {
1486
+ updatedState = {
1487
+ ...updatedState,
1488
+ ...streamingStateExtractor.extractState()
1489
+ };
1490
+ }
1491
+ if (!emitIntermediateState && currentNodeName === emitIntermediateStateUntilEnd && eventType === LangGraphEventTypes.OnChainEnd) {
1492
+ emitIntermediateStateUntilEnd = null;
1493
+ }
1494
+ const exitingNode = nodeName === currentNodeName && eventType === LangGraphEventTypes.OnChainEnd;
1495
+ if (JSON.stringify(updatedState) !== JSON.stringify(state) || prevNodeName != nodeName || exitingNode) {
1496
+ state = updatedState;
1497
+ prevNodeName = nodeName;
1498
+ emit(getStateSyncEvent({
1499
+ threadId,
1500
+ runId,
1501
+ agentName: agent.name,
1502
+ nodeName,
1503
+ state,
1504
+ running: true,
1505
+ active: !exitingNode
1506
+ }));
1507
+ }
1508
+ emit(JSON.stringify(event) + "\n");
1357
1509
  }
1510
+ state = await client.threads.getState(threadId);
1511
+ const isEndNode = state.next.length === 0;
1512
+ nodeName = Object.keys(state.metadata.writes)[0];
1513
+ emit(getStateSyncEvent({
1514
+ threadId,
1515
+ runId: externalRunId,
1516
+ agentName: agent.name,
1517
+ nodeName: isEndNode ? "__end__" : nodeName,
1518
+ state: state.values,
1519
+ running: !shouldExit,
1520
+ active: false
1521
+ }));
1522
+ return Promise.resolve();
1523
+ } catch (e) {
1524
+ return Promise.resolve();
1358
1525
  }
1359
- return headers;
1360
1526
  }
1361
- __name(createHeaders, "createHeaders");
1362
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1363
- logger2.debug({
1364
- url
1365
- }, "Fetching actions from url");
1366
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1367
- try {
1368
- const response = await fetch(`${url}/info`, {
1369
- method: "POST",
1370
- headers,
1371
- body: JSON.stringify({
1372
- properties: graphqlContext.properties,
1373
- frontendUrl
1374
- })
1375
- });
1376
- if (!response.ok) {
1377
- logger2.error({
1378
- url,
1379
- status: response.status,
1380
- body: await response.text()
1381
- }, "Failed to fetch actions from url");
1527
+ __name(streamEvents, "streamEvents");
1528
+ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1529
+ const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1530
+ if (key !== "messages") {
1531
+ acc[key] = state[key];
1532
+ }
1533
+ return acc;
1534
+ }, {});
1535
+ return JSON.stringify({
1536
+ event: LangGraphEventTypes.OnCopilotKitStateSync,
1537
+ thread_id: threadId,
1538
+ run_id: runId,
1539
+ agent_name: agentName,
1540
+ node_name: nodeName,
1541
+ active,
1542
+ state: stateWithoutMessages,
1543
+ running,
1544
+ role: "assistant"
1545
+ }) + "\n";
1546
+ }
1547
+ __name(getStateSyncEvent, "getStateSyncEvent");
1548
+ var StreamingStateExtractor = /* @__PURE__ */ __name(class StreamingStateExtractor2 {
1549
+ emitIntermediateState;
1550
+ toolCallBuffer;
1551
+ currentToolCall;
1552
+ previouslyParsableState;
1553
+ constructor(emitIntermediateState) {
1554
+ this.emitIntermediateState = emitIntermediateState;
1555
+ this.toolCallBuffer = {};
1556
+ this.currentToolCall = null;
1557
+ this.previouslyParsableState = {};
1558
+ }
1559
+ bufferToolCalls(event) {
1560
+ if (event.data.chunk.tool_call_chunks.length > 0) {
1561
+ const chunk = event.data.chunk.tool_call_chunks[0];
1562
+ if (chunk.name !== null) {
1563
+ this.currentToolCall = chunk.name;
1564
+ this.toolCallBuffer[this.currentToolCall] = chunk.args;
1565
+ } else if (this.currentToolCall !== null) {
1566
+ this.toolCallBuffer[this.currentToolCall] += chunk.args;
1567
+ }
1568
+ }
1569
+ }
1570
+ getEmitStateConfig(currentToolName) {
1571
+ for (const config2 of this.emitIntermediateState) {
1572
+ const stateKey = config2["state_key"];
1573
+ const tool = config2["tool"];
1574
+ const toolArgument = config2["tool_argument"];
1575
+ if (currentToolName === tool) {
1576
+ return [
1577
+ toolArgument,
1578
+ stateKey
1579
+ ];
1580
+ }
1581
+ }
1582
+ return [
1583
+ null,
1584
+ null
1585
+ ];
1586
+ }
1587
+ extractState() {
1588
+ const state = {};
1589
+ for (const [key, value] of Object.entries(this.toolCallBuffer)) {
1590
+ const [argumentName, stateKey] = this.getEmitStateConfig(key);
1591
+ if (stateKey === null) {
1592
+ continue;
1593
+ }
1594
+ let parsedValue;
1595
+ try {
1596
+ parsedValue = (0, import_partial_json.parse)(value);
1597
+ } catch (error) {
1598
+ if (key in this.previouslyParsableState) {
1599
+ parsedValue = this.previouslyParsableState[key];
1600
+ } else {
1601
+ continue;
1602
+ }
1603
+ }
1604
+ this.previouslyParsableState[key] = parsedValue;
1605
+ if (!argumentName) {
1606
+ state[stateKey] = parsedValue;
1607
+ } else {
1608
+ state[stateKey] = parsedValue[argumentName];
1609
+ }
1610
+ }
1611
+ return state;
1612
+ }
1613
+ }, "StreamingStateExtractor");
1614
+ function langGraphDefaultMergeState(state, messages, actions, agentName) {
1615
+ if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1616
+ messages = messages.slice(1);
1617
+ }
1618
+ const mergedMessages = state.messages || [];
1619
+ const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1620
+ const existingToolCallResults = /* @__PURE__ */ new Set();
1621
+ for (const message of mergedMessages) {
1622
+ if ("tool_call_id" in message) {
1623
+ existingToolCallResults.add(message.tool_call_id);
1624
+ }
1625
+ }
1626
+ for (const message of messages) {
1627
+ if ("tool_calls" in message && message.tool_calls.length > 0 && message.tool_calls[0].name === agentName) {
1628
+ continue;
1629
+ }
1630
+ if ("name" in message && message.name === agentName) {
1631
+ continue;
1632
+ }
1633
+ if (!existingMessageIds.has(message.id)) {
1634
+ if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
1635
+ console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
1636
+ continue;
1637
+ }
1638
+ mergedMessages.push(message);
1639
+ } else {
1640
+ for (let i = 0; i < mergedMessages.length; i++) {
1641
+ if (mergedMessages[i].id === message.id) {
1642
+ if ("tool_calls" in message) {
1643
+ if (("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) && mergedMessages[i].content) {
1644
+ message.tool_calls = mergedMessages[i]["tool_calls"];
1645
+ message.additional_kwargs = mergedMessages[i].additional_kwargs;
1646
+ }
1647
+ }
1648
+ mergedMessages[i] = message;
1649
+ }
1650
+ }
1651
+ }
1652
+ }
1653
+ for (let i = 0; i < mergedMessages.length - 1; i++) {
1654
+ const currentMessage = mergedMessages[i];
1655
+ const nextMessage = mergedMessages[i + 1];
1656
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0 && "tool_call_id" in nextMessage) {
1657
+ nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
1658
+ }
1659
+ }
1660
+ const correctedMessages = [];
1661
+ for (let i = 0; i < mergedMessages.length; i++) {
1662
+ const currentMessage = mergedMessages[i];
1663
+ const nextMessage = mergedMessages[i + 1] || null;
1664
+ const prevMessage = mergedMessages[i - 1] || null;
1665
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
1666
+ if (!nextMessage) {
1667
+ console.warn("No next message to auto-correct tool call, skipping:", currentMessage.tool_calls[0].id);
1668
+ continue;
1669
+ }
1670
+ if (!("tool_call_id" in nextMessage) || nextMessage.tool_call_id !== currentMessage.tool_calls[0].id) {
1671
+ const toolMessage = mergedMessages.find((m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id);
1672
+ if (toolMessage) {
1673
+ console.warn("Auto-corrected tool call alignment issue:", currentMessage.tool_calls[0].id);
1674
+ correctedMessages.push(currentMessage, toolMessage);
1675
+ continue;
1676
+ } else {
1677
+ console.warn("No corresponding tool call result found for tool call, skipping:", currentMessage.tool_calls[0].id);
1678
+ continue;
1679
+ }
1680
+ }
1681
+ correctedMessages.push(currentMessage);
1682
+ continue;
1683
+ }
1684
+ if ("tool_call_id" in currentMessage) {
1685
+ if (!prevMessage || !("tool_calls" in prevMessage)) {
1686
+ console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
1687
+ continue;
1688
+ }
1689
+ if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
1690
+ console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
1691
+ continue;
1692
+ }
1693
+ correctedMessages.push(currentMessage);
1694
+ continue;
1695
+ }
1696
+ correctedMessages.push(currentMessage);
1697
+ }
1698
+ return deepMerge(state, {
1699
+ messages: correctedMessages,
1700
+ copilotkit: {
1701
+ actions
1702
+ }
1703
+ });
1704
+ }
1705
+ __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1706
+ function deepMerge(obj1, obj2) {
1707
+ let result = {
1708
+ ...obj1
1709
+ };
1710
+ for (let key in obj2) {
1711
+ if (typeof obj2[key] === "object" && !Array.isArray(obj2[key])) {
1712
+ if (obj1[key]) {
1713
+ result[key] = deepMerge(obj1[key], obj2[key]);
1714
+ } else {
1715
+ result[key] = {
1716
+ ...obj2[key]
1717
+ };
1718
+ }
1719
+ } else {
1720
+ result[key] = obj2[key];
1721
+ }
1722
+ }
1723
+ return result;
1724
+ }
1725
+ __name(deepMerge, "deepMerge");
1726
+ function formatMessages(messages) {
1727
+ return messages.map((message) => {
1728
+ if (message.isTextMessage() && message.role === "assistant") {
1729
+ return message;
1730
+ }
1731
+ if (message.isTextMessage() && message.role === "system") {
1732
+ return message;
1733
+ }
1734
+ if (message.isTextMessage() && message.role === "user") {
1735
+ return message;
1736
+ }
1737
+ if (message.isActionExecutionMessage()) {
1738
+ const toolCall = {
1739
+ name: message.name,
1740
+ args: message.arguments,
1741
+ id: message.id
1742
+ };
1382
1743
  return {
1383
- actions: [],
1384
- agents: []
1744
+ type: message.type,
1745
+ content: "",
1746
+ tool_calls: [
1747
+ toolCall
1748
+ ],
1749
+ role: MessageRole.assistant,
1750
+ id: message.id
1385
1751
  };
1386
1752
  }
1387
- const json = await response.json();
1388
- logger2.debug({
1389
- json
1390
- }, "Fetched actions from url");
1391
- return json;
1392
- } catch (error) {
1393
- logger2.error({
1394
- error: error.message ? error.message : error + ""
1395
- }, "Failed to fetch actions from url");
1396
- return {
1397
- actions: [],
1398
- agents: []
1399
- };
1400
- }
1753
+ if (message.isResultMessage()) {
1754
+ return {
1755
+ type: message.type,
1756
+ content: message.result,
1757
+ id: message.id,
1758
+ tool_call_id: message.actionExecutionId,
1759
+ name: message.actionName,
1760
+ role: MessageRole.tool
1761
+ };
1762
+ }
1763
+ throw new Error(`Unknown message type ${message.type}`);
1764
+ });
1401
1765
  }
1402
- __name(fetchRemoteInfo, "fetchRemoteInfo");
1766
+ __name(formatMessages, "formatMessages");
1767
+
1768
+ // src/lib/runtime/remote-action-constructors.ts
1769
+ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
1770
+ const agents = endpoint.agents.map((agent) => ({
1771
+ name: agent.name,
1772
+ description: agent.description,
1773
+ parameters: [],
1774
+ handler: async (_args) => {
1775
+ },
1776
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1777
+ var _a;
1778
+ logger2.debug({
1779
+ actionName: agent.name
1780
+ }, "Executing LangGraph Cloud agent");
1781
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {});
1782
+ let state = {};
1783
+ if (agentStates) {
1784
+ const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1785
+ if (jsonState) {
1786
+ state = JSON.parse(jsonState);
1787
+ }
1788
+ }
1789
+ try {
1790
+ const response = await execute({
1791
+ logger: logger2,
1792
+ deploymentUrl: endpoint.deploymentUrl,
1793
+ langsmithApiKey: endpoint.langsmithApiKey,
1794
+ agent,
1795
+ threadId,
1796
+ nodeName,
1797
+ messages,
1798
+ state,
1799
+ properties: graphqlContext.properties,
1800
+ actions: actionInputsWithoutAgents.map((action) => ({
1801
+ name: action.name,
1802
+ description: action.description,
1803
+ parameters: JSON.parse(action.jsonSchema)
1804
+ }))
1805
+ });
1806
+ const eventSource = new RemoteLangGraphEventSource();
1807
+ streamResponse(response, eventSource.eventStream$);
1808
+ return eventSource.processLangGraphEvents();
1809
+ } catch (error) {
1810
+ logger2.error({
1811
+ url: endpoint.deploymentUrl,
1812
+ status: 500,
1813
+ body: error.message
1814
+ }, "Failed to execute LangGraph Cloud agent");
1815
+ throw new Error("Failed to execute LangGraph Cloud agent");
1816
+ }
1817
+ }
1818
+ }));
1819
+ return [
1820
+ ...agents
1821
+ ];
1822
+ }
1823
+ __name(constructLGCRemoteAction, "constructLGCRemoteAction");
1403
1824
  function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
1404
1825
  const actions = json["actions"].map((action) => ({
1405
1826
  name: action.name,
@@ -1491,7 +1912,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1491
1912
  throw new Error("Failed to execute remote agent");
1492
1913
  }
1493
1914
  const eventSource = new RemoteLangGraphEventSource();
1494
- eventSource.streamResponse(response);
1915
+ streamResponse(response.body, eventSource.eventStream$);
1495
1916
  return eventSource.processLangGraphEvents();
1496
1917
  }
1497
1918
  }));
@@ -1501,34 +1922,165 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1501
1922
  ];
1502
1923
  }
1503
1924
  __name(constructRemoteActions, "constructRemoteActions");
1504
- async function setupRemoteActions({ remoteActionDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1925
+ async function streamResponse(response, eventStream$) {
1926
+ const reader = response.getReader();
1927
+ const decoder = new TextDecoder();
1928
+ let buffer = [];
1929
+ function flushBuffer() {
1930
+ const currentBuffer = buffer.join("");
1931
+ if (currentBuffer.trim().length === 0) {
1932
+ return;
1933
+ }
1934
+ const parts = currentBuffer.split("\n");
1935
+ if (parts.length === 0) {
1936
+ return;
1937
+ }
1938
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
1939
+ buffer = [];
1940
+ if (!lastPartIsComplete) {
1941
+ buffer.push(parts.pop());
1942
+ }
1943
+ parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1944
+ eventStream$.next(JSON.parse(part));
1945
+ });
1946
+ }
1947
+ __name(flushBuffer, "flushBuffer");
1948
+ try {
1949
+ while (true) {
1950
+ const { done, value } = await reader.read();
1951
+ if (!done) {
1952
+ buffer.push(decoder.decode(value, {
1953
+ stream: true
1954
+ }));
1955
+ }
1956
+ flushBuffer();
1957
+ if (done) {
1958
+ break;
1959
+ }
1960
+ }
1961
+ } catch (error) {
1962
+ console.error("Error in stream", error);
1963
+ eventStream$.error(error);
1964
+ return;
1965
+ }
1966
+ eventStream$.complete();
1967
+ }
1968
+ __name(streamResponse, "streamResponse");
1969
+ function createHeaders(onBeforeRequest, graphqlContext) {
1970
+ const headers = {
1971
+ "Content-Type": "application/json"
1972
+ };
1973
+ if (onBeforeRequest) {
1974
+ const { headers: additionalHeaders } = onBeforeRequest({
1975
+ ctx: graphqlContext
1976
+ });
1977
+ if (additionalHeaders) {
1978
+ Object.assign(headers, additionalHeaders);
1979
+ }
1980
+ }
1981
+ return headers;
1982
+ }
1983
+ __name(createHeaders, "createHeaders");
1984
+
1985
+ // src/lib/runtime/remote-actions.ts
1986
+ var EndpointType;
1987
+ (function(EndpointType2) {
1988
+ EndpointType2["CopilotKit"] = "copilotKit";
1989
+ EndpointType2["LangGraphCloud"] = "langgraph-cloud";
1990
+ })(EndpointType || (EndpointType = {}));
1991
+ function isLangGraphAgentAction(action) {
1992
+ if (!action) {
1993
+ return false;
1994
+ }
1995
+ return typeof action.langGraphAgentHandler === "function";
1996
+ }
1997
+ __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1998
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1999
+ logger2.debug({
2000
+ url
2001
+ }, "Fetching actions from url");
2002
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
2003
+ try {
2004
+ const response = await fetch(`${url}/info`, {
2005
+ method: "POST",
2006
+ headers,
2007
+ body: JSON.stringify({
2008
+ properties: graphqlContext.properties,
2009
+ frontendUrl
2010
+ })
2011
+ });
2012
+ if (!response.ok) {
2013
+ logger2.error({
2014
+ url,
2015
+ status: response.status,
2016
+ body: await response.text()
2017
+ }, "Failed to fetch actions from url");
2018
+ return {
2019
+ actions: [],
2020
+ agents: []
2021
+ };
2022
+ }
2023
+ const json = await response.json();
2024
+ logger2.debug({
2025
+ json
2026
+ }, "Fetched actions from url");
2027
+ return json;
2028
+ } catch (error) {
2029
+ logger2.error({
2030
+ error: error.message ? error.message : error + ""
2031
+ }, "Failed to fetch actions from url");
2032
+ return {
2033
+ actions: [],
2034
+ agents: []
2035
+ };
2036
+ }
2037
+ }
2038
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
2039
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1505
2040
  const logger2 = graphqlContext.logger.child({
1506
2041
  component: "remote-actions.fetchRemoteActions"
1507
2042
  });
1508
2043
  logger2.debug({
1509
- remoteActionDefinitions
1510
- }, "Fetching remote actions");
1511
- const filtered = remoteActionDefinitions.filter((value, index, self) => index === self.findIndex((t) => t.url === value.url));
1512
- const result = await Promise.all(filtered.map(async (actionDefinition) => {
2044
+ remoteEndpointDefinitions
2045
+ }, "Fetching from remote endpoints");
2046
+ const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2047
+ if (value.type === "langgraph-cloud") {
2048
+ return value;
2049
+ }
2050
+ return index === self.findIndex((t) => t.url === value.url);
2051
+ });
2052
+ const result = await Promise.all(filtered.map(async (endpoint) => {
2053
+ if (endpoint.type === "langgraph-cloud") {
2054
+ return constructLGCRemoteAction({
2055
+ endpoint,
2056
+ messages,
2057
+ graphqlContext,
2058
+ logger: logger2.child({
2059
+ component: "remote-actions.constructLGCRemoteAction",
2060
+ endpoint
2061
+ }),
2062
+ agentStates
2063
+ });
2064
+ }
1513
2065
  const json = await fetchRemoteInfo({
1514
- url: actionDefinition.url,
1515
- onBeforeRequest: actionDefinition.onBeforeRequest,
2066
+ url: endpoint.url,
2067
+ onBeforeRequest: endpoint.onBeforeRequest,
1516
2068
  graphqlContext,
1517
2069
  logger: logger2.child({
1518
2070
  component: "remote-actions.fetchActionsFromUrl",
1519
- actionDefinition
2071
+ endpoint
1520
2072
  }),
1521
2073
  frontendUrl
1522
2074
  });
1523
2075
  return constructRemoteActions({
1524
2076
  json,
1525
2077
  messages,
1526
- url: actionDefinition.url,
1527
- onBeforeRequest: actionDefinition.onBeforeRequest,
2078
+ url: endpoint.url,
2079
+ onBeforeRequest: endpoint.onBeforeRequest,
1528
2080
  graphqlContext,
1529
2081
  logger: logger2.child({
1530
2082
  component: "remote-actions.constructActions",
1531
- actionDefinition
2083
+ endpoint
1532
2084
  }),
1533
2085
  agentStates
1534
2086
  });
@@ -1726,7 +2278,7 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
1726
2278
  __name(executeAction, "executeAction");
1727
2279
 
1728
2280
  // src/graphql/types/base/index.ts
1729
- var import_type_graphql = require("type-graphql");
2281
+ var import_type_graphql2 = require("type-graphql");
1730
2282
  function _ts_decorate(decorators, target, key, desc) {
1731
2283
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1732
2284
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -1749,15 +2301,15 @@ var BaseMessageInput = class {
1749
2301
  };
1750
2302
  __name(BaseMessageInput, "BaseMessageInput");
1751
2303
  _ts_decorate([
1752
- (0, import_type_graphql.Field)(() => String),
2304
+ (0, import_type_graphql2.Field)(() => String),
1753
2305
  _ts_metadata("design:type", String)
1754
2306
  ], BaseMessageInput.prototype, "id", void 0);
1755
2307
  _ts_decorate([
1756
- (0, import_type_graphql.Field)(() => Date),
2308
+ (0, import_type_graphql2.Field)(() => Date),
1757
2309
  _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
1758
2310
  ], BaseMessageInput.prototype, "createdAt", void 0);
1759
2311
  BaseMessageInput = _ts_decorate([
1760
- (0, import_type_graphql.InputType)()
2312
+ (0, import_type_graphql2.InputType)()
1761
2313
  ], BaseMessageInput);
1762
2314
 
1763
2315
  // src/graphql/types/converted/index.ts
@@ -1861,7 +2413,7 @@ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
1861
2413
  var import_rxjs3 = require("rxjs");
1862
2414
  var CopilotRuntime = class {
1863
2415
  actions;
1864
- remoteActionDefinitions;
2416
+ remoteEndpointDefinitions;
1865
2417
  langserve = [];
1866
2418
  onBeforeRequest;
1867
2419
  onAfterRequest;
@@ -1872,7 +2424,7 @@ var CopilotRuntime = class {
1872
2424
  const remoteChain = new RemoteChain(chain);
1873
2425
  this.langserve.push(remoteChain.toAction());
1874
2426
  }
1875
- this.remoteActionDefinitions = (params == null ? void 0 : params.remoteActions) || [];
2427
+ this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) || [];
1876
2428
  this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
1877
2429
  this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
1878
2430
  }
@@ -1941,7 +2493,7 @@ var CopilotRuntime = class {
1941
2493
  async processAgentRequest(request) {
1942
2494
  var _a;
1943
2495
  const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;
1944
- const { threadId = (0, import_shared8.randomId)(), agentName, nodeName } = agentSession;
2496
+ const { threadId, agentName, nodeName } = agentSession;
1945
2497
  const serverSideActions = await this.getServerSideActions(request);
1946
2498
  const messages = convertGqlInputToMessages(rawMessages);
1947
2499
  const agent = serverSideActions.find((action) => action.name === agentName && isLangGraphAgentAction(action));
@@ -2013,8 +2565,12 @@ var CopilotRuntime = class {
2013
2565
  console.error("Error loading langserve chain:", error);
2014
2566
  }
2015
2567
  }
2568
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
2569
+ ...endpoint,
2570
+ type: this.resolveEndpointType(endpoint)
2571
+ }));
2016
2572
  const remoteActions = await setupRemoteActions({
2017
- remoteActionDefinitions: this.remoteActionDefinitions,
2573
+ remoteEndpointDefinitions,
2018
2574
  graphqlContext,
2019
2575
  messages: inputMessages,
2020
2576
  agentStates,
@@ -2030,6 +2586,12 @@ var CopilotRuntime = class {
2030
2586
  ...remoteActions
2031
2587
  ];
2032
2588
  }
2589
+ resolveEndpointType(endpoint) {
2590
+ if (!endpoint.type && "langsmithApiKey" in endpoint && "deploymentUrl" in endpoint && "agents" in endpoint) {
2591
+ return EndpointType.LangGraphCloud;
2592
+ }
2593
+ return endpoint.type;
2594
+ }
2033
2595
  };
2034
2596
  __name(CopilotRuntime, "CopilotRuntime");
2035
2597
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -2044,6 +2606,20 @@ function flattenToolCallsNoDuplicates(toolsByPriority) {
2044
2606
  return allTools;
2045
2607
  }
2046
2608
  __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
2609
+ function copilotKitEndpoint(config2) {
2610
+ return {
2611
+ ...config2,
2612
+ type: EndpointType.CopilotKit
2613
+ };
2614
+ }
2615
+ __name(copilotKitEndpoint, "copilotKitEndpoint");
2616
+ function langGraphCloudEndpoint(config2) {
2617
+ return {
2618
+ ...config2,
2619
+ type: EndpointType.LangGraphCloud
2620
+ };
2621
+ }
2622
+ __name(langGraphCloudEndpoint, "langGraphCloudEndpoint");
2047
2623
 
2048
2624
  // src/lib/integrations/shared.ts
2049
2625
  var import_type_graphql16 = require("type-graphql");
@@ -2057,43 +2633,6 @@ var import_type_graphql11 = require("type-graphql");
2057
2633
 
2058
2634
  // src/graphql/inputs/message.input.ts
2059
2635
  var import_type_graphql3 = require("type-graphql");
2060
-
2061
- // src/graphql/types/enums.ts
2062
- var import_type_graphql2 = require("type-graphql");
2063
- var MessageRole;
2064
- (function(MessageRole2) {
2065
- MessageRole2["user"] = "user";
2066
- MessageRole2["assistant"] = "assistant";
2067
- MessageRole2["system"] = "system";
2068
- })(MessageRole || (MessageRole = {}));
2069
- var ActionExecutionScope;
2070
- (function(ActionExecutionScope2) {
2071
- ActionExecutionScope2["server"] = "server";
2072
- ActionExecutionScope2["client"] = "client";
2073
- ActionExecutionScope2["passThrough"] = "passThrough";
2074
- })(ActionExecutionScope || (ActionExecutionScope = {}));
2075
- var CopilotRequestType;
2076
- (function(CopilotRequestType2) {
2077
- CopilotRequestType2["Chat"] = "Chat";
2078
- CopilotRequestType2["Task"] = "Task";
2079
- CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
2080
- CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
2081
- CopilotRequestType2["Suggestion"] = "Suggestion";
2082
- })(CopilotRequestType || (CopilotRequestType = {}));
2083
- (0, import_type_graphql2.registerEnumType)(MessageRole, {
2084
- name: "MessageRole",
2085
- description: "The role of the message"
2086
- });
2087
- (0, import_type_graphql2.registerEnumType)(ActionExecutionScope, {
2088
- name: "ActionExecutionScope",
2089
- description: "The scope of the action"
2090
- });
2091
- (0, import_type_graphql2.registerEnumType)(CopilotRequestType, {
2092
- name: "CopilotRequestType",
2093
- description: "The type of Copilot request"
2094
- });
2095
-
2096
- // src/graphql/inputs/message.input.ts
2097
2636
  function _ts_decorate2(decorators, target, key, desc) {
2098
2637
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2099
2638
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -3750,6 +4289,7 @@ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
3750
4289
  UnifyAdapter,
3751
4290
  buildSchema,
3752
4291
  config,
4292
+ copilotKitEndpoint,
3753
4293
  copilotRuntimeNestEndpoint,
3754
4294
  copilotRuntimeNextJSAppRouterEndpoint,
3755
4295
  copilotRuntimeNextJSPagesRouterEndpoint,
@@ -3757,6 +4297,7 @@ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
3757
4297
  copilotRuntimeNodeHttpEndpoint,
3758
4298
  createContext,
3759
4299
  flattenToolCallsNoDuplicates,
3760
- getCommonConfig
4300
+ getCommonConfig,
4301
+ langGraphCloudEndpoint
3761
4302
  });
3762
4303
  //# sourceMappingURL=index.js.map