@copilotkit/runtime 1.3.12 → 1.3.14-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 +16 -0
  2. package/dist/{chunk-WBLYFYMZ.mjs → chunk-44JZSRY7.mjs} +2 -2
  3. package/dist/{chunk-PRG6VWHR.mjs → chunk-7MKHQGLE.mjs} +2 -2
  4. package/dist/{chunk-MYZHUCL6.mjs → chunk-B74M7FXG.mjs} +1 -1
  5. package/dist/chunk-B74M7FXG.mjs.map +1 -0
  6. package/dist/{chunk-ZEHCLFJ2.mjs → chunk-CPAHDRLS.mjs} +28 -4
  7. package/dist/chunk-CPAHDRLS.mjs.map +1 -0
  8. package/dist/{chunk-IZP72K7I.mjs → chunk-PY76HMMJ.mjs} +2 -2
  9. package/dist/{chunk-IXVCESAR.mjs → chunk-UF6TJDZ5.mjs} +37 -10
  10. package/dist/chunk-UF6TJDZ5.mjs.map +1 -0
  11. package/dist/{chunk-24WEOOFX.mjs → chunk-Y6RQG5HF.mjs} +2 -2
  12. package/dist/{chunk-F2KJWMGD.mjs → chunk-ZIHDDSMJ.mjs} +690 -152
  13. package/dist/chunk-ZIHDDSMJ.mjs.map +1 -0
  14. package/dist/{copilot-runtime-df3527ad.d.ts → copilot-runtime-68acb673.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-c2e65c95.d.ts} +1 -1
  19. package/dist/{index-cff31380.d.ts → index-439dfa2a.d.ts} +1 -1
  20. package/dist/index.d.ts +4 -4
  21. package/dist/index.js +788 -199
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +14 -10
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/{langserve-a14a6849.d.ts → langserve-0d844922.d.ts} +1 -1
  26. package/dist/lib/index.d.ts +4 -4
  27. package/dist/lib/index.js +788 -199
  28. package/dist/lib/index.js.map +1 -1
  29. package/dist/lib/index.mjs +14 -10
  30. package/dist/lib/integrations/index.d.ts +4 -4
  31. package/dist/lib/integrations/index.js +3 -1
  32. package/dist/lib/integrations/index.js.map +1 -1
  33. package/dist/lib/integrations/index.mjs +6 -6
  34. package/dist/lib/integrations/nest/index.d.ts +3 -3
  35. package/dist/lib/integrations/nest/index.js +3 -1
  36. package/dist/lib/integrations/nest/index.js.map +1 -1
  37. package/dist/lib/integrations/nest/index.mjs +4 -4
  38. package/dist/lib/integrations/node-express/index.d.ts +3 -3
  39. package/dist/lib/integrations/node-express/index.js +3 -1
  40. package/dist/lib/integrations/node-express/index.js.map +1 -1
  41. package/dist/lib/integrations/node-express/index.mjs +4 -4
  42. package/dist/lib/integrations/node-http/index.d.ts +3 -3
  43. package/dist/lib/integrations/node-http/index.js +3 -1
  44. package/dist/lib/integrations/node-http/index.js.map +1 -1
  45. package/dist/lib/integrations/node-http/index.mjs +3 -3
  46. package/dist/service-adapters/index.d.ts +4 -4
  47. package/dist/service-adapters/index.js +27 -3
  48. package/dist/service-adapters/index.js.map +1 -1
  49. package/dist/service-adapters/index.mjs +2 -2
  50. package/package.json +6 -4
  51. package/src/agents/langgraph/event-source.ts +62 -94
  52. package/src/agents/langgraph/events.ts +26 -17
  53. package/src/graphql/types/converted/index.ts +5 -1
  54. package/src/lib/runtime/copilot-runtime.ts +58 -11
  55. package/src/lib/runtime/remote-action-constructors.ts +284 -0
  56. package/src/lib/runtime/remote-actions.ts +65 -159
  57. package/src/lib/runtime/remote-lg-cloud-action.ts +624 -0
  58. package/src/service-adapters/langchain/utils.ts +31 -3
  59. package/dist/chunk-F2KJWMGD.mjs.map +0 -1
  60. package/dist/chunk-IXVCESAR.mjs.map +0 -1
  61. package/dist/chunk-MYZHUCL6.mjs.map +0 -1
  62. package/dist/chunk-ZEHCLFJ2.mjs.map +0 -1
  63. /package/dist/{chunk-WBLYFYMZ.mjs.map → chunk-44JZSRY7.mjs.map} +0 -0
  64. /package/dist/{chunk-PRG6VWHR.mjs.map → chunk-7MKHQGLE.mjs.map} +0 -0
  65. /package/dist/{chunk-IZP72K7I.mjs.map → chunk-PY76HMMJ.mjs.map} +0 -0
  66. /package/dist/{chunk-24WEOOFX.mjs.map → chunk-Y6RQG5HF.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.12",
47
+ version: "1.3.14-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
 
@@ -577,20 +581,39 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
577
581
  maybeSendActionExecutionResultIsMessage(eventStream$, actionExecution);
578
582
  let reader = result.getReader();
579
583
  let mode = null;
584
+ const toolCallDetails = {
585
+ name: null,
586
+ id: null,
587
+ index: null,
588
+ prevIndex: null
589
+ };
580
590
  while (true) {
581
591
  try {
582
592
  const { done, value } = await reader.read();
583
593
  let toolCallName = void 0;
584
594
  let toolCallId = void 0;
585
595
  let toolCallArgs = void 0;
596
+ let toolCallIndex = void 0;
597
+ let toolCallPrevIndex = void 0;
586
598
  let hasToolCall = false;
587
599
  let content = value == null ? void 0 : value.content;
588
600
  if (isAIMessageChunk(value)) {
589
601
  let chunk = (_d = value.tool_call_chunks) == null ? void 0 : _d[0];
590
- toolCallName = chunk == null ? void 0 : chunk.name;
591
- toolCallId = chunk == null ? void 0 : chunk.id;
592
602
  toolCallArgs = chunk == null ? void 0 : chunk.args;
593
603
  hasToolCall = chunk != void 0;
604
+ if (chunk == null ? void 0 : chunk.name)
605
+ toolCallDetails.name = chunk.name;
606
+ if ((chunk == null ? void 0 : chunk.index) != null) {
607
+ toolCallDetails.index = chunk.index;
608
+ if (toolCallDetails.prevIndex == null)
609
+ toolCallDetails.prevIndex = chunk.index;
610
+ }
611
+ if (chunk == null ? void 0 : chunk.id)
612
+ toolCallDetails.id = chunk.index != null ? `${chunk.id}-idx-${chunk.index}` : chunk.id;
613
+ toolCallName = toolCallDetails.name;
614
+ toolCallId = toolCallDetails.id;
615
+ toolCallIndex = toolCallDetails.index;
616
+ toolCallPrevIndex = toolCallDetails.prevIndex;
594
617
  } else if (isBaseMessageChunk(value)) {
595
618
  let chunk = (_f = (_e = value.additional_kwargs) == null ? void 0 : _e.tool_calls) == null ? void 0 : _f[0];
596
619
  toolCallName = (_g = chunk == null ? void 0 : chunk.function) == null ? void 0 : _g.name;
@@ -609,7 +632,7 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
609
632
  break;
610
633
  }
611
634
  if (mode === null) {
612
- if (hasToolCall) {
635
+ if (hasToolCall && toolCallId && toolCallName) {
613
636
  mode = "function";
614
637
  eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
615
638
  } else if (content) {
@@ -620,6 +643,11 @@ async function streamLangChainResponse({ result, eventStream$, actionExecution }
620
643
  if (mode === "message" && content) {
621
644
  eventStream$.sendTextMessageContent(Array.isArray(content) ? ((_i = content[0]) == null ? void 0 : _i.text) ?? "" : content);
622
645
  } else if (mode === "function" && toolCallArgs) {
646
+ if (toolCallIndex !== toolCallPrevIndex) {
647
+ eventStream$.sendActionExecutionEnd();
648
+ eventStream$.sendActionExecutionStart(toolCallId, toolCallName);
649
+ toolCallDetails.prevIndex = toolCallDetails.index;
650
+ }
623
651
  eventStream$.sendActionExecutionArgs(toolCallArgs);
624
652
  }
625
653
  } catch (error) {
@@ -1060,58 +1088,19 @@ var LangGraphEventTypes;
1060
1088
  LangGraphEventTypes2["OnToolStart"] = "on_tool_start";
1061
1089
  LangGraphEventTypes2["OnToolEnd"] = "on_tool_end";
1062
1090
  LangGraphEventTypes2["OnCopilotKitStateSync"] = "on_copilotkit_state_sync";
1063
- LangGraphEventTypes2["OnCopilotKitEmitMessage"] = "on_copilotkit_emit_message";
1064
- LangGraphEventTypes2["OnCopilotKitEmitToolCall"] = "on_copilotkit_emit_tool_call";
1091
+ LangGraphEventTypes2["OnCustomEvent"] = "on_custom_event";
1065
1092
  })(LangGraphEventTypes || (LangGraphEventTypes = {}));
1093
+ var CustomEventNames;
1094
+ (function(CustomEventNames2) {
1095
+ CustomEventNames2["CopilotKitManuallyEmitMessage"] = "copilotkit_manually_emit_message";
1096
+ CustomEventNames2["CopilotKitManuallyEmitToolCall"] = "copilotkit_manually_emit_tool_call";
1097
+ CustomEventNames2["CopilotKitManuallyEmitIntermediateState"] = "copilotkit_manually_emit_intermediate_state";
1098
+ })(CustomEventNames || (CustomEventNames = {}));
1066
1099
 
1067
1100
  // src/agents/langgraph/event-source.ts
1068
1101
  var import_shared7 = require("@copilotkit/shared");
1069
1102
  var RemoteLangGraphEventSource = class {
1070
1103
  eventStream$ = new import_rxjs.ReplaySubject();
1071
- async streamResponse(response) {
1072
- const reader = response.body.getReader();
1073
- const decoder = new TextDecoder();
1074
- let buffer = [];
1075
- const eventStream$ = this.eventStream$;
1076
- function flushBuffer() {
1077
- const currentBuffer = buffer.join("");
1078
- if (currentBuffer.trim().length === 0) {
1079
- return;
1080
- }
1081
- const parts = currentBuffer.split("\n");
1082
- if (parts.length === 0) {
1083
- return;
1084
- }
1085
- const lastPartIsComplete = currentBuffer.endsWith("\n");
1086
- buffer = [];
1087
- if (!lastPartIsComplete) {
1088
- buffer.push(parts.pop());
1089
- }
1090
- parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1091
- eventStream$.next(JSON.parse(part));
1092
- });
1093
- }
1094
- __name(flushBuffer, "flushBuffer");
1095
- try {
1096
- while (true) {
1097
- const { done, value } = await reader.read();
1098
- if (!done) {
1099
- buffer.push(decoder.decode(value, {
1100
- stream: true
1101
- }));
1102
- }
1103
- flushBuffer();
1104
- if (done) {
1105
- break;
1106
- }
1107
- }
1108
- } catch (error) {
1109
- console.error("Error in stream", error);
1110
- eventStream$.error(error);
1111
- return;
1112
- }
1113
- eventStream$.complete();
1114
- }
1115
1104
  shouldEmitToolCall(shouldEmitToolCalls, toolCallName) {
1116
1105
  if (typeof shouldEmitToolCalls === "boolean") {
1117
1106
  return shouldEmitToolCalls;
@@ -1134,20 +1123,25 @@ var RemoteLangGraphEventSource = class {
1134
1123
  } else {
1135
1124
  acc.content = null;
1136
1125
  }
1137
- if ((_h = (_g = (_f = event.data) == null ? void 0 : _f.chunk) == null ? void 0 : _g.kwargs) == null ? void 0 : _h.tool_call_chunks) {
1126
+ const toolCallChunks = (
1127
+ // @ts-expect-error -- LangGraph Cloud implementation stores data outside of kwargs
1128
+ ((_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)
1129
+ );
1130
+ 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);
1131
+ if (toolCallChunks && toolCallChunks.length > 0) {
1138
1132
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1139
- acc.toolCallMessageId = (_i = event.data.chunk.kwargs) == null ? void 0 : _i.id;
1140
- if ((_j = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _j.name) {
1141
- acc.toolCallName = event.data.chunk.kwargs.tool_call_chunks[0].name;
1133
+ acc.toolCallMessageId = toolCallMessageId;
1134
+ if ((_p = toolCallChunks[0]) == null ? void 0 : _p.name) {
1135
+ acc.toolCallName = toolCallChunks[0].name;
1142
1136
  }
1143
- if ((_k = event.data.chunk.kwargs.tool_call_chunks[0]) == null ? void 0 : _k.id) {
1144
- acc.toolCallId = event.data.chunk.kwargs.tool_call_chunks[0].id;
1137
+ if ((_q = toolCallChunks[0]) == null ? void 0 : _q.id) {
1138
+ acc.toolCallId = toolCallChunks[0].id;
1145
1139
  }
1146
1140
  acc.prevMessageId = acc.messageId;
1147
- acc.messageId = (_n = (_m = (_l = event.data) == null ? void 0 : _l.chunk) == null ? void 0 : _m.kwargs) == null ? void 0 : _n.id;
1141
+ acc.messageId = toolCallMessageId;
1148
1142
  } else if (acc.content && acc.content != "") {
1149
1143
  acc.prevMessageId = acc.messageId;
1150
- acc.messageId = (_q = (_p = (_o = event.data) == null ? void 0 : _o.chunk) == null ? void 0 : _p.kwargs) == null ? void 0 : _q.id;
1144
+ acc.messageId = toolCallMessageId;
1151
1145
  } else {
1152
1146
  acc.prevToolCallMessageId = acc.toolCallMessageId;
1153
1147
  acc.prevMessageId = acc.messageId;
@@ -1172,7 +1166,7 @@ var RemoteLangGraphEventSource = class {
1172
1166
  prevMessageId: null,
1173
1167
  content: null
1174
1168
  }), (0, import_rxjs.mergeMap)((eventWithState) => {
1175
- var _a, _b, _c, _d, _e;
1169
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1176
1170
  const events = [];
1177
1171
  let shouldEmitMessages = true;
1178
1172
  let shouldEmitToolCalls = false;
@@ -1195,32 +1189,33 @@ var RemoteLangGraphEventSource = class {
1195
1189
  });
1196
1190
  }
1197
1191
  switch (eventWithState.event.event) {
1198
- case LangGraphEventTypes.OnCopilotKitEmitMessage:
1199
- events.push({
1200
- type: RuntimeEventTypes.TextMessageStart,
1201
- messageId: eventWithState.event.message_id
1202
- });
1203
- events.push({
1204
- type: RuntimeEventTypes.TextMessageContent,
1205
- content: eventWithState.event.message
1206
- });
1207
- events.push({
1208
- type: RuntimeEventTypes.TextMessageEnd
1209
- });
1210
- break;
1211
- case LangGraphEventTypes.OnCopilotKitEmitToolCall:
1212
- events.push({
1213
- type: RuntimeEventTypes.ActionExecutionStart,
1214
- actionExecutionId: eventWithState.event.id,
1215
- actionName: eventWithState.event.name
1216
- });
1217
- events.push({
1218
- type: RuntimeEventTypes.ActionExecutionArgs,
1219
- args: JSON.stringify(eventWithState.event.args)
1220
- });
1221
- events.push({
1222
- type: RuntimeEventTypes.ActionExecutionEnd
1223
- });
1192
+ case LangGraphEventTypes.OnCustomEvent:
1193
+ if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitMessage) {
1194
+ events.push({
1195
+ type: RuntimeEventTypes.TextMessageStart,
1196
+ messageId: eventWithState.event.data.message_id
1197
+ });
1198
+ events.push({
1199
+ type: RuntimeEventTypes.TextMessageContent,
1200
+ content: eventWithState.event.data.message
1201
+ });
1202
+ events.push({
1203
+ type: RuntimeEventTypes.TextMessageEnd
1204
+ });
1205
+ } else if (eventWithState.event.name === CustomEventNames.CopilotKitManuallyEmitToolCall) {
1206
+ events.push({
1207
+ type: RuntimeEventTypes.ActionExecutionStart,
1208
+ actionExecutionId: eventWithState.event.data.id,
1209
+ actionName: eventWithState.event.data.name
1210
+ });
1211
+ events.push({
1212
+ type: RuntimeEventTypes.ActionExecutionArgs,
1213
+ args: JSON.stringify(eventWithState.event.data.args)
1214
+ });
1215
+ events.push({
1216
+ type: RuntimeEventTypes.ActionExecutionEnd
1217
+ });
1218
+ }
1224
1219
  break;
1225
1220
  case LangGraphEventTypes.OnCopilotKitStateSync:
1226
1221
  events.push({
@@ -1255,7 +1250,8 @@ var RemoteLangGraphEventSource = class {
1255
1250
  });
1256
1251
  }
1257
1252
  }
1258
- 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;
1253
+ 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
1254
+ ((_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);
1259
1255
  const content = eventWithState.content;
1260
1256
  if (args) {
1261
1257
  if (this.shouldEmitToolCall(shouldEmitToolCalls, eventWithState.toolCallName)) {
@@ -1306,70 +1302,543 @@ var RemoteLangGraphEventSource = class {
1306
1302
  };
1307
1303
  __name(RemoteLangGraphEventSource, "RemoteLangGraphEventSource");
1308
1304
 
1309
- // src/lib/runtime/remote-actions.ts
1310
- function isLangGraphAgentAction(action) {
1311
- if (!action) {
1312
- return false;
1313
- }
1314
- return typeof action.langGraphAgentHandler === "function";
1305
+ // src/lib/runtime/remote-lg-cloud-action.ts
1306
+ var import_langgraph_sdk = require("@langchain/langgraph-sdk");
1307
+ var import_node_crypto = require("crypto");
1308
+ var import_partial_json = require("partial-json");
1309
+
1310
+ // src/graphql/types/enums.ts
1311
+ var import_type_graphql = require("type-graphql");
1312
+ var MessageRole;
1313
+ (function(MessageRole2) {
1314
+ MessageRole2["user"] = "user";
1315
+ MessageRole2["assistant"] = "assistant";
1316
+ MessageRole2["system"] = "system";
1317
+ })(MessageRole || (MessageRole = {}));
1318
+ var ActionExecutionScope;
1319
+ (function(ActionExecutionScope2) {
1320
+ ActionExecutionScope2["server"] = "server";
1321
+ ActionExecutionScope2["client"] = "client";
1322
+ ActionExecutionScope2["passThrough"] = "passThrough";
1323
+ })(ActionExecutionScope || (ActionExecutionScope = {}));
1324
+ var CopilotRequestType;
1325
+ (function(CopilotRequestType2) {
1326
+ CopilotRequestType2["Chat"] = "Chat";
1327
+ CopilotRequestType2["Task"] = "Task";
1328
+ CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
1329
+ CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
1330
+ CopilotRequestType2["Suggestion"] = "Suggestion";
1331
+ })(CopilotRequestType || (CopilotRequestType = {}));
1332
+ (0, import_type_graphql.registerEnumType)(MessageRole, {
1333
+ name: "MessageRole",
1334
+ description: "The role of the message"
1335
+ });
1336
+ (0, import_type_graphql.registerEnumType)(ActionExecutionScope, {
1337
+ name: "ActionExecutionScope",
1338
+ description: "The scope of the action"
1339
+ });
1340
+ (0, import_type_graphql.registerEnumType)(CopilotRequestType, {
1341
+ name: "CopilotRequestType",
1342
+ description: "The type of Copilot request"
1343
+ });
1344
+
1345
+ // src/lib/runtime/remote-lg-cloud-action.ts
1346
+ async function execute(args) {
1347
+ return new ReadableStream({
1348
+ async start(controller) {
1349
+ try {
1350
+ await streamEvents(controller, args);
1351
+ controller.close();
1352
+ } catch (err) {
1353
+ }
1354
+ }
1355
+ });
1315
1356
  }
1316
- __name(isLangGraphAgentAction, "isLangGraphAgentAction");
1317
- function createHeaders(onBeforeRequest, graphqlContext) {
1318
- const headers = {
1319
- "Content-Type": "application/json"
1357
+ __name(execute, "execute");
1358
+ async function streamEvents(controller, args) {
1359
+ const { deploymentUrl, langsmithApiKey, threadId: agrsInitialThreadId, agent, nodeName: initialNodeName, state: initialState, messages, actions, logger: logger2 } = args;
1360
+ let nodeName = initialNodeName;
1361
+ let state = initialState;
1362
+ const { name, assistantId: initialAssistantId } = agent;
1363
+ const client = new import_langgraph_sdk.Client({
1364
+ apiUrl: deploymentUrl,
1365
+ apiKey: langsmithApiKey
1366
+ });
1367
+ let initialThreadId = agrsInitialThreadId;
1368
+ const wasInitiatedWithExistingThread = !!initialThreadId;
1369
+ if (initialThreadId && initialThreadId.startsWith("ck-")) {
1370
+ initialThreadId = initialThreadId.substring(3);
1371
+ }
1372
+ const assistants = await client.assistants.search();
1373
+ const retrievedAssistant = assistants.find((a) => a.name === name);
1374
+ const threadId = initialThreadId ?? (0, import_node_crypto.randomUUID)();
1375
+ if (initialThreadId === threadId) {
1376
+ await client.threads.get(threadId);
1377
+ } else {
1378
+ await client.threads.create({
1379
+ threadId
1380
+ });
1381
+ }
1382
+ let agentState = {
1383
+ values: {}
1320
1384
  };
1321
- if (onBeforeRequest) {
1322
- const { headers: additionalHeaders } = onBeforeRequest({
1323
- ctx: graphqlContext
1385
+ if (wasInitiatedWithExistingThread) {
1386
+ agentState = await client.threads.getState(threadId);
1387
+ }
1388
+ const agentStateValues = agentState.values;
1389
+ state.messages = agentStateValues.messages;
1390
+ const mode = wasInitiatedWithExistingThread && nodeName != "__end__" ? "continue" : "start";
1391
+ state = langGraphDefaultMergeState(state, formatMessages(messages), actions, name);
1392
+ if (mode === "continue") {
1393
+ await client.threads.updateState(threadId, {
1394
+ values: state,
1395
+ asNode: nodeName
1324
1396
  });
1325
- if (additionalHeaders) {
1326
- Object.assign(headers, additionalHeaders);
1397
+ }
1398
+ const assistantId = initialAssistantId ?? (retrievedAssistant == null ? void 0 : retrievedAssistant.assistant_id);
1399
+ if (!assistantId) {
1400
+ console.error(`
1401
+ No agent found for the agent name specified in CopilotKit provider
1402
+ Please check your available agents or provide an agent ID in the LangGraph Cloud endpoint definition.
1403
+
1404
+
1405
+ These are the available agents: [${assistants.map((a) => `${a.name} (ID: ${a.assistant_id})`).join(", ")}]
1406
+ `);
1407
+ throw new Error("No agent id found");
1408
+ }
1409
+ const graphInfo = await client.assistants.getGraph(assistantId);
1410
+ const streamInput = mode === "start" ? state : null;
1411
+ let streamingStateExtractor = new StreamingStateExtractor([]);
1412
+ let prevNodeName = null;
1413
+ let emitIntermediateStateUntilEnd = null;
1414
+ let shouldExit = null;
1415
+ let externalRunId = null;
1416
+ const streamResponse2 = client.runs.stream(threadId, assistantId, {
1417
+ input: streamInput,
1418
+ streamMode: [
1419
+ "events",
1420
+ "values"
1421
+ ]
1422
+ });
1423
+ const emit = /* @__PURE__ */ __name((message) => controller.enqueue(new TextEncoder().encode(message)), "emit");
1424
+ let latestStateValues = {};
1425
+ for await (const chunk of streamResponse2) {
1426
+ if (![
1427
+ "events",
1428
+ "values",
1429
+ "error"
1430
+ ].includes(chunk.event))
1431
+ continue;
1432
+ if (chunk.event === "error") {
1433
+ logger2.error(chunk, `Error event thrown: ${chunk.data.message}`);
1434
+ throw new Error(`Error event thrown: ${chunk.data.message}`);
1435
+ }
1436
+ if (chunk.event === "values") {
1437
+ latestStateValues = chunk.data;
1438
+ continue;
1439
+ }
1440
+ const event = chunk.data;
1441
+ const currentNodeName = event.name;
1442
+ const eventType = event.event;
1443
+ const runId = event.metadata.run_id;
1444
+ externalRunId = runId;
1445
+ const metadata = event.metadata;
1446
+ shouldExit = shouldExit != null ? shouldExit : metadata["copilotkit:exit"];
1447
+ const emitIntermediateState = metadata["copilotkit:emit-intermediate-state"];
1448
+ const forceEmitIntermediateState = metadata["copilotkit:force-emit-intermediate-state"];
1449
+ const manuallyEmitMessage = metadata["copilotkit:manually-emit-messages"];
1450
+ const manuallyEmitToolCall = metadata["copilotkit:manually-emit-tool-calls"];
1451
+ if (graphInfo["nodes"].some((node) => node.id === currentNodeName)) {
1452
+ nodeName = currentNodeName;
1327
1453
  }
1454
+ if (!nodeName) {
1455
+ continue;
1456
+ }
1457
+ if (forceEmitIntermediateState) {
1458
+ if (eventType === "on_chain_end") {
1459
+ state = event.data.output;
1460
+ emit(getStateSyncEvent({
1461
+ threadId,
1462
+ runId,
1463
+ agentName: agent.name,
1464
+ nodeName,
1465
+ state: event.data.output,
1466
+ running: true,
1467
+ active: true
1468
+ }));
1469
+ }
1470
+ continue;
1471
+ }
1472
+ if (manuallyEmitMessage) {
1473
+ if (eventType === "on_chain_end") {
1474
+ state = event.data.output;
1475
+ emit(JSON.stringify({
1476
+ event: "on_copilotkit_emit_message",
1477
+ message: event.data.output,
1478
+ messageId: (0, import_node_crypto.randomUUID)(),
1479
+ role: MessageRole.assistant
1480
+ }) + "\n");
1481
+ }
1482
+ continue;
1483
+ }
1484
+ if (manuallyEmitToolCall) {
1485
+ if (eventType === "on_chain_end") {
1486
+ state = event.data.output;
1487
+ emit(JSON.stringify({
1488
+ event: "on_copilotkit_emit_tool_call",
1489
+ name: event.data.output.name,
1490
+ args: event.data.output.args,
1491
+ id: event.data.output.id
1492
+ }) + "\n");
1493
+ }
1494
+ continue;
1495
+ }
1496
+ if (emitIntermediateState && emitIntermediateStateUntilEnd == null) {
1497
+ emitIntermediateStateUntilEnd = nodeName;
1498
+ }
1499
+ if (emitIntermediateState && eventType === "on_chat_model_start") {
1500
+ streamingStateExtractor = new StreamingStateExtractor(emitIntermediateState);
1501
+ }
1502
+ let updatedState = latestStateValues;
1503
+ if (emitIntermediateState && eventType === "on_chat_model_stream") {
1504
+ streamingStateExtractor.bufferToolCalls(event);
1505
+ }
1506
+ if (emitIntermediateStateUntilEnd !== null) {
1507
+ updatedState = {
1508
+ ...updatedState,
1509
+ ...streamingStateExtractor.extractState()
1510
+ };
1511
+ }
1512
+ if (!emitIntermediateState && currentNodeName === emitIntermediateStateUntilEnd && eventType === "on_chain_end") {
1513
+ emitIntermediateStateUntilEnd = null;
1514
+ }
1515
+ const exitingNode = nodeName === currentNodeName && eventType === "on_chain_end";
1516
+ if (JSON.stringify(updatedState) !== JSON.stringify(state) || prevNodeName != nodeName || exitingNode) {
1517
+ state = updatedState;
1518
+ prevNodeName = nodeName;
1519
+ emit(getStateSyncEvent({
1520
+ threadId,
1521
+ runId,
1522
+ agentName: agent.name,
1523
+ nodeName,
1524
+ state,
1525
+ running: true,
1526
+ active: !exitingNode
1527
+ }));
1528
+ }
1529
+ emit(JSON.stringify(event) + "\n");
1328
1530
  }
1329
- return headers;
1531
+ state = await client.threads.getState(threadId);
1532
+ const isEndNode = state.next.length === 0;
1533
+ nodeName = Object.keys(state.metadata.writes)[0];
1534
+ emit(getStateSyncEvent({
1535
+ threadId,
1536
+ runId: externalRunId,
1537
+ agentName: agent.name,
1538
+ nodeName: isEndNode ? "__end__" : nodeName,
1539
+ state: state.values,
1540
+ running: !shouldExit,
1541
+ active: false
1542
+ }));
1543
+ return Promise.resolve();
1330
1544
  }
1331
- __name(createHeaders, "createHeaders");
1332
- async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
1333
- logger2.debug({
1334
- url
1335
- }, "Fetching actions from url");
1336
- const headers = createHeaders(onBeforeRequest, graphqlContext);
1337
- try {
1338
- const response = await fetch(`${url}/info`, {
1339
- method: "POST",
1340
- headers,
1341
- body: JSON.stringify({
1342
- properties: graphqlContext.properties,
1343
- frontendUrl
1344
- })
1345
- });
1346
- if (!response.ok) {
1347
- logger2.error({
1348
- url,
1349
- status: response.status,
1350
- body: await response.text()
1351
- }, "Failed to fetch actions from url");
1545
+ __name(streamEvents, "streamEvents");
1546
+ function getStateSyncEvent({ threadId, runId, agentName, nodeName, state, running, active }) {
1547
+ const stateWithoutMessages = Object.keys(state).reduce((acc, key) => {
1548
+ if (key !== "messages") {
1549
+ acc[key] = state[key];
1550
+ }
1551
+ return acc;
1552
+ }, {});
1553
+ return JSON.stringify({
1554
+ event: "on_copilotkit_state_sync",
1555
+ thread_id: threadId,
1556
+ run_id: runId,
1557
+ agent_name: agentName,
1558
+ node_name: nodeName,
1559
+ active,
1560
+ state: stateWithoutMessages,
1561
+ running,
1562
+ role: "assistant"
1563
+ }) + "\n";
1564
+ }
1565
+ __name(getStateSyncEvent, "getStateSyncEvent");
1566
+ var StreamingStateExtractor = /* @__PURE__ */ __name(class StreamingStateExtractor2 {
1567
+ emitIntermediateState;
1568
+ toolCallBuffer;
1569
+ currentToolCall;
1570
+ previouslyParsableState;
1571
+ constructor(emitIntermediateState) {
1572
+ this.emitIntermediateState = emitIntermediateState;
1573
+ this.toolCallBuffer = {};
1574
+ this.currentToolCall = null;
1575
+ this.previouslyParsableState = {};
1576
+ }
1577
+ bufferToolCalls(event) {
1578
+ if (event.data.chunk.tool_call_chunks.length > 0) {
1579
+ const chunk = event.data.chunk.tool_call_chunks[0];
1580
+ if (chunk.name !== null) {
1581
+ this.currentToolCall = chunk.name;
1582
+ this.toolCallBuffer[this.currentToolCall] = chunk.args;
1583
+ } else if (this.currentToolCall !== null) {
1584
+ this.toolCallBuffer[this.currentToolCall] += chunk.args;
1585
+ }
1586
+ }
1587
+ }
1588
+ getEmitStateConfig(currentToolName) {
1589
+ for (const config2 of this.emitIntermediateState) {
1590
+ const stateKey = config2["state_key"];
1591
+ const tool = config2["tool"];
1592
+ const toolArgument = config2["tool_argument"];
1593
+ if (currentToolName === tool) {
1594
+ return [
1595
+ toolArgument,
1596
+ stateKey
1597
+ ];
1598
+ }
1599
+ }
1600
+ return [
1601
+ null,
1602
+ null
1603
+ ];
1604
+ }
1605
+ extractState() {
1606
+ const state = {};
1607
+ for (const [key, value] of Object.entries(this.toolCallBuffer)) {
1608
+ const [argumentName, stateKey] = this.getEmitStateConfig(key);
1609
+ if (stateKey === null) {
1610
+ continue;
1611
+ }
1612
+ let parsedValue;
1613
+ try {
1614
+ parsedValue = (0, import_partial_json.parse)(value);
1615
+ } catch (error) {
1616
+ if (key in this.previouslyParsableState) {
1617
+ parsedValue = this.previouslyParsableState[key];
1618
+ } else {
1619
+ continue;
1620
+ }
1621
+ }
1622
+ this.previouslyParsableState[key] = parsedValue;
1623
+ if (!argumentName) {
1624
+ state[stateKey] = parsedValue;
1625
+ } else {
1626
+ state[stateKey] = parsedValue[argumentName];
1627
+ }
1628
+ }
1629
+ return state;
1630
+ }
1631
+ }, "StreamingStateExtractor");
1632
+ function langGraphDefaultMergeState(state, messages, actions, agentName) {
1633
+ if (messages.length > 0 && "role" in messages[0] && messages[0].role === "system") {
1634
+ messages = messages.slice(1);
1635
+ }
1636
+ const mergedMessages = state.messages || [];
1637
+ const existingMessageIds = new Set(mergedMessages.map((message) => message.id));
1638
+ const existingToolCallResults = /* @__PURE__ */ new Set();
1639
+ for (const message of mergedMessages) {
1640
+ if ("tool_call_id" in message) {
1641
+ existingToolCallResults.add(message.tool_call_id);
1642
+ }
1643
+ }
1644
+ for (const message of messages) {
1645
+ if ("tool_calls" in message && message.tool_calls.length > 0 && message.tool_calls[0].name === agentName) {
1646
+ continue;
1647
+ }
1648
+ if ("name" in message && message.name === agentName) {
1649
+ continue;
1650
+ }
1651
+ if (!existingMessageIds.has(message.id)) {
1652
+ if ("tool_call_id" in message && existingToolCallResults.has(message.tool_call_id)) {
1653
+ console.warn("Warning: Duplicate tool call result, skipping:", message.tool_call_id);
1654
+ continue;
1655
+ }
1656
+ mergedMessages.push(message);
1657
+ } else {
1658
+ for (let i = 0; i < mergedMessages.length; i++) {
1659
+ if (mergedMessages[i].id === message.id) {
1660
+ if ("tool_calls" in message) {
1661
+ if (("tool_calls" in mergedMessages[i] || "additional_kwargs" in mergedMessages[i]) && mergedMessages[i].content) {
1662
+ message.tool_calls = mergedMessages[i]["tool_calls"];
1663
+ message.additional_kwargs = mergedMessages[i].additional_kwargs;
1664
+ }
1665
+ }
1666
+ mergedMessages[i] = message;
1667
+ }
1668
+ }
1669
+ }
1670
+ }
1671
+ for (let i = 0; i < mergedMessages.length - 1; i++) {
1672
+ const currentMessage = mergedMessages[i];
1673
+ const nextMessage = mergedMessages[i + 1];
1674
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0 && "tool_call_id" in nextMessage) {
1675
+ nextMessage.tool_call_id = currentMessage.tool_calls[0].id;
1676
+ }
1677
+ }
1678
+ const correctedMessages = [];
1679
+ for (let i = 0; i < mergedMessages.length; i++) {
1680
+ const currentMessage = mergedMessages[i];
1681
+ const nextMessage = mergedMessages[i + 1] || null;
1682
+ const prevMessage = mergedMessages[i - 1] || null;
1683
+ if ("tool_calls" in currentMessage && currentMessage.tool_calls.length > 0) {
1684
+ if (!nextMessage) {
1685
+ console.warn("No next message to auto-correct tool call, skipping:", currentMessage.tool_calls[0].id);
1686
+ continue;
1687
+ }
1688
+ if (!("tool_call_id" in nextMessage) || nextMessage.tool_call_id !== currentMessage.tool_calls[0].id) {
1689
+ const toolMessage = mergedMessages.find((m) => "tool_call_id" in m && m.tool_call_id === currentMessage.tool_calls[0].id);
1690
+ if (toolMessage) {
1691
+ console.warn("Auto-corrected tool call alignment issue:", currentMessage.tool_calls[0].id);
1692
+ correctedMessages.push(currentMessage, toolMessage);
1693
+ continue;
1694
+ } else {
1695
+ console.warn("No corresponding tool call result found for tool call, skipping:", currentMessage.tool_calls[0].id);
1696
+ continue;
1697
+ }
1698
+ }
1699
+ correctedMessages.push(currentMessage);
1700
+ continue;
1701
+ }
1702
+ if ("tool_call_id" in currentMessage) {
1703
+ if (!prevMessage || !("tool_calls" in prevMessage)) {
1704
+ console.warn("No previous tool call, skipping tool call result:", currentMessage.id);
1705
+ continue;
1706
+ }
1707
+ if (prevMessage.tool_calls && prevMessage.tool_calls[0].id !== currentMessage.tool_call_id) {
1708
+ console.warn("Tool call id is incorrect, skipping tool call result:", currentMessage.id);
1709
+ continue;
1710
+ }
1711
+ correctedMessages.push(currentMessage);
1712
+ continue;
1713
+ }
1714
+ correctedMessages.push(currentMessage);
1715
+ }
1716
+ return deepMerge(state, {
1717
+ messages: correctedMessages,
1718
+ copilotkit: {
1719
+ actions
1720
+ }
1721
+ });
1722
+ }
1723
+ __name(langGraphDefaultMergeState, "langGraphDefaultMergeState");
1724
+ function deepMerge(obj1, obj2) {
1725
+ let result = {
1726
+ ...obj1
1727
+ };
1728
+ for (let key in obj2) {
1729
+ if (typeof obj2[key] === "object" && !Array.isArray(obj2[key])) {
1730
+ if (obj1[key]) {
1731
+ result[key] = deepMerge(obj1[key], obj2[key]);
1732
+ } else {
1733
+ result[key] = {
1734
+ ...obj2[key]
1735
+ };
1736
+ }
1737
+ } else {
1738
+ result[key] = obj2[key];
1739
+ }
1740
+ }
1741
+ return result;
1742
+ }
1743
+ __name(deepMerge, "deepMerge");
1744
+ function formatMessages(messages) {
1745
+ return messages.map((message) => {
1746
+ if (message.isTextMessage() && message.role === "assistant") {
1747
+ return message;
1748
+ }
1749
+ if (message.isTextMessage() && message.role === "system") {
1750
+ return message;
1751
+ }
1752
+ if (message.isTextMessage() && message.role === "user") {
1753
+ return message;
1754
+ }
1755
+ if (message.isActionExecutionMessage()) {
1756
+ const toolCall = {
1757
+ name: message.name,
1758
+ args: message.arguments,
1759
+ id: message.id
1760
+ };
1352
1761
  return {
1353
- actions: [],
1354
- agents: []
1762
+ type: message.type,
1763
+ content: "",
1764
+ tool_calls: [
1765
+ toolCall
1766
+ ],
1767
+ role: MessageRole.assistant,
1768
+ id: message.id
1355
1769
  };
1356
1770
  }
1357
- const json = await response.json();
1358
- logger2.debug({
1359
- json
1360
- }, "Fetched actions from url");
1361
- return json;
1362
- } catch (error) {
1363
- logger2.error({
1364
- error: error.message ? error.message : error + ""
1365
- }, "Failed to fetch actions from url");
1366
- return {
1367
- actions: [],
1368
- agents: []
1369
- };
1370
- }
1771
+ if (message.isResultMessage()) {
1772
+ return {
1773
+ type: message.type,
1774
+ content: message.result,
1775
+ id: message.id,
1776
+ tool_call_id: message.actionExecutionId,
1777
+ name: message.actionName,
1778
+ role: MessageRole.assistant
1779
+ };
1780
+ }
1781
+ throw new Error(`Unknown message type ${message.type}`);
1782
+ });
1371
1783
  }
1372
- __name(fetchRemoteInfo, "fetchRemoteInfo");
1784
+ __name(formatMessages, "formatMessages");
1785
+
1786
+ // src/lib/runtime/remote-action-constructors.ts
1787
+ function constructLGCRemoteAction({ endpoint, graphqlContext, logger: logger2, messages, agentStates }) {
1788
+ const agents = endpoint.agents.map((agent) => ({
1789
+ name: agent.name,
1790
+ description: agent.description,
1791
+ parameters: [],
1792
+ handler: async (_args) => {
1793
+ },
1794
+ langGraphAgentHandler: async ({ name, actionInputsWithoutAgents, threadId, nodeName }) => {
1795
+ var _a;
1796
+ logger2.debug({
1797
+ actionName: agent.name
1798
+ }, "Executing LangGraph Cloud agent");
1799
+ telemetry_client_default.capture("oss.runtime.remote_action_executed", {});
1800
+ let state = {};
1801
+ if (agentStates) {
1802
+ const jsonState = (_a = agentStates.find((state2) => state2.agentName === name)) == null ? void 0 : _a.state;
1803
+ if (jsonState) {
1804
+ state = JSON.parse(jsonState);
1805
+ }
1806
+ }
1807
+ try {
1808
+ const response = await execute({
1809
+ logger: logger2,
1810
+ deploymentUrl: endpoint.deploymentUrl,
1811
+ langsmithApiKey: endpoint.langsmithApiKey,
1812
+ agent,
1813
+ threadId,
1814
+ nodeName,
1815
+ messages,
1816
+ state,
1817
+ properties: graphqlContext.properties,
1818
+ actions: actionInputsWithoutAgents.map((action) => ({
1819
+ name: action.name,
1820
+ description: action.description,
1821
+ parameters: JSON.parse(action.jsonSchema)
1822
+ }))
1823
+ });
1824
+ const eventSource = new RemoteLangGraphEventSource();
1825
+ streamResponse(response, eventSource.eventStream$);
1826
+ return eventSource.processLangGraphEvents();
1827
+ } catch (error) {
1828
+ logger2.error({
1829
+ url: endpoint.deploymentUrl,
1830
+ status: 500,
1831
+ body: error.message
1832
+ }, "Failed to execute LangGraph Cloud agent");
1833
+ throw new Error("Failed to execute LangGraph Cloud agent");
1834
+ }
1835
+ }
1836
+ }));
1837
+ return [
1838
+ ...agents
1839
+ ];
1840
+ }
1841
+ __name(constructLGCRemoteAction, "constructLGCRemoteAction");
1373
1842
  function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, logger: logger2, messages, agentStates }) {
1374
1843
  const actions = json["actions"].map((action) => ({
1375
1844
  name: action.name,
@@ -1461,7 +1930,7 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1461
1930
  throw new Error("Failed to execute remote agent");
1462
1931
  }
1463
1932
  const eventSource = new RemoteLangGraphEventSource();
1464
- eventSource.streamResponse(response);
1933
+ streamResponse(response.body, eventSource.eventStream$);
1465
1934
  return eventSource.processLangGraphEvents();
1466
1935
  }
1467
1936
  }));
@@ -1471,34 +1940,165 @@ function constructRemoteActions({ json, url, onBeforeRequest, graphqlContext, lo
1471
1940
  ];
1472
1941
  }
1473
1942
  __name(constructRemoteActions, "constructRemoteActions");
1474
- async function setupRemoteActions({ remoteActionDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1943
+ async function streamResponse(response, eventStream$) {
1944
+ const reader = response.getReader();
1945
+ const decoder = new TextDecoder();
1946
+ let buffer = [];
1947
+ function flushBuffer() {
1948
+ const currentBuffer = buffer.join("");
1949
+ if (currentBuffer.trim().length === 0) {
1950
+ return;
1951
+ }
1952
+ const parts = currentBuffer.split("\n");
1953
+ if (parts.length === 0) {
1954
+ return;
1955
+ }
1956
+ const lastPartIsComplete = currentBuffer.endsWith("\n");
1957
+ buffer = [];
1958
+ if (!lastPartIsComplete) {
1959
+ buffer.push(parts.pop());
1960
+ }
1961
+ parts.map((part) => part.trim()).filter((part) => part != "").forEach((part) => {
1962
+ eventStream$.next(JSON.parse(part));
1963
+ });
1964
+ }
1965
+ __name(flushBuffer, "flushBuffer");
1966
+ try {
1967
+ while (true) {
1968
+ const { done, value } = await reader.read();
1969
+ if (!done) {
1970
+ buffer.push(decoder.decode(value, {
1971
+ stream: true
1972
+ }));
1973
+ }
1974
+ flushBuffer();
1975
+ if (done) {
1976
+ break;
1977
+ }
1978
+ }
1979
+ } catch (error) {
1980
+ console.error("Error in stream", error);
1981
+ eventStream$.error(error);
1982
+ return;
1983
+ }
1984
+ eventStream$.complete();
1985
+ }
1986
+ __name(streamResponse, "streamResponse");
1987
+ function createHeaders(onBeforeRequest, graphqlContext) {
1988
+ const headers = {
1989
+ "Content-Type": "application/json"
1990
+ };
1991
+ if (onBeforeRequest) {
1992
+ const { headers: additionalHeaders } = onBeforeRequest({
1993
+ ctx: graphqlContext
1994
+ });
1995
+ if (additionalHeaders) {
1996
+ Object.assign(headers, additionalHeaders);
1997
+ }
1998
+ }
1999
+ return headers;
2000
+ }
2001
+ __name(createHeaders, "createHeaders");
2002
+
2003
+ // src/lib/runtime/remote-actions.ts
2004
+ var EndpointType;
2005
+ (function(EndpointType2) {
2006
+ EndpointType2["CopilotKit"] = "copilotKit";
2007
+ EndpointType2["LangGraphCloud"] = "langgraph-cloud";
2008
+ })(EndpointType || (EndpointType = {}));
2009
+ function isLangGraphAgentAction(action) {
2010
+ if (!action) {
2011
+ return false;
2012
+ }
2013
+ return typeof action.langGraphAgentHandler === "function";
2014
+ }
2015
+ __name(isLangGraphAgentAction, "isLangGraphAgentAction");
2016
+ async function fetchRemoteInfo({ url, onBeforeRequest, graphqlContext, logger: logger2, frontendUrl }) {
2017
+ logger2.debug({
2018
+ url
2019
+ }, "Fetching actions from url");
2020
+ const headers = createHeaders(onBeforeRequest, graphqlContext);
2021
+ try {
2022
+ const response = await fetch(`${url}/info`, {
2023
+ method: "POST",
2024
+ headers,
2025
+ body: JSON.stringify({
2026
+ properties: graphqlContext.properties,
2027
+ frontendUrl
2028
+ })
2029
+ });
2030
+ if (!response.ok) {
2031
+ logger2.error({
2032
+ url,
2033
+ status: response.status,
2034
+ body: await response.text()
2035
+ }, "Failed to fetch actions from url");
2036
+ return {
2037
+ actions: [],
2038
+ agents: []
2039
+ };
2040
+ }
2041
+ const json = await response.json();
2042
+ logger2.debug({
2043
+ json
2044
+ }, "Fetched actions from url");
2045
+ return json;
2046
+ } catch (error) {
2047
+ logger2.error({
2048
+ error: error.message ? error.message : error + ""
2049
+ }, "Failed to fetch actions from url");
2050
+ return {
2051
+ actions: [],
2052
+ agents: []
2053
+ };
2054
+ }
2055
+ }
2056
+ __name(fetchRemoteInfo, "fetchRemoteInfo");
2057
+ async function setupRemoteActions({ remoteEndpointDefinitions, graphqlContext, messages, agentStates, frontendUrl }) {
1475
2058
  const logger2 = graphqlContext.logger.child({
1476
2059
  component: "remote-actions.fetchRemoteActions"
1477
2060
  });
1478
2061
  logger2.debug({
1479
- remoteActionDefinitions
1480
- }, "Fetching remote actions");
1481
- const filtered = remoteActionDefinitions.filter((value, index, self) => index === self.findIndex((t) => t.url === value.url));
1482
- const result = await Promise.all(filtered.map(async (actionDefinition) => {
2062
+ remoteEndpointDefinitions
2063
+ }, "Fetching from remote endpoints");
2064
+ const filtered = remoteEndpointDefinitions.filter((value, index, self) => {
2065
+ if (value.type === "langgraph-cloud") {
2066
+ return value;
2067
+ }
2068
+ return index === self.findIndex((t) => t.url === value.url);
2069
+ });
2070
+ const result = await Promise.all(filtered.map(async (endpoint) => {
2071
+ if (endpoint.type === "langgraph-cloud") {
2072
+ return constructLGCRemoteAction({
2073
+ endpoint,
2074
+ messages,
2075
+ graphqlContext,
2076
+ logger: logger2.child({
2077
+ component: "remote-actions.constructLGCRemoteAction",
2078
+ endpoint
2079
+ }),
2080
+ agentStates
2081
+ });
2082
+ }
1483
2083
  const json = await fetchRemoteInfo({
1484
- url: actionDefinition.url,
1485
- onBeforeRequest: actionDefinition.onBeforeRequest,
2084
+ url: endpoint.url,
2085
+ onBeforeRequest: endpoint.onBeforeRequest,
1486
2086
  graphqlContext,
1487
2087
  logger: logger2.child({
1488
2088
  component: "remote-actions.fetchActionsFromUrl",
1489
- actionDefinition
2089
+ endpoint
1490
2090
  }),
1491
2091
  frontendUrl
1492
2092
  });
1493
2093
  return constructRemoteActions({
1494
2094
  json,
1495
2095
  messages,
1496
- url: actionDefinition.url,
1497
- onBeforeRequest: actionDefinition.onBeforeRequest,
2096
+ url: endpoint.url,
2097
+ onBeforeRequest: endpoint.onBeforeRequest,
1498
2098
  graphqlContext,
1499
2099
  logger: logger2.child({
1500
2100
  component: "remote-actions.constructActions",
1501
- actionDefinition
2101
+ endpoint
1502
2102
  }),
1503
2103
  agentStates
1504
2104
  });
@@ -1696,7 +2296,7 @@ async function executeAction(eventStream$, guardrailsResult$, action, actionArgu
1696
2296
  __name(executeAction, "executeAction");
1697
2297
 
1698
2298
  // src/graphql/types/base/index.ts
1699
- var import_type_graphql = require("type-graphql");
2299
+ var import_type_graphql2 = require("type-graphql");
1700
2300
  function _ts_decorate(decorators, target, key, desc) {
1701
2301
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1702
2302
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -1719,15 +2319,15 @@ var BaseMessageInput = class {
1719
2319
  };
1720
2320
  __name(BaseMessageInput, "BaseMessageInput");
1721
2321
  _ts_decorate([
1722
- (0, import_type_graphql.Field)(() => String),
2322
+ (0, import_type_graphql2.Field)(() => String),
1723
2323
  _ts_metadata("design:type", String)
1724
2324
  ], BaseMessageInput.prototype, "id", void 0);
1725
2325
  _ts_decorate([
1726
- (0, import_type_graphql.Field)(() => Date),
2326
+ (0, import_type_graphql2.Field)(() => Date),
1727
2327
  _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
1728
2328
  ], BaseMessageInput.prototype, "createdAt", void 0);
1729
2329
  BaseMessageInput = _ts_decorate([
1730
- (0, import_type_graphql.InputType)()
2330
+ (0, import_type_graphql2.InputType)()
1731
2331
  ], BaseMessageInput);
1732
2332
 
1733
2333
  // src/graphql/types/converted/index.ts
@@ -1831,7 +2431,7 @@ __name(convertGqlInputToMessages, "convertGqlInputToMessages");
1831
2431
  var import_rxjs3 = require("rxjs");
1832
2432
  var CopilotRuntime = class {
1833
2433
  actions;
1834
- remoteActionDefinitions;
2434
+ remoteEndpointDefinitions;
1835
2435
  langserve = [];
1836
2436
  onBeforeRequest;
1837
2437
  onAfterRequest;
@@ -1842,7 +2442,7 @@ var CopilotRuntime = class {
1842
2442
  const remoteChain = new RemoteChain(chain);
1843
2443
  this.langserve.push(remoteChain.toAction());
1844
2444
  }
1845
- this.remoteActionDefinitions = (params == null ? void 0 : params.remoteActions) || [];
2445
+ this.remoteEndpointDefinitions = (params == null ? void 0 : params.remoteEndpoints) || [];
1846
2446
  this.onBeforeRequest = (_a = params == null ? void 0 : params.middleware) == null ? void 0 : _a.onBeforeRequest;
1847
2447
  this.onAfterRequest = (_b = params == null ? void 0 : params.middleware) == null ? void 0 : _b.onAfterRequest;
1848
2448
  }
@@ -1911,7 +2511,7 @@ var CopilotRuntime = class {
1911
2511
  async processAgentRequest(request) {
1912
2512
  var _a;
1913
2513
  const { messages: rawMessages, outputMessagesPromise, graphqlContext, agentSession } = request;
1914
- const { threadId = (0, import_shared8.randomId)(), agentName, nodeName } = agentSession;
2514
+ const { threadId, agentName, nodeName } = agentSession;
1915
2515
  const serverSideActions = await this.getServerSideActions(request);
1916
2516
  const messages = convertGqlInputToMessages(rawMessages);
1917
2517
  const agent = serverSideActions.find((action) => action.name === agentName && isLangGraphAgentAction(action));
@@ -1983,8 +2583,12 @@ var CopilotRuntime = class {
1983
2583
  console.error("Error loading langserve chain:", error);
1984
2584
  }
1985
2585
  }
2586
+ const remoteEndpointDefinitions = this.remoteEndpointDefinitions.map((endpoint) => ({
2587
+ ...endpoint,
2588
+ type: this.resolveEndpointType(endpoint)
2589
+ }));
1986
2590
  const remoteActions = await setupRemoteActions({
1987
- remoteActionDefinitions: this.remoteActionDefinitions,
2591
+ remoteEndpointDefinitions,
1988
2592
  graphqlContext,
1989
2593
  messages: inputMessages,
1990
2594
  agentStates,
@@ -2000,6 +2604,12 @@ var CopilotRuntime = class {
2000
2604
  ...remoteActions
2001
2605
  ];
2002
2606
  }
2607
+ resolveEndpointType(endpoint) {
2608
+ if (!endpoint.type && "langsmithApiKey" in endpoint && "deploymentUrl" in endpoint && "agents" in endpoint) {
2609
+ return EndpointType.LangGraphCloud;
2610
+ }
2611
+ return endpoint.type;
2612
+ }
2003
2613
  };
2004
2614
  __name(CopilotRuntime, "CopilotRuntime");
2005
2615
  function flattenToolCallsNoDuplicates(toolsByPriority) {
@@ -2014,6 +2624,20 @@ function flattenToolCallsNoDuplicates(toolsByPriority) {
2014
2624
  return allTools;
2015
2625
  }
2016
2626
  __name(flattenToolCallsNoDuplicates, "flattenToolCallsNoDuplicates");
2627
+ function copilotKitEndpoint(config2) {
2628
+ return {
2629
+ ...config2,
2630
+ type: EndpointType.CopilotKit
2631
+ };
2632
+ }
2633
+ __name(copilotKitEndpoint, "copilotKitEndpoint");
2634
+ function langGraphCloudEndpoint(config2) {
2635
+ return {
2636
+ ...config2,
2637
+ type: EndpointType.LangGraphCloud
2638
+ };
2639
+ }
2640
+ __name(langGraphCloudEndpoint, "langGraphCloudEndpoint");
2017
2641
 
2018
2642
  // src/lib/integrations/shared.ts
2019
2643
  var import_type_graphql16 = require("type-graphql");
@@ -2027,43 +2651,6 @@ var import_type_graphql11 = require("type-graphql");
2027
2651
 
2028
2652
  // src/graphql/inputs/message.input.ts
2029
2653
  var import_type_graphql3 = require("type-graphql");
2030
-
2031
- // src/graphql/types/enums.ts
2032
- var import_type_graphql2 = require("type-graphql");
2033
- var MessageRole;
2034
- (function(MessageRole2) {
2035
- MessageRole2["user"] = "user";
2036
- MessageRole2["assistant"] = "assistant";
2037
- MessageRole2["system"] = "system";
2038
- })(MessageRole || (MessageRole = {}));
2039
- var ActionExecutionScope;
2040
- (function(ActionExecutionScope2) {
2041
- ActionExecutionScope2["server"] = "server";
2042
- ActionExecutionScope2["client"] = "client";
2043
- ActionExecutionScope2["passThrough"] = "passThrough";
2044
- })(ActionExecutionScope || (ActionExecutionScope = {}));
2045
- var CopilotRequestType;
2046
- (function(CopilotRequestType2) {
2047
- CopilotRequestType2["Chat"] = "Chat";
2048
- CopilotRequestType2["Task"] = "Task";
2049
- CopilotRequestType2["TextareaCompletion"] = "TextareaCompletion";
2050
- CopilotRequestType2["TextareaPopover"] = "TextareaPopover";
2051
- CopilotRequestType2["Suggestion"] = "Suggestion";
2052
- })(CopilotRequestType || (CopilotRequestType = {}));
2053
- (0, import_type_graphql2.registerEnumType)(MessageRole, {
2054
- name: "MessageRole",
2055
- description: "The role of the message"
2056
- });
2057
- (0, import_type_graphql2.registerEnumType)(ActionExecutionScope, {
2058
- name: "ActionExecutionScope",
2059
- description: "The scope of the action"
2060
- });
2061
- (0, import_type_graphql2.registerEnumType)(CopilotRequestType, {
2062
- name: "CopilotRequestType",
2063
- description: "The type of Copilot request"
2064
- });
2065
-
2066
- // src/graphql/inputs/message.input.ts
2067
2654
  function _ts_decorate2(decorators, target, key, desc) {
2068
2655
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2069
2656
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
@@ -3720,6 +4307,7 @@ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
3720
4307
  UnifyAdapter,
3721
4308
  buildSchema,
3722
4309
  config,
4310
+ copilotKitEndpoint,
3723
4311
  copilotRuntimeNestEndpoint,
3724
4312
  copilotRuntimeNextJSAppRouterEndpoint,
3725
4313
  copilotRuntimeNextJSPagesRouterEndpoint,
@@ -3727,6 +4315,7 @@ __name(copilotRuntimeNestEndpoint, "copilotRuntimeNestEndpoint");
3727
4315
  copilotRuntimeNodeHttpEndpoint,
3728
4316
  createContext,
3729
4317
  flattenToolCallsNoDuplicates,
3730
- getCommonConfig
4318
+ getCommonConfig,
4319
+ langGraphCloudEndpoint
3731
4320
  });
3732
4321
  //# sourceMappingURL=index.js.map